Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

WhatsNewIn22: middleware_demo.py

Line 
1 """
2 This is an example of a way to use WSGI middleware with
3 CherryPy 2.2.
4
5 This example requires EvalException from Paste.
6 """
7
8 import sys
9
10 import cherrypy
11 from cherrypy._cpwsgi import wsgiApp, CPHTTPRequest
12 from cherrypy._cpwsgiserver import CherryPyWSGIServer
13
14 from paste.evalexception.middleware import EvalException
15
16 # we need a WSGI server class that accepts a WSGI application
17 # as a parameter to its constructor - here is an example
18
19 class SimpleWSGIServer(CherryPyWSGIServer):
20     """A WSGI server that accepts a WSGI application as a parameter."""
21     RequestHandlerClass = CPHTTPRequest
22    
23     def __init__(self, wsgi_app):
24         conf = cherrypy.config.get
25         bind_addr = (conf("server.socket_host"), conf("server.socket_port"))
26         CherryPyWSGIServer.__init__(self, bind_addr, wsgi_app,
27                                     conf("server.thread_pool"),
28                                     conf("server.socket_host"),
29                                     request_queue_size = conf("server.socket_queue_size"),
30                                     )
31
32
33 # here is a sample CherryPy root class
34 # we are using exception catching middleware in this example,
35 # so the "problem" page handler purposely generates an error
36 # to demonstrate the middleware
37
38 class Root(object):
39     @cherrypy.expose
40     def index(self):
41         yield "Get in <a href='/problem'>trouble</a><br>"
42         yield cherrypy.request.browser_url + '<br>'
43         yield cherrypy.request.path + '<br>'
44         yield cherrypy.request.object_path + '<br>'
45
46     @cherrypy.expose
47     def problem(self):
48         "error on purpose to show off EvalException"
49         assert 0, "Houston, we have a problem."
50
51 # we need this so that errors trickle down to the middleware
52 cherrypy.config.update({'server.throw_errors':True})
53
54 # mount our CherryPy
55 cherrypy.root = Root()
56
57 # wrap the CP wsgiApp in the middleware
58 app = EvalException(wsgiApp, global_conf={})
59
60 # init the custom server with the middleware
61 mw_server = SimpleWSGIServer(app)
62
63 # start CherryPy with the custom server
64 cherrypy.server.start(server=mw_server)
65

Hosted by WebFaction

Log in as guest/cpguest to create tickets