A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible
npx @tessl/cli install tessl/pypi-flask-cors@5.0.0A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible. Flask-CORS provides comprehensive CORS support that can be applied globally to all routes, selectively to specific resources and origins, or individually to routes using decorators.
pip install flask-corsfrom flask_cors import CORS, cross_originFor version information:
from flask_cors import __version__from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # Enable CORS for all routes and origins
@app.route("/")
def hello():
return "Hello, cross-origin-world!"from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "*"}})
@app.route("/api/v1/users")
def list_users():
return "user example"from flask import Flask
from flask_cors import cross_origin
app = Flask(__name__)
@app.route("/")
@cross_origin()
def hello():
return "Hello, cross-origin-world!"Flask-CORS follows the Flask extension pattern with two main approaches:
CORS class integrates with Flask's application context and uses after_request handlers to automatically add CORS headers to responsescross_origin decorator wraps individual route functions to add CORS headers on a per-route basisThe extension automatically handles:
Application-wide CORS configuration using the CORS class. Supports global settings, resource-specific configurations, and automatic handling of preflight requests and exception responses.
class CORS:
def __init__(
self,
app=None,
resources=r"/*",
origins="*",
methods=None,
expose_headers=None,
allow_headers="*",
supports_credentials=False,
max_age=None,
send_wildcard=False,
vary_header=True,
allow_private_network=False,
intercept_exceptions=True,
always_send=True,
**kwargs
): ...
def init_app(self, app, **kwargs): ...Route-specific CORS configuration using the cross_origin decorator. Provides fine-grained control over CORS settings for individual routes with automatic OPTIONS handling.
def cross_origin(
origins="*",
methods=None,
expose_headers=None,
allow_headers="*",
supports_credentials=False,
max_age=None,
send_wildcard=False,
vary_header=True,
automatic_options=True,
allow_private_network=False,
always_send=True,
**kwargs
): ...from typing import Union, List, Dict, Pattern, Any
from datetime import timedelta
# Common type aliases used throughout the API
Origins = Union[str, List[str], Pattern[str], List[Pattern[str]]]
Methods = Union[str, List[str]]
Headers = Union[str, List[str], Pattern[str], List[Pattern[str]]]
MaxAge = Union[int, float, timedelta, str]
Resources = Union[str, List[str], Dict[str, Dict[str, Any]], Pattern[str]]__version__: str # Package version (e.g., "5.0.0")
# Default HTTP methods allowed for CORS
ALL_METHODS = ["GET", "HEAD", "POST", "OPTIONS", "PUT", "PATCH", "DELETE"]All CORS options can be configured through:
CORS() or cross_origin()CORS_* prefixed keysCORS_ORIGINS # Allowed origins
CORS_METHODS # Allowed methods
CORS_ALLOW_HEADERS # Allowed request headers
CORS_EXPOSE_HEADERS # Headers exposed to client
CORS_SUPPORTS_CREDENTIALS # Allow credentials
CORS_MAX_AGE # Preflight cache time
CORS_SEND_WILDCARD # Send '*' instead of specific origin
CORS_AUTOMATIC_OPTIONS # Handle OPTIONS automatically
CORS_VARY_HEADER # Include Vary: Origin header
CORS_RESOURCES # Resource patterns and options
CORS_INTERCEPT_EXCEPTIONS # Apply CORS to exception handlers
CORS_ALWAYS_SEND # Send headers even without Origin
CORS_ALLOW_PRIVATE_NETWORK # Allow private network accessFlask-CORS includes comprehensive logging support for troubleshooting CORS issues:
import logging
logging.getLogger('flask_cors').level = logging.DEBUGCommon exceptions:
ValueError: Raised when supports_credentials=True is used with wildcard origins ('*')supports_credentials=True per CORS specification