Search code examples
pythonjsoncherrypy

Return json from cherrypy before_handler tool


I have a cherrypy application in which I've implemented a custom tool( a request filter) that I've attached to before_handler hook. Bellow is the filter implementation:

def custom_filter():
    method = cherrypy.request.method
    if method == 'POST':
        print 'check POST token'
        try:
            request_headers = cherrypy.request.headers
            token = request_headers['Authorization']
            if not _auth.validate_token(token):
                    return 'error message'
        except:
            print 'Error in post filter'

What I want is to return a message to the client if the token is invalid. The return statement is not working. Is it possible to do this? If not, is there an alternative?


Solution

  • Based on this post and after some investigations I found a solution that works for me: stop the execution of the request and then add a response body.

    def custom_filter():
    method = cherrypy.request.method
    if method == 'POST':
        print 'check POST token'
        try:
            request_headers = cherrypy.request.headers
            token = request_headers['Authorization']
            if not _auth.validate_token(token):
                    cherrypy.request.handler = None # stop request
                    cherrypy.response.status = 403 
                    cherrypy.response.body = 'test'  # add response message
    
        except:
            print 'Error in post filter'