Skip to content

Instantly share code, notes, and snippets.

@nigma
Created December 20, 2012 22:44
Show Gist options
  • Save nigma/4349257 to your computer and use it in GitHub Desktop.
Save nigma/4349257 to your computer and use it in GitHub Desktop.
Serving Django with CherryPy
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import webbrowser
from threading import Timer
os.environ["DJANGO_SETTINGS_MODULE"] = "webapp.settings"
import cherrypy
from django.conf import settings
from django.core.handlers.wsgi import WSGIHandler
class DjangoApplication(object):
HOST = "127.0.0.1"
PORT = 8001
def mount_static(self, url, root):
"""
:param url: Relative url
:param root: Path to static files root
"""
config = {
'tools.staticdir.on': True,
'tools.staticdir.dir': root,
'tools.expires.on': True,
'tools.expires.secs': 86400
}
cherrypy.tree.mount(None, url, {'/': config})
def open_browser(self):
Timer(3, webbrowser.open, ("http://%s:%s" % (self.HOST, self.PORT),)).start()
def run(self):
cherrypy.config.update({
'server.socket_host': self.HOST,
'server.socket_port': self.PORT,
'engine.autoreload_on': False,
'log.screen': True
})
self.mount_static(settings.STATIC_URL, settings.STATIC_ROOT)
cherrypy.log("Loading and serving Django application")
cherrypy.tree.graft(WSGIHandler())
cherrypy.engine.start()
self.open_browser()
cherrypy.engine.block()
if __name__ == "__main__":
print "Your app is running at http://localhost:8001"
DjangoApplication().run()
@behudson
Copy link

behudson commented Jan 7, 2015

Thank you for this code! I added the following and now my app runs on https only with cherrypy:
line 9:
tdir = os.path.abspath(os.path.dirname(file))
inserted between lines 38 and 39:
'server.ssl_module': 'builtin',
'server.ssl_certificate': os.path.join(tdir, 'ssl_cert.pem'),
'server.ssl_private_key': os.path.join(tdir, 'ssl_key.pem'),

@joemarct
Copy link

For Django 1.7 and higher, the following is necessary:

import django
django.setup()

Do that before importing django.conf.settings.

@stephansemerad
Copy link

Is there any explanation on how to use this at all? I am lost.

@NothingxFluctuation
Copy link

what about static files (css, js, images etc) ?

@satyadasari44
Copy link

where do i use this code..?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment