or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

cors-extension.mdcross-origin-decorator.mdindex.md
tile.json

tessl/pypi-flask-cors

A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible

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

To install, run

npx @tessl/cli install tessl/pypi-flask-cors@5.0.0

index.mddocs/

Flask-CORS

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

Package Information

  • Package Name: Flask-Cors
  • Package Type: pypi
  • Language: Python
  • Installation: pip install flask-cors

Core Imports

from flask_cors import CORS, cross_origin

For version information:

from flask_cors import __version__

Basic Usage

Application-wide CORS

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

Resource-specific CORS

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"

Route-specific CORS with decorator

from flask import Flask
from flask_cors import cross_origin

app = Flask(__name__)

@app.route("/")
@cross_origin()
def hello():
    return "Hello, cross-origin-world!"

Architecture

Flask-CORS follows the Flask extension pattern with two main approaches:

  • Extension Pattern: The CORS class integrates with Flask's application context and uses after_request handlers to automatically add CORS headers to responses
  • Decorator Pattern: The cross_origin decorator wraps individual route functions to add CORS headers on a per-route basis
  • Configuration Hierarchy: Settings are resolved in order: resource-level → keyword arguments → app configuration → defaults

The extension automatically handles:

  • Preflight OPTIONS requests
  • Origin validation and matching (strings, regexes, wildcards)
  • Header validation and filtering
  • Credential handling and security enforcement
  • Exception interception for consistent CORS headers

Capabilities

CORS Extension

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

CORS Extension

Cross-Origin Decorator

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

Cross-Origin Decorator

Types

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

Constants

__version__: str  # Package version (e.g., "5.0.0")

# Default HTTP methods allowed for CORS
ALL_METHODS = ["GET", "HEAD", "POST", "OPTIONS", "PUT", "PATCH", "DELETE"]

Configuration

All CORS options can be configured through:

  1. Direct parameters to CORS() or cross_origin()
  2. Flask app configuration using CORS_* prefixed keys
  3. Resource-specific dictionaries (for CORS extension only)

Flask Configuration Keys

CORS_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 access

Error Handling

Flask-CORS includes comprehensive logging support for troubleshooting CORS issues:

import logging
logging.getLogger('flask_cors').level = logging.DEBUG

Common exceptions:

  • ValueError: Raised when supports_credentials=True is used with wildcard origins ('*')

Security Considerations

  • Credentials: By default, cookie submission across domains is disabled for security
  • Wildcard Origins: Cannot be used with supports_credentials=True per CORS specification
  • Private Network: Modern browsers require explicit permission for private network access
  • Origin Validation: Supports exact matches, regex patterns, and case-insensitive comparison
  • CSRF Protection: Consider implementing CSRF protection when enabling credentials