CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask-cors

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

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

cors-extension.mddocs/

CORS Extension

The CORS class provides application-wide Cross-Origin Resource Sharing configuration for Flask applications. It integrates with Flask's request/response cycle to automatically add appropriate CORS headers based on configurable rules and resource patterns.

Capabilities

CORS Class Initialization

Creates a CORS extension instance that can be bound to a Flask application either during instantiation or later using the application factory pattern.

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
    ):
        """
        Initialize Cross Origin Resource sharing for the application.

        Parameters:
        - app: Flask application instance (optional)
        - resources: Resource patterns to match (dict, list, string, or regex)
        - origins: Allowed origins (string, list, or regex patterns)
        - methods: Allowed HTTP methods (list or string)
        - expose_headers: Headers safe to expose to CORS API (list or string)
        - allow_headers: Headers allowed in requests (list, string, or regex)
        - supports_credentials: Allow authenticated requests (bool)
        - max_age: Cache time for preflight requests (timedelta, int, or string)
        - send_wildcard: Send '*' instead of specific origin (bool)
        - vary_header: Include Vary: Origin header (bool)
        - allow_private_network: Allow private network access (bool, default: False)
        - intercept_exceptions: Apply CORS to exception handlers (bool)
        - always_send: Send CORS headers even without Origin header (bool)
        """

Application Factory Pattern

Binds the CORS extension to a Flask application, supporting the application factory pattern where the app is created after the extension.

def init_app(self, app, **kwargs):
    """
    Initialize the CORS extension with a Flask application.
    
    Parameters:
    - app: Flask application instance
    - **kwargs: Additional CORS options (same as __init__)
    """

Usage Examples

Global CORS Configuration

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes with default settings

@app.route("/api/data")
def get_data():
    return {"message": "Hello from CORS-enabled endpoint"}

Resource-Specific Configuration

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

# Configure different CORS settings for different URL patterns
CORS(app, resources={
    r"/api/*": {"origins": ["https://frontend.example.com"]},
    r"/public/*": {"origins": "*"},
    r"/admin/*": {
        "origins": ["https://admin.example.com"],
        "supports_credentials": True
    }
})

@app.route("/api/users")
def api_users():
    return {"users": []}

@app.route("/public/info")
def public_info():
    return {"info": "public data"}

@app.route("/admin/stats")
def admin_stats():
    return {"stats": "sensitive data"}

Application Factory Pattern

from flask import Flask
from flask_cors import CORS

cors = CORS()

def create_app():
    app = Flask(__name__)
    
    # Configure CORS with the application
    cors.init_app(app, resources={
        r"/api/*": {"origins": ["https://trusted-domain.com"]}
    })
    
    return app

app = create_app()

Advanced Origins Configuration

import re
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

# Mixed origins configuration with strings and regex patterns
CORS(app, resources={
    r"/api/*": {
        "origins": [
            "https://example.com",          # Exact match
            "http://localhost:3000",        # Development server
            r"https://.*\.example\.com",    # Subdomain regex
            re.compile(r"https://app\d+\.example\.com")  # Compiled regex
        ]
    }
})

Credentials and Security

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

# Enable credentials for trusted origins only
CORS(app, resources={
    r"/api/auth/*": {
        "origins": ["https://trusted-frontend.com"],
        "supports_credentials": True,
        "allow_headers": ["Content-Type", "Authorization"]
    }
})

@app.route("/api/auth/login", methods=["POST"])
def login():
    # This endpoint will accept cookies and credentials
    return {"token": "auth-token"}

Configuration Priority

Settings are resolved in the following order (last wins):

  1. Default settings
  2. App-level Flask configuration (CORS_*)
  3. CORS constructor keyword arguments
  4. Resource-specific options
  5. init_app keyword arguments
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

# App-level configuration
app.config['CORS_ORIGINS'] = ['https://default.com']

# Constructor arguments override app config
cors = CORS(origins=['https://constructor.com'])

# Resource-specific settings override constructor
cors.init_app(app, resources={
    r"/specific/*": {"origins": ["https://specific.com"]}
})

Resource Pattern Matching

Resource patterns support multiple formats for flexible URL matching:

String Patterns

CORS(app, resources={
    "/exact/path": {"origins": "*"},           # Exact match
    r"/api/*": {"origins": "*"},               # Wildcard pattern
    r"/users/\d+": {"origins": "*"}            # Regex pattern
})

Compiled Regex

import re

CORS(app, resources={
    re.compile(r"/api/v\d+/.*"): {"origins": "*"}
})

List of Patterns

CORS(app, resources=[
    r"/api/*",
    r"/public/*"
])  # Uses app-wide configuration for all patterns

Error Handling

The CORS extension automatically handles common error scenarios:

  • Invalid Origins: Non-matching origins are rejected silently
  • Missing Headers: Required CORS headers are added automatically
  • Preflight Requests: OPTIONS requests are handled automatically
  • Exception Responses: CORS headers are added to error responses (if intercept_exceptions=True)

Performance Considerations

  • Pattern Matching: Patterns are sorted by length (longest first) for optimal matching
  • Caching: Preflight responses can be cached using max_age parameter
  • Header Optimization: Only necessary headers are added to responses

Install with Tessl CLI

npx tessl i tessl/pypi-flask-cors

docs

cors-extension.md

cross-origin-decorator.md

index.md

tile.json