Created
June 11, 2019 21:21
-
-
Save jacqueswww/8ecb89fd908ba46bcd7b7347b11b665c to your computer and use it in GitHub Desktop.
Quick Cherrpy Hosting of a Django App
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import os | |
import webbrowser | |
from threading import Timer | |
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<app_name>.settings") | |
import cherrypy | |
import django | |
django.setup() | |
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() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment