A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
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)
"""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__)
"""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"}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"}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()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
]
}
})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"}Settings are resolved in the following order (last wins):
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 patterns support multiple formats for flexible URL matching:
CORS(app, resources={
"/exact/path": {"origins": "*"}, # Exact match
r"/api/*": {"origins": "*"}, # Wildcard pattern
r"/users/\d+": {"origins": "*"} # Regex pattern
})import re
CORS(app, resources={
re.compile(r"/api/v\d+/.*"): {"origins": "*"}
})CORS(app, resources=[
r"/api/*",
r"/public/*"
]) # Uses app-wide configuration for all patternsThe CORS extension automatically handles common error scenarios:
intercept_exceptions=True)max_age parameterInstall with Tessl CLI
npx tessl i tessl/pypi-flask-cors