<<TableOfContents(2)>>

## page was renamed from CherryPy
= CherryPy =
Pythonic, object-oriented web framework

http://www.cherrypy.org/

== Install on Slackware 14 ==
{{{#!highlight bash
wget https://pypi.python.org/packages/source/C/CherryPy/CherryPy-3.2.4.tar.gz
cp CherryPy-3.2.4.tar.gz /tmp
cd /tmp
tar xvzf CherryPy-3.2.4.tar.gz
cd CherryPy-3.2.4
python setup.py build
python setup.py install
}}}

== Check installation ==
{{{#!highlight python
# python
# Python 2.7.3 (default, Jul  3 2012, 21:16:07) 
# [GCC 4.7.1] on linux2
# Type "help", "copyright", "credits" or "license" for more information.
import cherrypy
cherrypy.__version__
# '3.2.2'
quit()
}}}

== CherryPy test web app ==

Create folder the web app
{{{#!highlight bash
mkdir -p /var/www/htdocs/cherrypytest/static
}}}

Create file '''/var/www/htdocs/cherrypytest/cherrypytest.wsgi'''

{{{#!highlight python
import sys
sys.stdout = sys.stderr
import cherrypy

cherrypy.config.update({'environment': 'embedded'})

class HelloWorld(object):
    @cherrypy.expose
    def index(self):
        return "Hello World CherryPy!!!!"

    @cherrypy.expose
    def add(self,param1,param2):
       return str( int(param1)+int(param2) )

    @cherrypy.expose
    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def hellojson(self): 
        #  curl -X POST -d "{\"name\":\"jkl\"}" http://localhostcherrypytest/hellojson --header "Content-Type:application/json"
        inj = cherrypy.request.json
        return {"message": "hello world " + inj['name'] }

hello = HelloWorld()    
#static dir
confx={'/static': {'tools.staticdir.on':True ,
                  'tools.staticdir.dir':'/var/www/htdocs/cherrypytest/static',
                  'tools.gzip.on': True, 
                  'tools.gzip.mime_types': ['text/*', 'application/*'
                  }}

application = cherrypy.Application(hello, script_name=None, config=confx)
}}}

Create static file
{{{#!highlight bash
echo "Static Test" > /var/www/htdocs/cherrypytest/static/a.txt 
}}}

Create entry in /etc/httpd/vhosts.conf
{{{#!highlight xml
<VirtualHost *:80>
    ServerName localhostcherrypytest
    DocumentRoot "/var/www/htdocs/cherrypytest"
    WSGIScriptAlias / /var/www/htdocs/cherrypytest/cherrypytest.wsgi
    <Directory "/var/www/htdocs/cherrypytest">
      Require local
    </Directory>
</VirtualHost>
}}}

Add entry in /etc/hosts
 * 127.0.0.1 localhostcherrypytest

Restart apache
{{{#!highlight bash
/etc/rc.d/rc.httpd restart
}}}

Open the following URLs:
 * http://localhostcherrypytest/
 * http://localhostcherrypytest/add/3/4
 * http://localhostcherrypytest/static/a.txt

== CherryPy configuration location ==
In Slack14 is in 
 * /usr/lib/python2.7/site-packages/CherryPy-3.2.2-py2.7.egg/cherrypy/_cpconfig.py

Inside the file look for Config.environments .
Run python interactively to check the environments
{{{#!highlight python
import cherrypy
envs= cherrypy._cpconfig.environments #dictionary
envs['embedded']
# {'checker.on': True, 'engine.SIGTERM': None, 'request.show_mismatched_params': True, 'request.show_tracebacks': True, 'engine.autoreload_on': False, 'tools.log_headers.on': True, 'log.screen': True, 'engine.SIGHUP': None}
envs['production']
# {'request.show_tracebacks': False, 'log.screen': False, 'request.show_mismatched_params': False, 'checker.on': False, 'engine.autoreload_on': False, 'tools.log_headers.on': False}
}}}

Open URL  http://localhostcherrypytest/add/1/2a with environment embedded will show a traceback.

To disable the traceback add the follow inside the class HelloWorld
{{{#!highlight python
class HelloWorld(object):
    _cp_config = {'request.show_tracebacks': False}
    @cherrypy.expose
    def index(self):
        return "Hello World CherryPy!!!!"
    @cherrypy.expose
    def add(self,param1,param2):
       return str( int(param1)+int(param2) )
}}}

== Templating ==
Check [[Python/Jinja2]]

== REST ==
https://cherrypy.readthedocs.org/en/3.2.6/progguide/REST.html

REST quick tips: http://www.restapitutorial.com/lessons/restquicktips.html

== Install python 3.8.5 in raspberry py ==
{{{#!highlight bash
tar xvzf Python-3.8.5.tgz 
cd Python-3.8.5/
./configure 
make clean
make
make install
sudo make install
/usr/local/bin/python3.8 -v
/usr/local/bin/pip3.8 install cherrypy
}}}

== Console app ==
 * http://localhost:8080/middle/goodbye/
 * http://localhost:8080/middle
 * http://localhost:8080/
{{{#!highlight bash
pip install cherrypy routes --user
python main.py
}}}
{{{#!highlight python
import cherrypy
import wsgiref.handlers

class RootUrl:
  @cherrypy.expose
  def index(self):
    return "Hello world!"

class Middle:
  @cherrypy.expose
  def index(self):
    return "middle"

class GoodbyeWorld:
   @cherrypy.expose
   def index(self,num=None):
     return "Goodbye World!"

def main():
  ru = RootUrl()
  ru.middle = Middle()
  ru.middle.goodbye  = GoodbyeWorld()
  cherrypy.server.socket_host = '0.0.0.0'
  cherrypy.quickstart(ru) 

if __name__ == '__main__':
  main()
}}}

== Docker + cherrypy + ubuntu ==
{{{#!highlight bash
# build.sh 
docker build -t test1-image .
mkdir mnt_data
docker run -p 8181:8080 -d --rm --mount type=bind,source="$(pwd)"/mnt_data,target=/mnt/data test1-image
# what is written in the folder /mnt/data located in the container is shared in the folder mnt_data
docker run -p 8282:8080 -d --rm \
  --mount type=bind,source="$(pwd)"/mnt_data,target=/mnt/data \
  test1-image
ab -n 10000 -c 10 http://localhost:8181/ &
ab -n 10000 -c 10 http://localhost:8282/ &
tail -f mnt_data/filex.log
}}}

{{{#!highlight bash
cd ~
cd Documents
mkdir test-cherrypy
cd test-cherrypy
docker build -t test1-image .
docker run -p 8181:8080 -d --rm test1-image # expose internal port 8080 to 8181
curl localhost:8181
docker exec -it 94af745958fa bash
# edit main.py to change return message
curl localhost:8181/middle/goodbye/
docker stop 94af745958fa
}}}

=== Dockerfile ===
{{{#!highlight bash
FROM ubuntu:latest
RUN apt update
RUN apt install -y nano vim python curl
RUN curl https://bootstrap.pypa.io/pip/2.7/get-pip.py > get-pip.py
RUN python get-pip.py
RUN pip install cherrypy routes --user
RUN mkdir /app
COPY . /app/
WORKDIR /app
CMD ["python","main.py"]
}}}

=== main.py ===
{{{#!highlight python
import cherrypy
import wsgiref.handlers
import time
import socket 

class RootUrl:
  @cherrypy.expose
  def index(self):
    f=open('/mnt/data/filex.log','a')
    f.write('%s %f\n'%( socket.gethostname(),  time.time()))
    f.close()
    return "Hello world ola mundo"

class Middle:
  @cherrypy.expose
  def index(self):
    return "middle"

class GoodbyeWorld:
   @cherrypy.expose
   def index(self,num=None):
     return "Goodbye World!"

def main():
  ru = RootUrl()
  ru.middle = Middle()
  ru.middle.goodbye  = GoodbyeWorld()
  cherrypy.server.socket_host = '0.0.0.0'
  cherrypy.quickstart(ru) 

if __name__ == '__main__':
  main()
}}}