[Twisted-web] confusion with general web serving

L. Daniel Burr ldanielburr at mac.com
Tue Apr 17 10:20:27 CDT 2007

On Tue, 17 Apr 2007 09:57:24 -0500, Jonathan Vanasco  
<twisted-python at 2xlp.com> wrote:

> I asked this on the -python list, some suggested I re-ask here.
> I'm trying to build a small daemon that does the following:
> 	1_ parse the uri for the key to an image
> 	2_ validate that key against db
> 		3_ if not valid, render a 404
> 		4_ if valid, map to an arbitrary file on the fs  ( pulled from db )
> 		4b_ or check a bdb to see if its on the fs, pull a copy off of  
> amazon's s3 otherwise and update the cachedb to note we have it
> The issue that I'm having:
> 	i originally tried doing this based on one of the chapters in the  
> twisted o'reilley book.  i ran into issues when I tried to render an  
> image -- i couldn't figure out how to do that.
> 	somone on twisted web suggested i not use the protocol and instead use  
> site (http://twistedmatrix.com/projects/web/documentation/howto/ 
> using-twistedweb.html#auto2 ).   i ran into issues when trying to render  
> status codes and add in proxy functionality.
> I'm at a loss on what I should be using.  can someone offer advice ?

You are attacking this at too low a level, I think.  In essence you are
building a fixed-function web server, which is a waste of your time and
resources, because twisted already has a decent web server implementation.

Just make a .tac file for starters, something along these lines:



 from twisted.application import internet, service
 from twisted.python import log
 from twisted.web2 import channel, http
 from twisted.web2 import resource, responsecode, server

class Image(resource.LeafResource):
     def __init__(self, key):
         self.key = key

     def render(self, request)
         # Locate the image, return some kind
         # of http.Response, or a defer.Deferred

class Root(resource.Resource):
     addSlash = True

     def childFactory(self, request, name):
         return Image(name)

     def render(self, request):
         return http.Response(

root = Root()
site = server.Site(root)
port = 8080
application = service.Application('ImageServer')
svc = internet.TCPServer(port, channel.HTTPFactory(site))


Run the above with twistd -noy webserver.tac.  This should be
sufficient to get you started.

Hope this helps,

L. Daniel Burr

More information about the Twisted-web mailing list