HTTPServer classes

Peter Hansen peter at engcorp.com
Thu May 1 12:45:57 EDT 2003


Drazen Gemic wrote:
> 
> Few days ago I was asking for an example of using BaseHTTPServer and
> SimpleHTTPServer, and no one seems to have one. I nthe meantime I
> managed to figure out how it works. This is the example which adds a
> custom service for certain URL
> 
> import BaseHTTPServer, SimpleHTTPServer
[snip]
> httpLoop()

Just for comparison, I thought I'd try to write the rough equivalent 
using Twisted:

from twisted.internet import reactor
from twisted.web import server, static, resource


class Saluter(resource.Resource):
    isLeaf = True
    
    def render(self, request):
        return "<html><body><h1>SALUTE</h1></body></html>"
        

if __name__ == '__main__':
    root = static.File(".")	# serves any file from current dir
    root.putChild('salute', Saluter())
    
    site = server.Site(root)
    reactor.listenTCP(80, site)
    
    reactor.run()


Note: you should really not do just "httpLoop()" since that will
execute during import, even if the module is to be imported from
another module.  Instead, use the __name__ == '__main__' convention
above to ensure that it runs the code only when you are executing
the script from the command line.

-Peter




More information about the Python-list mailing list