How to disable csrf protection for particular routes in Flask-wtf


security

Flask-wtf recommends using @csrf.exempt to disable csrf protection for particular routes as in the case of APIs.

Now this is pretty confusing. What does csrf refers to?

If you inspect Flask-wtf you do see a csrf attribute

>>> import flask_wtf
>>> dir(flask_wtf)
['CSRFProtect', 'CsrfProtect', 'FlaskForm',
'Form', 'Recaptcha', 'RecaptchaField', 
'RecaptchaWidget', '__builtins__', '__cached__', 
'__doc__', '__file__', '__loader__', 
'__name__', '__package__', '__p
ath__', 
'__spec__', '__version__', '_compat', 
'absolute_import', 'csrf', 'fields', 
'form', 'recaptcha', 'validators', 
'widgets']
>>>

But it does not mean the above. It means what you defined as csrf.

from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()

@some_blueprint.route("/myendpoint", methods=['POST'])
@csrf.exempt
def myfunc():
    pass

Written by

Abdur-Rahmaan Janhangeer

Chef

Python author of 7+ years having worked for Python companies around the world

Suggested Posts

Securing Flask: Preventing Open Redirect Vulnerabilities

If your Flask application uses a next parameter to redirect users after login, you might be vulnerab...

Read article

How to correctly use the next parameter in login and logout in Flask

Here is a sample login and logout route taken from the shopyo web framework. You can learn here how ...

Read article

How to run a Flask Linux-only App on Windows - The AFPy Site

There are in the Python world many Flask Linux-only apps. However in many case, with some twerking w...

Read article
Free Flask Course