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 + validators
  • validate_on_submit()
  • form.hidden_tag() includes token
  • CSRFProtect for global protection

More most-asked Flask questions

← All Flask questions