问题
I want to be able to catch the arguments of the methods of my CherryPy application before the method itself. But I'm not sure if there is a way to do it in CherryPy or with standard python. It should look something like this:
HTTP Request --> Parser to catch the arguments --> CherryPy who passes the request to method
My goal is to capture the input and output to a server without disturbing the code in the method itself.
Also, how can you redirect the request to a CherryPy server to other CherryPy servers?
回答1:
Here is how I check post methods for a valid csrf token our server generates.
def check_token(self=None):
# whenever a user posts a form we verify that the csrf token is valid.
if cherrypy.request.method == 'POST':
token = cherrypy.session.get('_csrf_token')
if token is None or cherrypy.request.params.get('csrf_token') == None or token != cherrypy.request.params['csrf_token']:
raise cherrypy.HTTPError(403)
cherrypy.tools.Functions = cherrypy.Tool('before_handler', check_token)
Hope this helps!
回答2:
The standard Python way of handling HTTP requests is WSGI. WSGI allows stacking the processing components called WSGI middleware. That is where you can modify requests before they get to the framework's internals. CherryPy is WSGI-compliant, so the middleware can be used with it.
However, CherryPy is more than just a framework, it is also a web server. If you're using it as a server, it's most likely a cherrypy.quickstart()
call. To add a middleware, it needs to have some more coding to build a site "tree" producing a WSGI app and to connect the app to the CherryPyWSGIServer
class. This article seems to be explaining it well. As usual however, I recommend using uWSGI for running Python WSGI applications instead of CherryPy's built-in server. It has tons of features and overcomes GIL issue.
Additionally you could use page handlers / tools to manipulate requests before they are actually processed. See docs.
来源:https://stackoverflow.com/questions/19920137/cherrypy-how-to-process-a-request-before-it-has-reached-the-application-method