Django runserver alternative using twisted.web  [Python]

Posted by tomfmason 1 year, 3 months ago 0 comments

This is a Django runserver alternative using twisted.web. I like this method as it is also production worthy. It is very useful for both production and development environments. In my opinion, it is important to develop applications using a similar environment that will be used in production. This will cut back on unforeseen problems that come as a result of a different production environment. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import os
import re
from yourproject import settings
from django.contrib import admin
from twisted.internet import reactor
from optparse import OptionParser, make_option
from django.core.handlers.wsgi import WSGIHandler
from twisted.application import internet, service
from django.core.management.base import BaseCommand
from twisted.web import server, resource, wsgi, static

class WSGIRoot(resource.Resource):
    def __init__(self, wsgi_resource):
        resource.Resource.__init__(self)
        self.wsgi_resource = wsgi_resource
    def getChild(self, path, request):
        path0 = request.prepath.pop(0)
        request.postpath.insert(0, path0)
        return self.wsgi_resource

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('-p','--port',dest='port'),
    )
    appusage = """

Usage:

./manage.py runserver -p,--port default is 8000
    """
    def handle(self,*args,**options):
        if not options['port']:
            port = 8000
        else:
            port = int(options['port'])
        wsgi_resource = wsgi.WSGIResource(reactor, reactor.getThreadPool(), WSGIHandler())
        resource = WSGIRoot(wsgi_resource)
        site_media_url = re.sub('\/|\/','',settings.MEDIA_URL)
        site_media = static.File(settings.MEDIA_ROOT, site_media_url)
        resource.putChild(site_media_url,site_media)
        #this is a bit hackish but it works :)
        admin_media_url = re.sub('\/|\/','',settings.ADMIN_MEDIA_PREFIX)
        admin_media = static.File(os.path.join(os.path.dirname(admin.__file__),"media"),admin_media_url)
        resource.putChild(admin_media_url,admin_media)
        reactor.listenTCP(port, server.Site(resource))
        reactor.run()

Comments

  • There are currently no comments
Comment
required
required (not published)
optional