Form rendering, validation, and CSRF protection for Flask with WTForms.
npx @tessl/cli install tessl/pypi-flask-wtf@1.2.00
# Flask-WTF
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: Flask-WTF
7
- **Language**: Python
8
- **Installation**: `pip install Flask-WTF`
9
- **Package Type**: Flask extension/library
10
11
## Core Imports
12
13
```python
14
from flask_wtf import FlaskForm, CSRFProtect
15
```
16
17
Specific functionality imports:
18
19
```python
20
from flask_wtf import FlaskForm, CSRFProtect, RecaptchaField
21
from flask_wtf.csrf import generate_csrf, validate_csrf
22
from flask_wtf.file import FileField, FileRequired, FileAllowed, FileSize
23
from flask_wtf.recaptcha import Recaptcha, RecaptchaWidget
24
```
25
26
## Basic Usage
27
28
```python
29
from flask import Flask, render_template, request, redirect
30
from flask_wtf import FlaskForm, CSRFProtect
31
from wtforms import StringField, SubmitField
32
from wtforms.validators import DataRequired
33
34
app = Flask(__name__)
35
app.config['SECRET_KEY'] = 'your-secret-key'
36
37
# Enable CSRF protection globally
38
csrf = CSRFProtect(app)
39
40
class MyForm(FlaskForm):
41
name = StringField('Name', validators=[DataRequired()])
42
submit = SubmitField('Submit')
43
44
@app.route('/', methods=['GET', 'POST'])
45
def index():
46
form = MyForm()
47
if form.validate_on_submit():
48
name = form.name.data
49
return f'Hello {name}!'
50
return render_template('form.html', form=form)
51
52
# Template (form.html)
53
# <form method="POST">
54
# {{ form.hidden_tag() }} <!-- Includes CSRF token -->
55
# {{ form.name.label }} {{ form.name() }}
56
# {{ form.submit() }}
57
# </form>
58
```
59
60
## Architecture
61
62
Flask-WTF extends WTForms with Flask-specific integrations:
63
64
- **Form Integration**: FlaskForm automatically binds to Flask request data and provides CSRF protection
65
- **CSRF Protection**: Session-based token generation and validation with automatic request processing
66
- **File Handling**: Werkzeug-aware file fields with built-in validation capabilities
67
- **Request Context**: Seamless integration with Flask's application and request contexts
68
- **Template Integration**: Automatic CSRF token injection into Jinja2 templates
69
70
## Capabilities
71
72
### CSRF Protection
73
74
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.
75
76
```python { .api }
77
class CSRFProtect:
78
"""Enable CSRF protection globally for a Flask app."""
79
def __init__(self, app=None): ...
80
def init_app(self, app): ...
81
def exempt(self, view): ...
82
def protect(self): ...
83
84
def generate_csrf(secret_key: str = None, token_key: str = None) -> str:
85
"""Generate a CSRF token. The token is cached for a request."""
86
87
def validate_csrf(data: str, secret_key: str = None, time_limit: int = None, token_key: str = None):
88
"""Validate a CSRF token."""
89
```
90
91
[CSRF Protection](./csrf-protection.md)
92
93
### Form Handling
94
95
Flask-integrated form processing with automatic request data binding, validation, and CSRF token management. Provides enhanced form capabilities beyond basic WTForms functionality.
96
97
```python { .api }
98
class FlaskForm(Form):
99
"""Flask-specific subclass of WTForms Form with CSRF protection."""
100
def __init__(self, formdata=_Auto, **kwargs): ...
101
def is_submitted(self) -> bool:
102
"""Consider the form submitted if method is POST, PUT, PATCH, or DELETE."""
103
def validate_on_submit(self, extra_validators=None) -> bool:
104
"""Call validate() only if the form is submitted."""
105
def hidden_tag(self, *fields):
106
"""Render the form's hidden fields in one call."""
107
108
# Re-exported from WTForms for convenience
109
Form = wtforms.Form # Base WTForms Form class
110
```
111
112
[Form Handling](./form-handling.md)
113
114
### File Upload
115
116
Secure file upload handling with Werkzeug integration, providing specialized file fields and comprehensive validation including file type restrictions, size limits, and presence checking.
117
118
```python { .api }
119
class FileField:
120
"""Werkzeug-aware file upload field."""
121
def process_formdata(self, valuelist): ...
122
123
class MultipleFileField:
124
"""Multiple file upload field (added in v1.2.0)."""
125
def process_formdata(self, valuelist): ...
126
127
class FileRequired:
128
"""Validates that uploaded file(s) are present."""
129
def __init__(self, message=None): ...
130
131
class FileAllowed:
132
"""Validates that uploaded file(s) have allowed extensions."""
133
def __init__(self, upload_set, message=None): ...
134
135
class FileSize:
136
"""Validates that uploaded file(s) are within size limits."""
137
def __init__(self, max_size: int, min_size: int = 0, message=None): ...
138
139
# Convenience aliases
140
file_required = FileRequired
141
file_allowed = FileAllowed
142
file_size = FileSize
143
```
144
145
[File Upload](./file-upload.md)
146
147
### reCAPTCHA Integration
148
149
Complete Google reCAPTCHA integration with form fields, validation, and widget rendering. Provides bot protection for forms with configurable reCAPTCHA parameters and error handling.
150
151
```python { .api }
152
class RecaptchaField(Field):
153
"""ReCAPTCHA form field with automatic validation."""
154
def __init__(self, label="", validators=None, **kwargs): ...
155
156
class Recaptcha:
157
"""Validates a ReCAPTCHA response."""
158
def __init__(self, message=None): ...
159
def __call__(self, form, field): ...
160
161
class RecaptchaWidget:
162
"""Widget for rendering ReCAPTCHA HTML."""
163
def recaptcha_html(self, public_key: str): ...
164
```
165
166
[reCAPTCHA Integration](./recaptcha.md)
167
168
## Core Types
169
170
```python { .api }
171
class CSRFError(Exception):
172
"""CSRF validation error exception (inherits from werkzeug.exceptions.BadRequest)"""
173
description: str = "CSRF validation failed."
174
175
# Form validation status indicator
176
_Auto: object # Internal marker for automatic formdata binding
177
```
178
179
## Configuration
180
181
Flask-WTF uses Flask's configuration system. Key configuration options:
182
183
### CSRF Settings
184
- `WTF_CSRF_ENABLED` (bool): Enable/disable CSRF protection (default: True)
185
- `WTF_CSRF_SECRET_KEY` (str): Secret key for CSRF tokens (defaults to app.secret_key)
186
- `WTF_CSRF_TIME_LIMIT` (int): Token expiration in seconds (default: 3600)
187
- `WTF_CSRF_FIELD_NAME` (str): CSRF token field name (default: "csrf_token")
188
189
### reCAPTCHA Settings
190
- `RECAPTCHA_PUBLIC_KEY` (str): reCAPTCHA site key (required)
191
- `RECAPTCHA_PRIVATE_KEY` (str): reCAPTCHA secret key (required)
192
193
### Internationalization
194
- `WTF_I18N_ENABLED` (bool): Enable/disable i18n support (default: True)