Flask interview question · Most asked
How do Flask-WTF forms and CSRF protection work?
Summary
Flask-WTF integrates WTForms: define a FlaskForm with fields and validators, call form.validate_on_submit() in the view, and render {{ form.hidden_tag() }} to include the CSRF token, which is validated automatically.
Longer Answer
CSRFProtect(app) enables CSRF checks globally, including for non-WTForms POSTs (send the token in a header for AJAX). Disable CSRF in tests via WTF_CSRF_ENABLED = False. For JSON APIs authenticated by headers rather than cookies, CSRF isn't needed.
Key Points
FlaskForm+ validatorsvalidate_on_submit()form.hidden_tag()includes tokenCSRFProtectfor global protection
More most-asked Flask questions
- How do you access request data and build responses in Flask?
- How do Flask sessions work and what are their security implications?
- What is the application factory pattern in Flask and why use it?
- What is Flask and what does 'microframework' mean?
- Explain Flask's application context and request context.
- What are Blueprints in Flask?
- How does routing work in Flask, including variable rules and HTTP methods?
- How do you use SQLAlchemy with Flask (Flask-SQLAlchemy 3.x)?