#2024: Using CherryPy Filters to handle the same parameter on each controller
method
---------------------------+------------------------------------------------
Reporter: exhuma | Owner: Chris Arndt
Type: task | Status: new
Priority: normal | Milestone:
Component: Documentation | Version: 1.0
Severity: normal | Keywords: doc request
---------------------------+------------------------------------------------
I was not able to find a proper section in the documentation pages, so I
decided to open a ticket :/ You could consider this a recipe/howto. I hope
it will make it into the official/rough docs. It took me quite some time
to find the appropriate pointers/hints on how to work with filters....
= Problem =
You want to add the same GET/POST parameter to '''each''' controller
method, but using {{{**kwargs}}} is cumbersome. Imagine you want to be
able to change the "skin" variable on any controller.
= Solution =
Using CherryPy filters you can intercept the request before it reaches the
controller method and add/remove parameters from the request object. You
could then, for example, put this request into the session.
So:
1. Write a CherryPy filter
1. Append the filter to a controller. Note that the filter is also
active for all controllers inside that controller!
== The Filter class ==
{{{
#!python
from cherrypy.filters.basefilter import BaseFilter
from cherrypy import request, session
class SkinFilter(BaseFilter):
"""
If the request parameters contain a "skin" variable, pull it out the
request
and put it into the session
"""
__detected_skin = None
def before_request_body(self):
try:
if "skin" in request.params:
skin = request.params.pop("skin")
if skin is not None:
self.__detected_skin = skin
except Exception, e:
log.warning( "Error in %s:\n%s" % (self.__class__.__name__,
str(e)) )
def before_main(self):
if self.__detected_skin is not None:
session['skin'] = self.__detected_skin
}}}
== Adding it to the controller ==
{{{
#!python
...
class Root(controllers.RootController):
# attach cherrypy filters
_cp_filters = [SkinFilter()]
...
}}}
The filter could also be attached to non-root controllers so only parts of
you application handles those requests.
--
Ticket URL: <http://trac.turbogears.org/ticket/2024>
TurboGears <http://www.turbogears.org/>
TurboGears front-to-back web development
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "TurboGears Tickets" group.
This group is read-only. No posting by normal members allowed.
To unsubscribe from this group, send email to
[EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/turbogears-tickets?hl=en?hl=en
-~----------~----~----~----~------~----~------~--~---