Login

Simple twisted replacement for runserver

Author:
tomfmason
Posted:
October 21, 2010
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

This is an extremely simple example but from here the possibilities are almost endless :)

 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()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.