Search code examples
pythonhttprequestcherrypy

CherryPy: How to process a request before it has reached the application method?


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.


Solution

  • 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!