The goal of this example is to show you how to serve static content from a filesystem. First, we need to import some objects:
-
Site
, anIProtocolFactory
which glues a listening server port (IListeningPort
) to theHTTPChannel
implementation:1
from twisted.web.server import Site -
File
, anIResource
which glues the HTTP protocol implementation to the filesystem:1
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:1
from twisted.internet import reactor
Then we create an instance of the Site factory with that resource:1
resource = File("/tmp")
Now we glue that factory to a TCP port:1
factory = Site(resource)
Finally, we start the reactor so it can make the program work:1
reactor.listenTCP(8888, factory)
And that's it. Here's the complete program:1
reactor.run()
1 2 3 4 5 6 7 8
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()
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 the command line twistd
tool can do. In this case,
the command
twistd -n web --path /tmpwill accomplish the same thing as the above server. See helper programs in the Twisted Core documentation for more information on using
twistd
.