Forums

The CSRF tokens do not match.

HI - I am getting the above message in my error log. How can I determine which route caused it please? And is there a way to add a handler for this error so I can present a nicer page to the user?

Thanks

Paul

With most web frameworks I'd expect the error message to mention which route it was, but it sounds like that's not happening for you. Which web framework are you using?

Hi - I am using Flask.

Thanks

Paul

Do you have debug switched off? It might help to switch it on temporarily, at least while trying to track down the cause of this issue. Alternatively, if you're using Flask-WTF for your form handling (which would be the most common way of making your Flask app do CSRF protection) then you could look into using its handle_csrf_error hook -- that would allow you to return a nice user-friendly error page, and also to log what is causing the problem manually.

Awesome - thank you.

One further question....

I can use @csrf.exempt to exempt a function/route on my flask_app.py file. However I have blueprints, and would like to exempt a function/route from one of those blueprints. As csrf is not defined in the blueprint .py file, how can I use the @csrf.exempt decorator in that blueprint .py file please?

Thanks

Paul

The Flask-WTF docs explain how -- see the bottom of that page.

Hi Giles - thank you for your response. I appreciate this is a Flask issue, and not pythonanywhere, but I cannot find the answer anywhere.

"The Flask-WTF docs explain how -- see the bottom of that page." - that page does not show how to exempt a single route from a blueprint - it only shows how to exempt all the routes from a blueprint. I want to exempt a single view from a blueprint, however the @csrf.exempt decoration doesn't work in the blueprint, as crsf is not definted.

Thanks

Paul

I don't use Blueprints myself, but as far as I can tell from this GitHub issue you just need to use the csrf.exempt decorator inside the blueprint file. The trick is, as you say, making it available there, but it looks like you can import it from your main app module.

Ah, perfect - thank you for the excellent support.

Paul

No problem, glad to help!