Skip to content

Instantly share code, notes, and snippets.

@whiteinge
Last active October 30, 2021 00:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save whiteinge/9906785 to your computer and use it in GitHub Desktop.
Save whiteinge/9906785 to your computer and use it in GitHub Desktop.
A not-so-simple but minimal example of a CherryPy app.
#!/usr/bin/env python
# coding: utf-8
'''
A minimal but thorough example of a CherryPy app.
'''
import cherrypy
class Root(object):
@cherrypy.expose
def index(self):
'''
"index" is a special-case that gets mapped to the root URL.
"default" is another special-case that can be used as a fall-back
(think 404).
'''
return 'What up, yo?'
@cherrypy.expose
def other_url(self, *args, **kwargs):
'''
The name of the method is mapped to the URL. This url is /other_url
Try calling this with /other_url/some/path
Try calling this with /other_url?foo=Foo&bar=Bar
Try calling this with POST data.
'''
return '''\
Any sub-paths on the URL are available as args: {0}
Query params _and_ POST data is available via kwargs: {1}
Headers and the HTTP method and everything else is available via
the thread-local cherrypy objects ``cherrypy.request`` and
``cherrypy.response``.
You can get and set session values and cookies as though they are
dictionaries:
cherrypy.session['key'] = 'val'
cherrypy.request.cookie['key'] = 'val'
cherrypy.session.get('key', 'defaultval')
cherrypy.request.cookie.get('key', 'defaultval')
'''.format(args, kwargs)
if __name__ == '__main__':
conf = {
'global': {
'server.socket_host': '0.0.0.0',
'server.socket_port': 8000,
# Remove this to auto-reload code on change and output logs
# directly to the console (dev mode).
'environment': 'production',
},
'/': {
'tools.sessions.on': True,
'tools.sessions.timeout': 60 * 10, # hours
# The default session backend is in RAM. Other options are 'file',
# 'postgres', 'memcached'. For example, uncomment:
# 'tools.sessions.storage_type': 'file',
# 'tools.sessions.storage_path': '/tmp/mysessions',
},
}
# Start the server with the above app and the above config.
cherrypy.quickstart(Root(), '/', conf)
# If you want to use a different WSGI server, use mount() instead of
# quickstart(). The return from mount is a regular WSGI app that mod_wsgi
# (et al) can run.
# cherrypy.tree.mount(Root(), '/', conf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment