Form rendering, validation, and CSRF protection for Flask with WTForms.
npx @tessl/cli install tessl/pypi-flask-wtf@1.2.0Flask-WTF is a Flask extension that provides simple integration between Flask and WTForms. It offers essential web form functionality including CSRF (Cross-Site Request Forgery) protection, secure file upload handling with validation, reCAPTCHA integration for bot protection, and seamless form rendering with automatic CSRF token generation. The library extends WTForms with Flask-specific features like request data binding, session-based CSRF tokens, and integration with Flask's application context.
pip install Flask-WTFfrom flask_wtf import FlaskForm, CSRFProtectSpecific functionality imports:
from flask_wtf import FlaskForm, CSRFProtect, RecaptchaField
from flask_wtf.csrf import generate_csrf, validate_csrf
from flask_wtf.file import FileField, FileRequired, FileAllowed, FileSize
from flask_wtf.recaptcha import Recaptcha, RecaptchaWidgetfrom flask import Flask, render_template, request, redirect
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
# Enable CSRF protection globally
csrf = CSRFProtect(app)
class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST'])
def index():
form = MyForm()
if form.validate_on_submit():
name = form.name.data
return f'Hello {name}!'
return render_template('form.html', form=form)
# Template (form.html)
# <form method="POST">
# {{ form.hidden_tag() }} <!-- Includes CSRF token -->
# {{ form.name.label }} {{ form.name() }}
# {{ form.submit() }}
# </form>Flask-WTF extends WTForms with Flask-specific integrations:
Comprehensive Cross-Site Request Forgery protection with automatic token generation, validation, and Flask request integration. Provides both global application protection and manual token handling for custom scenarios.
class CSRFProtect:
"""Enable CSRF protection globally for a Flask app."""
def __init__(self, app=None): ...
def init_app(self, app): ...
def exempt(self, view): ...
def protect(self): ...
def generate_csrf(secret_key: str = None, token_key: str = None) -> str:
"""Generate a CSRF token. The token is cached for a request."""
def validate_csrf(data: str, secret_key: str = None, time_limit: int = None, token_key: str = None):
"""Validate a CSRF token."""Flask-integrated form processing with automatic request data binding, validation, and CSRF token management. Provides enhanced form capabilities beyond basic WTForms functionality.
class FlaskForm(Form):
"""Flask-specific subclass of WTForms Form with CSRF protection."""
def __init__(self, formdata=_Auto, **kwargs): ...
def is_submitted(self) -> bool:
"""Consider the form submitted if method is POST, PUT, PATCH, or DELETE."""
def validate_on_submit(self, extra_validators=None) -> bool:
"""Call validate() only if the form is submitted."""
def hidden_tag(self, *fields):
"""Render the form's hidden fields in one call."""
# Re-exported from WTForms for convenience
Form = wtforms.Form # Base WTForms Form classSecure file upload handling with Werkzeug integration, providing specialized file fields and comprehensive validation including file type restrictions, size limits, and presence checking.
class FileField:
"""Werkzeug-aware file upload field."""
def process_formdata(self, valuelist): ...
class MultipleFileField:
"""Multiple file upload field (added in v1.2.0)."""
def process_formdata(self, valuelist): ...
class FileRequired:
"""Validates that uploaded file(s) are present."""
def __init__(self, message=None): ...
class FileAllowed:
"""Validates that uploaded file(s) have allowed extensions."""
def __init__(self, upload_set, message=None): ...
class FileSize:
"""Validates that uploaded file(s) are within size limits."""
def __init__(self, max_size: int, min_size: int = 0, message=None): ...
# Convenience aliases
file_required = FileRequired
file_allowed = FileAllowed
file_size = FileSizeComplete Google reCAPTCHA integration with form fields, validation, and widget rendering. Provides bot protection for forms with configurable reCAPTCHA parameters and error handling.
class RecaptchaField(Field):
"""ReCAPTCHA form field with automatic validation."""
def __init__(self, label="", validators=None, **kwargs): ...
class Recaptcha:
"""Validates a ReCAPTCHA response."""
def __init__(self, message=None): ...
def __call__(self, form, field): ...
class RecaptchaWidget:
"""Widget for rendering ReCAPTCHA HTML."""
def recaptcha_html(self, public_key: str): ...class CSRFError(Exception):
"""CSRF validation error exception (inherits from werkzeug.exceptions.BadRequest)"""
description: str = "CSRF validation failed."
# Form validation status indicator
_Auto: object # Internal marker for automatic formdata bindingFlask-WTF uses Flask's configuration system. Key configuration options:
WTF_CSRF_ENABLED (bool): Enable/disable CSRF protection (default: True)WTF_CSRF_SECRET_KEY (str): Secret key for CSRF tokens (defaults to app.secret_key)WTF_CSRF_TIME_LIMIT (int): Token expiration in seconds (default: 3600)WTF_CSRF_FIELD_NAME (str): CSRF token field name (default: "csrf_token")RECAPTCHA_PUBLIC_KEY (str): reCAPTCHA site key (required)RECAPTCHA_PRIVATE_KEY (str): reCAPTCHA secret key (required)WTF_I18N_ENABLED (bool): Enable/disable i18n support (default: True)