Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

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

This comment has been minimized.

Copy link

joemarct commented Jun 29, 2015

For Django 1.7 and higher, the following is necessary:

import django
django.setup()

Do that before importing django.conf.settings.

@stephansemerad

This comment has been minimized.

Copy link

stephansemerad commented Sep 8, 2016

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

@NothingxFluctuation

This comment has been minimized.

Copy link

NothingxFluctuation commented Dec 28, 2017

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

@satyadasari44

This comment has been minimized.

Copy link

satyadasari44 commented Jul 9, 2018

where do i use this code..?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.