Flask-CORS
Flask-CORS is a Flask extension that simplifies the implementation of Cross-Origin Resource Sharing (CORS) in Flask applications, enabling cross-origin AJAX requests. It supports global, resource-specific, and route-specific CORS configurations. The current version is 6.0.2, and it maintains an active release cadence with regular updates and security patches.
Warnings
- breaking In version 6.0.0, the path specificity ordering for CORS rules changed to improve specificity. This might alter how CORS rules are applied if your application relied on the previous, less specific ordering. Additionally, `urllib.unquote_plus` was replaced with `urllib.unquote`, and request path matching became case-sensitive.
- breaking Version 5.0.0 introduced a breaking change by defaulting to disable private network access. This was a security enhancement. If your application needs to make requests to private network resources from a public-facing origin, you will need to explicitly re-enable this functionality.
- breaking Version 4.0.0 dropped support for Python versions older than 3.8. Applications running on Python 3.7 or earlier will not be able to upgrade to Flask-CORS 4.0.0 or newer.
- gotcha Enabling `supports_credentials=True` allows browsers to send cookies and HTTP authentication headers with cross-origin requests. While necessary for authenticated requests, it introduces security implications and should always be used in conjunction with robust CSRF protection.
- gotcha Using `origins='*'` (allowing all origins) is generally not recommended for production environments due to security risks. It can expose your API to unintended access.
- gotcha When specifying `origins` in `CORS` or `@cross_origin`, ensure you include the full schema (http/https) and the port number (if not the default 80 or 443). For example, `http://localhost:8000` is correct, while `localhost:8000` or `http://localhost` (if on a non-default port) might not work.
Install
-
pip install Flask-CORS
Imports
- CORS
from flask_cors import CORS
- cross_origin
from flask_cors import cross_origin
Quickstart
from flask import Flask
from flask_cors import CORS
import os
app = Flask(__name__)
CORS(app) # Enable CORS for all routes, for all origins and methods
@app.route("/")
def hello_world():
return "Hello, cross-origin-world!"
# Example of specific CORS for an API endpoint
@app.route("/api/data")
@cross_origin(origins="http://localhost:3000", methods=["GET", "POST"], supports_credentials=True)
def get_data():
return {"message": "Data from API!"}
if __name__ == '__main__':
app.run(debug=True, port=int(os.environ.get('PORT', 5000)))