### Install Pre-commit Hooks
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Installs the pre-commit framework, which automatically runs code checks and formatting before each commit.
```bash
pre-commit install
```
--------------------------------
### Upgrade Pip and Setuptools
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Upgrades the pip package installer and setuptools for the current Python environment.
```bash
python -m pip install --upgrade pip setuptools
```
--------------------------------
### Install Flask-WTF (Development Version from Archive)
Source: https://flask-wtf.readthedocs.io/en/1.2.x/install
Installs the latest development version of Flask-WTF from a tarball archive hosted on GitHub. This method is an alternative to cloning the repository and is useful for quick installation of the bleeding-edge version.
```bash
pip install -U https://github.com/wtforms/flask-wtf/archive/main.tar.gz
```
--------------------------------
### Install Flask-WTF (Development Version from GitHub)
Source: https://flask-wtf.readthedocs.io/en/1.2.x/install
Installs the latest development version of Flask-WTF directly from its GitHub repository. This involves cloning the repository and then performing an editable installation. Useful for developers contributing to Flask-WTF or needing the absolute latest features.
```bash
git clone https://github.com/wtforms/flask-wtf
pip install -e ./flask-wtf
```
--------------------------------
### Install Development Dependencies and Flask-WTF
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Installs all necessary development dependencies from 'requirements/dev.txt' and then installs Flask-WTF in editable mode for development.
```bash
pip install -r requirements/dev.txt && pip install -e .
```
--------------------------------
### Install Flask-WTF (Released Version)
Source: https://flask-wtf.readthedocs.io/en/1.2.x/install
Installs or upgrades to the latest stable version of Flask-WTF using pip. This is the recommended method for most users. It requires pip to be installed and accessible.
```bash
pip install -U Flask-WTF
```
--------------------------------
### Create a Flask-WTF Form
Source: https://flask-wtf.readthedocs.io/en/1.2.x/quickstart
Defines a basic Flask-WTF form with a string field requiring data. This form integrates with Flask applications and automatically includes CSRF protection.
```python
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
class MyForm(FlaskForm):
name = StringField('name', validators=[DataRequired()])
```
--------------------------------
### Display Form Field Error Messages
Source: https://flask-wtf.readthedocs.io/en/1.2.x/quickstart
Renders validation error messages for a specific form field in an HTML template. It iterates through the `errors` attribute of the field if any exist.
```html
{% if form.name.errors %}
{% for error in form.name.errors %}
- {{ error }}
{% endfor %}
{% endif %}
```
--------------------------------
### Generate HTML Test Coverage Report
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Installs the 'coverage' package, runs pytest with coverage measurement, and generates an HTML report of test coverage. This helps identify areas needing more tests.
```bash
pip install coverage
coverage run -m pytest
coverage html
```
--------------------------------
### Setup CSRF Protection Globally with Flask-WTF
Source: https://flask-wtf.readthedocs.io/en/1.2.x/csrf
This snippet demonstrates how to initialize the CSRFProtect extension globally for a Flask application. It can be applied directly or lazily during app creation. CSRF protection requires a secret key, which defaults to the Flask app's SECRET_KEY.
```python
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect(app)
```
```python
csrf = CSRFProtect()
def create_app():
app = Flask(__name__)
csrf.init_app(app)
```
--------------------------------
### Render CSRF Token in HTML Forms with Flask-WTF
Source: https://flask-wtf.readthedocs.io/en/1.2.x/csrf
These code examples show how to include the CSRF token in HTML forms. The first example assumes the template uses FlaskForm, rendering the token with `{{ form.csrf_token }}`. The second example is for templates not using FlaskForm, rendering a hidden input with `{{ csrf_token() }}`.
```html
```
```html
```
--------------------------------
### Validate Form in Flask View Handler
Source: https://flask-wtf.readthedocs.io/en/1.2.x/quickstart
Handles form submission and validation within a Flask route. It checks if the request is a POST and if the form data is valid using `validate_on_submit()`.
```python
@app.route('/submit', methods=['GET', 'POST'])
def submit():
form = MyForm()
if form.validate_on_submit():
return redirect('/success')
return render_template('submit.html', form=form)
```
--------------------------------
### Render Hidden Fields with hidden_tag()
Source: https://flask-wtf.readthedocs.io/en/1.2.x/quickstart
Renders all hidden fields of a form, including the CSRF token, using the `hidden_tag()` helper. This is useful when a form has multiple hidden fields.
```html
```
--------------------------------
### Render CSRF Token in HTML Form
Source: https://flask-wtf.readthedocs.io/en/1.2.x/quickstart
Renders the automatically generated CSRF token hidden field within an HTML form. This is essential for security and is automatically included by Flask-WTF.
```html
```
--------------------------------
### Render Recaptcha Field in HTML Form (HTML)
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
This example shows how to render the RecaptchaField within an HTML form using Jinja2 templating. The form action and method are specified, and then the username and recaptcha fields are rendered using their respective template variables.
```html
```
--------------------------------
### Build Documentation with Sphinx
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Navigates to the 'docs' directory and builds the project documentation in HTML format using Sphinx. The generated files can be viewed in a web browser.
```bash
cd docs
make html
```
--------------------------------
### Create and Activate Virtual Environment
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Creates a Python virtual environment named 'env' and activates it. The activation command differs between Unix-like systems and Windows.
```bash
python3 -m venv env
. env/bin/activate
```
```powershell
> env\Scripts\activate
```
--------------------------------
### Run Full Test Suite with Tox
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Executes the complete test suite across multiple Python environments using tox. This is recommended for a thorough test before CI checks.
```bash
tox
```
--------------------------------
### Run Basic Test Suite with Pytest
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Executes the basic test suite for the current environment using pytest. This is a quick check before submitting a pull request.
```bash
pytest
```
--------------------------------
### Configure Git Global Settings
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Sets the global username and email for Git configuration, necessary for version control operations.
```bash
git config --global user.name 'your name'
git config --global user.email 'your email'
```
--------------------------------
### Clone Flask-WTF Repository
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Clones the Flask-WTF repository from GitHub to a local directory and navigates into it.
```bash
git clone https://github.com/wtforms/flask-wtf
cd flask-wtf
```
--------------------------------
### Create Feature Branch (Main)
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Fetches the latest changes from the 'origin' remote and creates a new branch named 'your-branch-name' based on the 'main' branch for feature development.
```bash
git fetch origin
git checkout -b your-branch-name origin/main
```
--------------------------------
### Create Bugfix Branch (1.0.x)
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Fetches the latest changes from the 'origin' remote and creates a new branch named 'your-branch-name' based on the latest '.x' release branch (e.g., '1.0.x') for bug or documentation fixes.
```bash
git fetch origin
git checkout -b your-branch-name origin/1.0.x
```
--------------------------------
### Handle Single File Upload in Flask-WTF
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
Illustrates how to handle single file uploads using Flask-WTF's FileField and FileRequired validator. It includes setting up the form, route, saving the file, and rendering the upload template.
```python
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired
from werkzeug.utils import secure_filename
class PhotoForm(FlaskForm):
photo = FileField(validators=[FileRequired()])
@app.route('/upload', methods=['GET', 'POST'])
def upload():
form = PhotoForm()
if form.validate_on_submit():
f = form.photo.data
filename = secure_filename(f.filename)
f.save(os.path.join(
app.instance_path, 'photos', filename
))
return redirect(url_for('index'))
return render_template('upload.html', form=form)
```
--------------------------------
### Add Fork Remote
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Adds a remote repository for your forked Flask-WTF project, allowing you to push your changes. Replace '{username}' with your GitHub username.
```bash
git remote add fork https://github.com/{username}/flask-wtf
```
--------------------------------
### Flask-WTF Core Classes and Methods
Source: https://flask-wtf.readthedocs.io/en/1.2.x/genindex
This section details core components of Flask-WTF, including form handling, CSRF protection, file uploads, and reCAPTCHA integration.
```APIDOC
## FlaskForm Class
### Description
Represents a WTForms form integrated with Flask.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## FlaskForm.Meta Class
### Description
Metaclass for FlaskForm, handling form meta-information.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## CSRFProtect Class
### Description
Handles Cross-Site Request Forgery (CSRF) protection for Flask applications.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## FileAllowed Class
### Description
Validator for checking if a file is allowed based on extensions.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## FileField Class
### Description
A WTForms field for handling file uploads.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## FileRequired Class
### Description
Validator to ensure a file is present in a FileField.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## Recaptcha Class
### Description
Represents the reCAPTCHA widget and validation.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## RecaptchaField Class
### Description
A WTForms field for integrating reCAPTCHA.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## RecaptchaWidget Class
### Description
The widget used for rendering the reCAPTCHA field.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## CSRFError Class
### Description
Custom exception raised for CSRF-related errors.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## Module: flask_wtf
### Description
Main module for the Flask-WTF library.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## Module: flask_wtf.csrf
### Description
Module containing CSRF protection related classes and functions.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## Module: flask_wtf.file
### Description
Module containing file upload related classes and validators.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## Functions within flask_wtf.csrf
### Description
Provides functions for CSRF management.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
## Methods within FlaskForm and FlaskForm.Meta
### Description
Provides methods for form submission, CSRF field generation, and meta-information handling.
### Method
N/A
### Endpoint
N/A
### Parameters
N/A
### Request Example
N/A
### Response
N/A
```
--------------------------------
### Validate File Uploads with FileAllowed (Direct Extensions)
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
Shows how to use FileAllowed validator without Flask-Uploads by directly passing a list of allowed file extensions (e.g., 'jpg', 'png') to the validator.
```python
class UploadForm(FlaskForm):
upload = FileField('image', validators=[
FileRequired(),
FileAllowed(['jpg', 'png'], 'Images only!')
])
```
--------------------------------
### Push Commits to Fork
Source: https://flask-wtf.readthedocs.io/en/1.2.x/contributing
Pushes the commits from the current local branch ('your-branch-name') to your fork on GitHub, setting the upstream remote.
```bash
git push --set-upstream fork your-branch-name
```
--------------------------------
### File Handling Fields and Validators
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Details on file-related fields and validators provided by Flask-WTF, including `FileField`, `FileAllowed`, and `FileRequired`.
```APIDOC
## File Handling Fields and Validators
### Description
This section details the file-related fields and validators offered by Flask-WTF, designed to work with Werkzeug's file handling.
### Fields
- **FileField**: Werkzeug-aware subclass of `wtforms.fields.FileField`.
### Validators
- **FileAllowed(upload_set, message=None)**: Validates that the uploaded file(s) is allowed by a given list of extensions or a Flask-Uploads `UploadSet`.
- **Parameters**:
- **upload_set** (list or UploadSet) - A list of extensions or an `UploadSet`.
- **message** (str) - Error message.
- **FileRequired(message=None)**: Validates that the uploaded files(s) is a Werkzeug `FileStorage` object.
- **Parameters**:
- **message** (str) - Error message.
```
--------------------------------
### Define Signup Form with RecaptchaField (Python)
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
This snippet demonstrates how to define a Flask-WTF form that includes a RecaptchaField. It requires importing FlaskForm and RecaptchaField from flask_wtf, and TextField from wtforms. The RecaptchaField is added as a form field, and it will automatically handle Recaptcha validation.
```python
from flask_wtf import FlaskForm, RecaptchaField
from wtforms import TextField
class SignupForm(FlaskForm):
username = TextField('Username')
recaptcha = RecaptchaField()
```
--------------------------------
### Handle Multiple File Uploads in Flask-WTF
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
Demonstrates handling multiple file uploads using Flask-WTF's MultipleFileField and FileRequired validator. The code shows iterating through the uploaded files and saving each one securely.
```python
from flask_wtf import FlaskForm
from flask_wtf.file import MultipleFileField, FileRequired
from werkzeug.utils import secure_filename
class PhotoForm(FlaskForm):
photos = MultipleFileField(validators=[FileRequired()])
@app.route('/upload', methods=['GET', 'POST'])
def upload():
form = PhotoForm()
if form.validate_on_submit():
for f in form.photo.data: # form.photo.data return a list of FileStorage object
filename = secure_filename(f.filename)
f.save(os.path.join(
app.instance_path, 'photos', filename
))
return redirect(url_for('index'))
return render_template('upload.html', form=form)
```
--------------------------------
### FlaskForm Class
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Provides a Flask-specific subclass of WTForms `Form`. It automatically uses `flask.request.form` and `flask.request.files` for formdata unless explicitly disabled.
```APIDOC
## FlaskForm Class
### Description
Flask-specific subclass of WTForms `Form`. If `formdata` is not specified, this will use `flask.request.form` and `flask.request.files`. Explicitly pass `formdata=None` to prevent this.
### Class
`flask_wtf.FlaskForm`
### Properties
- **csrf** (bool) - Controls CSRF protection.
- **csrf_field_name** (str) - The name of the CSRF field.
### Methods
- **get_translations(form)**: Override in subclasses to provide alternate translations factory.
- **wrap_formdata(form, formdata)**: Allows custom wrappers of WTForms formdata.
- **hidden_tag(*fields)**: Render the form’s hidden fields in one call.
- **is_submitted()**: Returns True if the form is submitted (active request with POST, PUT, PATCH, or DELETE method).
- **validate_on_submit(extra_validators=None)**: Calls `validate()` only if the form is submitted.
```
--------------------------------
### Manually Combine Request Data for File Uploads
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
Shows how to manually combine request.files and request.form using CombinedMultiDict when passing data explicitly to a FlaskForm. This is an alternative to Flask-WTF handling it automatically.
```python
from flask import request
from werkzeug.datastructures import CombinedMultiDict
form = PhotoForm(CombinedMultiDict((request.files, request.form)))
```
--------------------------------
### Recaptcha Field
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Documentation for the `RecaptchaField` and related `Recaptcha` validator.
```APIDOC
## Recaptcha Field
### Description
This section covers the `RecaptchaField` used for integrating Google reCAPTCHA into Flask-WTF forms, along with its associated validator.
### Fields
- **RecaptchaField**: Field for Google reCAPTCHA integration.
### Validators
- **Recaptcha(message=None)**: Validates a ReCaptcha.
- **Parameters**:
- **message** (str) - Error message.
```
--------------------------------
### Configure Recaptcha Parameters and Data Attributes (Python)
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
Illustrates how to set optional configuration variables for Recaptcha in Flask-WTF. RECAPTCHA_PARAMETERS allows customizing JavaScript API parameters, such as language and rendering mode. RECAPTCHA_DATA_ATTRS enables passing data attributes to the Recaptcha widget, like theme.
```python
RECAPTCHA_PARAMETERS = {'hl': 'zh', 'render': 'explicit'}
RECAPTCHA_DATA_ATTRS = {'theme': 'dark'}
```
--------------------------------
### Enable Global CSRF Protection in Flask App
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Initializes CSRF protection for a Flask application. It checks for CSRF tokens in form fields or headers and requires rendering the token in templates using `{{ csrf_token() }}`.
```python
from flask import Flask
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
csrf = CSRFProtect(app)
```
--------------------------------
### CSRF Token Generation and Validation Functions
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Provides functions to generate and validate CSRF tokens, crucial for securing web applications against CSRF attacks.
```APIDOC
## CSRF Token Functions
### generate_csrf
Generate a CSRF token. The token is cached for a request, so multiple calls will generate the same token. During testing, it might be useful to access the signed token in `g.csrf_token` and the raw token in `session['csrf_token']`.
#### Parameters
- **secret_key** (str) - Used to securely sign the token. Defaults to `WTF_CSRF_SECRET_KEY` or `SECRET_KEY`.
- **token_key** (str) - Key where the token is stored in the session for comparison. Defaults to `WTF_CSRF_FIELD_NAME` or `'csrf_token'`.
### validate_csrf
Check if the given data is a valid CSRF token. This compares the given signed token to the one stored in the session.
#### Parameters
- **data** - The signed CSRF token to be checked.
- **secret_key** (str) - Used to securely sign the token. Defaults to `WTF_CSRF_SECRET_KEY` or `SECRET_KEY`.
- **time_limit** (int) - Number of seconds that the token is valid. Defaults to `WTF_CSRF_TIME_LIMIT` or 3600 seconds (60 minutes).
- **token_key** (str) - Key where the token is stored in the session for comparison. Defaults to `WTF_CSRF_FIELD_NAME` or `'csrf_token'`.
#### Raises
- **ValidationError** - Contains the reason that validation failed.
*Changed in version 0.14: Raises `ValidationError` with a specific error message rather than returning `True` or `False`.*
```
--------------------------------
### Validate File Uploads with FileAllowed and Flask-Uploads
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
Demonstrates using FileRequired and FileAllowed validators with Flask-WTF's FileField, integrating with Flask-Uploads to restrict uploads to specific image types. It defines an UploadSet for images.
```python
from flask_uploads import UploadSet, IMAGES
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileRequired
images = UploadSet('images', IMAGES)
class UploadForm(FlaskForm):
upload = FileField('image', validators=[
FileRequired(),
FileAllowed(images, 'Images only!')
])
```
--------------------------------
### HTML Form for File Uploads (enctype)
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
Specifies the required HTML form attribute 'enctype' set to 'multipart/form-data' for handling file uploads correctly. This ensures that request.files is populated.
```html
```
--------------------------------
### Configure CSRF Secret Key in Flask-WTF
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
Explains how to configure a separate secret key for CSRF token generation in Flask-WTF using WTF_CSRF_SECRET_KEY. This key is used in conjunction with the Flask app's secret key.
```python
WTF_CSRF_SECRET_KEY = 'a random string'
```
--------------------------------
### Generate CSRF Token
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Generates a CSRF token that can be used for manual CSRF validation. The token is cached per request. It uses `WTF_CSRF_SECRET_KEY` or `SECRET_KEY` for signing and `WTF_CSRF_FIELD_NAME` or `'csrf_token'` for the session key by default.
```python
from flask_wtf.csrf import generate_csrf
token = generate_csrf()
```
--------------------------------
### CSRFProtect Class
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Enables CSRF protection globally for a Flask application. It checks the 'csrf_token' field from forms or the 'X-CSRFToken' header from JavaScript requests. Tokens can be rendered in templates using '{{ csrf_token() }}'.
```APIDOC
## CSRFProtect Class
### Description
Enables CSRF protection globally for a Flask app. Checks the `csrf_token` field sent with forms, or the `X-CSRFToken` header sent with JavaScript requests. Render the token in templates using `{{ csrf_token() }}`.
### Initialization
```python
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
crsf = CSRFProtect(app)
```
### exempt Method
Mark a view or blueprint to be excluded from CSRF protection.
#### Example (View Exemption)
```python
@app.route('/some-view', methods=['POST'])
@csrf.exempt
def some_view():
...
```
#### Example (Blueprint Exemption)
```python
from flask import Blueprint
bp = Blueprint('my_blueprint', __name__)
csrf.exempt(bp)
```
```
--------------------------------
### Exclude Specific Views or Blueprints from CSRF Protection
Source: https://flask-wtf.readthedocs.io/en/1.2.x/csrf
This code illustrates how to exempt specific views or entire blueprints from Flask-WTF's CSRF protection. The `@csrf.exempt` decorator can be applied to individual view functions, or `csrf.exempt()` can be called with a blueprint object. It also shows how to disable default protection and selectively apply it.
```python
@app.route('/foo', methods=('GET', 'POST'))
@csrf.exempt
def my_handler():
# ...
return 'ok'
```
```python
csrf.exempt(account_blueprint)
```
```python
@app.before_request
def check_csrf():
if not is_oauth(request):
csrf.protect()
```
--------------------------------
### Disable CSRF Protection in Flask-WTF Form
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
Demonstrates how to disable CSRF protection for a specific FlaskForm instance by passing meta={'csrf': False}. This allows for forms without CSRF token generation, though it's generally discouraged.
```python
form = FlaskForm(meta={'csrf': False})
```
--------------------------------
### Globally Disable CSRF Protection in Flask-WTF
Source: https://flask-wtf.readthedocs.io/en/1.2.x/form
Shows how to globally disable CSRF protection in Flask-WTF by setting the WTF_CSRF_ENABLED configuration variable to False. This is a global setting and should be used with caution.
```python
WTF_CSRF_ENABLED = False
```
--------------------------------
### Add CSRF Token Header to AJAX Requests with jQuery
Source: https://flask-wtf.readthedocs.io/en/1.2.x/csrf
This JavaScript snippet configures jQuery's AJAX requests to automatically include the CSRF token in the `X-CSRFToken` header. This ensures that AJAX requests are protected against CSRF attacks. It's configured using `$.ajaxSetup` and a `beforeSend` function.
```javascript
var csrf_token = "{{ csrf_token() }}";
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
}
});
```
--------------------------------
### Customize CSRFError Response with Flask
Source: https://flask-wtf.readthedocs.io/en/1.2.x/csrf
This Python snippet demonstrates how to customize the response when a `CSRFError` occurs in Flask. By using Flask's `errorhandler()`, you can define a custom function to handle these errors, returning a specific template and status code (e.g., 400).
```python
from flask_wtf.csrf import CSRFError
@app.errorhandler(CSRFError)
def handle_csrf_error(e):
return render_template('csrf_error.html', reason=e.description), 400
```
--------------------------------
### Validate CSRF Token
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Validates a provided CSRF token against the one stored in the session. It checks the `data` against the signed token stored in the session using `token_key`. The token is valid for `time_limit` seconds (default 3600). Raises `ValidationError` on failure.
```python
from flask_wtf.csrf import validate_csrf, ValidationError
try:
validate_csrf(received_token)
except ValidationError:
# Handle validation error
...
```
--------------------------------
### Exclude a Blueprint from CSRF Protection
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Excludes an entire Flask Blueprint from CSRF protection. This is a convenient way to disable CSRF checks for a group of related routes.
```python
from flask import Blueprint
bp = Blueprint('my_bp', __name__)
csrf.exempt(bp)
```
--------------------------------
### Set CSRF Token Header for All Axios Requests
Source: https://flask-wtf.readthedocs.io/en/1.2.x/csrf
This JavaScript snippet shows how to set the CSRF token for all outgoing requests made with the Axios library. The token is assigned to `axios.defaults.headers.common["X-CSRFToken"]`, ensuring that every request includes the necessary header for CSRF protection.
```javascript
axios.defaults.headers.common["X-CSRFToken"] = "{{ csrf_token() }}";
```
--------------------------------
### CSRFError Class
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Represents an error raised when a client sends invalid CSRF data. It defaults to generating a 400 Bad Request response, which can be customized using Flask's errorhandler.
```APIDOC
## CSRFError Class
### Description
Raise if the client sends invalid CSRF data with the request. Generates a 400 Bad Request response with the failure reason by default. Customize the response by registering a handler with `flask.Flask.errorhandler()`.
### Parameters
- **description** (str | None) - Description of the CSRF error.
- **response** (Response | None) - A Flask Response object to use for the error.
```
--------------------------------
### Exclude a View from CSRF Protection
Source: https://flask-wtf.readthedocs.io/en/1.2.x/api
Marks a specific view function to be excluded from CSRF protection. This is useful for routes that do not require CSRF validation, such as certain API endpoints.
```python
@app.route('/some-view', methods=['POST'])
@csrf.exempt
def some_view():
...
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.