Flask-CORS

repository·main·Indexed 21 days ago

https://github.com/corydolphin/flask-cors

A Flask extension that simplifies Cross-Origin Resource Sharing (CORS) support, enabling cross-origin AJAX requests. It provides a CORS class for centralized application-level configuration and a @cross_origin decorator for granular control over specific routes and Flask Blueprints. The library allows configuration of allowed origins, methods, headers, and credentials support via constructor arguments, resource patterns, or Flask app config using the CORS_ prefix.

Tokens
4.8K
Snippets
22
Records
25
Agent score
74%

What's inside flask-cors

  1. Use Flask-CORS as an extension for centralized configuration

    main

    You can use Flask-CORS as a Flask extension to provide centralized Cross-Origin Resource Sharing (CORS) configuration for your application. This allows you to define CORS rules for your resources using patterns rather than applying them to individual routes manually.

    # Note: The actual implementation is contained in examples/app_based_example.py
    # It demonstrates using Flask-CORS as an extension to manage resources by patterns.
  2. Enable CORS with cookies and credentials

    main

    By default, flask-cors disables the submission of cookies across domains for security reasons. To allow cross-site cookies or authenticated requests (credentials), set the supports_credentials option to True when initializing the extension.

    Warning: If you enable this, ensure you have implemented CSRF (Cross-Site Request Forgery) protection to secure your application.

    from flask import Flask, session
    from flask_cors import CORS
    
    app = Flask(__name__)
    CORS(app, supports_credentials=True)
    
    @app.route("/")
    def helloWorld():
      return "Hello, %s" % session['username']
  3. Get started with flask-cors

    main

    To enable CORS support for all routes, all origins, and all methods in your Flask application, initialize the CORS extension by passing your app instance to it. This is the simplest way to allow cross-origin AJAX requests globally.

    from flask import Flask
    from flask_cors import CORS
    
    app = Flask(__name__)
    CORS(app)
    
    @app.route("/")
    def helloWorld():
      return "Hello, cross-origin-world!"
  4. Enable CORS for all routes and origins

    main

    The simplest way to use Flask-CORS is to initialize the CORS extension with your Flask app instance. By default, this enables CORS support for all routes, all origins, and all methods.

    from flask import Flask
    from flask_cors import CORS
    
    app = Flask(__name__)
    CORS(app)
    
    @app.route("/")
    def helloWorld():
      return "Hello, cross-origin-world!"
  5. Use CORS with Flask Blueprints

    main

    Flask-CORS supports Flask Blueprints natively. To apply CORS settings to a specific blueprint rather than the entire application, pass the blueprint instance to the CORS extension constructor. This allows you to isolate CORS configurations to specific modules or routes defined within that blueprint.

    from flask import Blueprint
    from flask_cors import CORS
    
    my_blueprint = Blueprint('my_blueprint', __name__)
    # Pass the blueprint instance to CORS to apply settings to it
    CORS(my_blueprint)
  6. Define resource patterns for CORS

    main

    The resources argument allows you to map specific URL patterns to specific CORS configurations.

    Accepted shapes for ResourceSpec:

    • A single pattern (string or regex) applied to all routes.
    • A list of patterns, all using the default configuration.
    • A dictionary mapping ResourcePattern to a dictionary of specific options (e.g., dict[ResourcePattern, dict[str, Any]]).

    Patterns can be literal strings or pre-compiled regular expressions (re.Pattern).

    # Mapping specific paths to specific CORS settings
    CORS(app, resources=[
        r"/public/*": {"origins": "*"},
        r"/api/v1/*": {"origins": "https://api.example.com", "supports_credentials": True}
    ])
  7. Use CORS with a view decorator

    main

    Instead of applying CORS to an entire Flask application, you can use CORS as a decorator on specific view functions. This allows you to isolate CORS configuration to a small subset of views, providing more granular control over which endpoints are accessible cross-origin.

    # Note: The actual implementation is in examples/view_based_example.py
    # It demonstrates applying the @CORS() decorator to specific routes.
  8. Use the @cross_origin decorator for route-specific CORS

    main

    If you prefer a decorator-based approach, you can use @cross_origin() on specific Flask routes. This must be placed below the @app.route(...) decorator. This allows you to enable CORS on a per-route basis rather than globally.

    @app.route("/")
    @cross_origin()
    def helloWorld():
      return "Hello, cross-origin-world!"
  9. Configure resource-specific CORS options

    main

    You can apply specific CORS settings to certain paths by passing a resources dictionary to the CORS constructor. This dictionary maps URL patterns (as regex strings) to a set of configuration options, such as origins.

    app = Flask(__name__)
    # This allows all origins ('*') only for paths matching '/api/*'
    cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
    
    @app.route("/api/v1/users")
    def list_users():
      return "user example"