Welcome, guest | Sign In | My Account | Store | Cart

A simple integration of a CherryPy web server, using Quixote template publishing, managed in its own thread.

Using CherryPy as a web server is a good move because it fixes problems on Windows shutting down a call to serve_forever. This example extends the CherryPy capability by running it in a seperate thread. Further extension comes from Quixote, for templating HTML.

One thing I like about this snippet of code is its simplicity. And the fact that it solves a large number of design problems, all in one shot.

Python, 42 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from BaseHTTPServer import *
from cherrypy._cphttpserver import CherryHTTPServer
from contrib.quixote.server.simple_server import HTTPRequestHandler
from threading import Thread,Event

class HTTPServerPlus(CherryHTTPServer, Thread):
    
    def __init__(self, **kwargs):
        CherryHTTPServer.__init__(self,**kwargs)
        Thread.__init__(self)

    def run(self):
        self.serve_forever()

    def join(self,timeout=None):
        self.shutdown()
        Thread.join(self, timeout)


from contrib.quixote.publish import Publisher

def create_publisher():
    from quixote.demo.root import RootDirectory
    return Publisher(RootDirectory(), display_exceptions='plain')

class TemplateServer(HTTPServerPlus):

    def __init__(self, port):
        HTTPServerPlus.__init__(self,server_address=('', port), RequestHandlerClass=HTTPRequestHandler)
        self.server_port = port
        self.server_name = 'My Local Server'
        create_publisher()
        self.start()


if __name__=='__main__':
    server = TemplateServer(8800)
    try:
        while 1: pass
    except KeyboardInterrupt:
        print 'Got Ctrl-C...'
        server.join(1.0)

If you're trying to put together a web application in Python that needs to run on Windows, you need to deal with the matter of web server shutdown. The baseline Python experience for this is not good.

My needs were running quixote off a web server running in a separate thread on Windows. If your needs are similar, or you want to learn about integrating these technologies, this example may help you.

Good Luck.

2 comments

Christopher Smith 18 years, 10 months ago  # | flag

edit. s/One this/One thing/

Jonathan Kolyer (author) 18 years, 6 months ago  # | flag

D'oh. Dang it. My kingdom for a spell check!