watch this The wheels are turning, slowly turning. home
Twisted Web in 60 seconds: serve static content from a directory 2009-09-16

Welcome to the first installment of “Twisted Web in 60 seconds”. The goal of this installment is to show you how to serve static content from a filesystem using some APIs from Twisted Web (while Twisted also includes some command line tools, I will not be discussing those here) and have you understand it in 60 seconds or less (if you don’t already know Python, you might want to stop here). Where possibly useful, I’ll include links to the Twisted documentation, but consider these as tips for further exploration, not necessary prerequisites for understanding the example. So, let’s dive in.

First, we need to import some things:

Next, we create an instance of the File resource pointed at the directory to serve:

    resource = File("/tmp")

Then we create an instance of the Site factory with that resource:

    factory = Site(resource)

Now we glue that factory to a TCP port:

    reactor.listenTCP(8888, factory)

Finally, we start the reactor so it can make the program work:

And that’s it.

Here’s the complete program without annoying explanations:

from twisted.web.server import Site
from twisted.web.static import File
from twisted.internet import reactor

resource = File('/tmp')
factory = Site(resource)
reactor.listenTCP(8888, factory)

The Twisted site has more web examples, as well as some longer form style documentation.

Bonus example! For those times when you don’t actually want to write a new program, the above implemented functionality is one of the things which the command line twistd tool can do. In this case, the command twistd -n web –path /tmp will accomplish the same thing as the above server.

Keep an eye out of the next installment, in which I’ll describe simple dynamic resources.