2

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?

florin
  • 719
  • 12
  • 31
  • You should raise `cherrypy.HTTPError` or so (maybe your own error class instance, having error metadata attached). You may write custom error handlers to send JSON reply. Make [request.error_response and/or error_page.default](https://github.com/GDG-Ukraine/gdg.org.ua/blob/master/config/dev/app.yml#L138-L139) in your config point to your functions, [intercepting exceptions](https://github.com/GDG-Ukraine/gdg.org.ua/blob/master/src/GDGUkraine/errors.py#L37-L89) – webknjaz -- Слава Україні Aug 05 '16 at 16:00
  • You may try using [before_error_response/after_error_response hooks](https://cherrypy.readthedocs.io/en/latest/extend.html#hook-point) as well – webknjaz -- Слава Україні Aug 05 '16 at 16:08

1 Answers1

3

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'
Community
  • 1
  • 1
florin
  • 719
  • 12
  • 31