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

Ticket #455: app_with_middleware.py

Line 
1 """This example requires EvalException from Paste and
2 Allan Saddi's session middleware.
3 """
4
5 import sys
6
7 import cherrypy
8
9 try:
10     from paste.evalexception.middleware import EvalException
11     from paste.lint import middleware as lint_middleware
12 except ImportError:
13     print "Please install paste 0.4.2 or the latest Paste development code."
14     print "(hint: easy_install -U Paste==dev)"
15     sys.exit(1)
16 try: 
17     from session import SessionMiddleware, MemorySessionStore
18 except ImportError:
19     print """The middleware session example is only available with
20     Alan Saddi's session middlware on your python path.
21     http://www.saddi.com/software/py-lib/#Session
22     """
23     sys.exit(1)
24
25 # wrapper for session middleware
26 def session_middleware(app, store=None):
27     return SessionMiddleware(store, app)
28
29 class Root(object):
30     @cherrypy.expose
31     def index(self):
32         yield "Some things are cool and some things are awesome<br>"
33         yield "Get in <a href='/problem'>trouble</a><br>"
34         yield "Middleware <a href='tracker'>sessions</a><br>"
35         yield cherrypy.request.browser_url + '<br>'
36         yield cherrypy.request.path + '<br>'
37         yield cherrypy.request.object_path + '<br>'
38
39     @cherrypy.expose
40     def problem(self):
41         "error on purpose to show off EvalException"
42         assert 0, "Houston, we have a problem."
43
44     @cherrypy.expose
45     def tracker(self):
46         env = cherrypy.request.wsgi_environ.get
47         session = env('com.saddi.service.session').session
48         count = session.get('count', 0) + 1
49         session['count'] = count
50         return "You have been here %s times." % count
51
52 # we need this so that errors trickle down to the middleware
53 cherrypy.config.update({'server.throw_errors':True})
54
55 # mount our CherryPy apps
56 cherrypy.root = Root()
57 cherrypy.root.toor = Root()
58
59 # create our middleware "stack"
60 # (a list of middleware that will chain together with
61 # each other and finally CP
62 mw = [(EvalException, {'global_conf':dict()}),
63       # there is a problem with [wsgi.input] in CP that lint hangs on
64       # (lint_middleware, {}),
65       (session_middleware, {'store':MemorySessionStore()}),
66       ]
67
68 # start the server with the middleware stack
69 cherrypy.server.start(middleware=mw)
70

Hosted by WebFaction

Log in as guest/cpguest to create tickets