or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

csrf-protection.mdfile-upload.mdform-handling.mdindex.mdrecaptcha.md
tile.json

tessl/pypi-flask-wtf

Form rendering, validation, and CSRF protection for Flask with WTForms.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/flask-wtf@1.2.x

To install, run

npx @tessl/cli install tessl/pypi-flask-wtf@1.2.0

index.mddocs/

Flask-WTF

Flask-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.

Package Information

  • Package Name: Flask-WTF
  • Language: Python
  • Installation: pip install Flask-WTF
  • Package Type: Flask extension/library

Core Imports

from flask_wtf import FlaskForm, CSRFProtect

Specific 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, RecaptchaWidget

Basic Usage

from 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>

Architecture

Flask-WTF extends WTForms with Flask-specific integrations:

  • Form Integration: FlaskForm automatically binds to Flask request data and provides CSRF protection
  • CSRF Protection: Session-based token generation and validation with automatic request processing
  • File Handling: Werkzeug-aware file fields with built-in validation capabilities
  • Request Context: Seamless integration with Flask's application and request contexts
  • Template Integration: Automatic CSRF token injection into Jinja2 templates

Capabilities

CSRF Protection

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."""

CSRF Protection

Form Handling

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 class

Form Handling

File Upload

Secure 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 = FileSize

File Upload

reCAPTCHA Integration

Complete 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): ...

reCAPTCHA Integration

Core Types

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 binding

Configuration

Flask-WTF uses Flask's configuration system. Key configuration options:

CSRF Settings

  • 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 Settings

  • RECAPTCHA_PUBLIC_KEY (str): reCAPTCHA site key (required)
  • RECAPTCHA_PRIVATE_KEY (str): reCAPTCHA secret key (required)

Internationalization

  • WTF_I18N_ENABLED (bool): Enable/disable i18n support (default: True)