Skip to content

Instantly share code, notes, and snippets.

@k4ml
Created March 5, 2017 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k4ml/cc2535f55f4444ede16e455d30e24d4f to your computer and use it in GitHub Desktop.
Save k4ml/cc2535f55f4444ede16e455d30e24d4f to your computer and use it in GitHub Desktop.
Python web programming with cherrypy

This assuming you are on Linux or OSX machine. Make sure python version is 3.5 and above.

Create your project directory, let say we're building application named webby:-

mkdir webby
cd webbpy

Create new virtualenv that will be the PYTHON that we will use going forward in this project:-

python3 -mvenv venv

Now we should have PYTHON that we can use for our project. Let's try to run it:-

venv/bin/python

Try to run the following code:-

>>> import sys
>>> sys.path
['', '/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python35.zip', '/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload', '/Users/kamal/python/webby/venv/lib/python3.5/site-packages']

Now let's install cherrypy into our venv:-

venv/bin/pip install cherrypy

Let's verify cherrypy was installed:-

venv/bin/python
import cherrypy
cherrypy
>>> cherrypy
<module 'cherrypy' from '/Users/kamal/python/webby/venv/lib/python3.5/site-packages/cherrypy/__init__.py'>

Notice where cherrypy come from above - /Users/kamal/python/webby/venv/. This is our project directory, right ?

Now let's create our first cherrypy app. Open file named app.py and add the following code:-

import cherrypy
	  
class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())

Run the app:-

venv/bin/python app.py
[05/Mar/2017:16:05:01] ENGINE Listening for SIGHUP.
[05/Mar/2017:16:05:01] ENGINE Listening for SIGUSR1.
[05/Mar/2017:16:05:01] ENGINE Listening for SIGTERM.
[05/Mar/2017:16:05:01] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.

[05/Mar/2017:16:05:01] ENGINE Started monitor thread '_TimeoutMonitor'.
[05/Mar/2017:16:05:01] ENGINE Started monitor thread 'Autoreloader'.
[05/Mar/2017:16:05:01] ENGINE Serving on http://127.0.0.1:8080
[05/Mar/2017:16:05:01] ENGINE Bus STARTED
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment