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:
Site, a factory which glues a listening server port to the HTTP protocol implementation:
from twisted.web.server import Site
File, a resource which glues the HTTP protocol implementation to the filesystem:
from twisted.web.static import File
The reactor, which drives the whole process, actually accepting TCP connections and moving bytes into and out of them:
from twisted.internet import reactor
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:
reactor.run()
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)
reactor.run()
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.