📜  flask cors - Python (1)

📅  最后修改于: 2023-12-03 14:41:13.381000             🧑  作者: Mango

Flask CORS - Python

Introduction

Flask CORS is a Flask extension that allows you to enable Cross Origin Resource Sharing (CORS) in your Flask applications. CORS is a security feature implemented by modern browsers that restricts web pages from making requests to a different domain than the one that served the original page. Flask CORS can be used to relax this restriction and enable your Flask application to make cross-domain requests.

Installation

You can install Flask CORS using pip. Simply run the following command:

pip install flask-cors
Usage

To use Flask CORS in your Flask application, first, import the CORS class from the Flask CORS module. Then, create a Flask instance as usual and pass it to the CORS class constructor. Finally, add the CORS object to your Flask application using the .init_app() method.

Here is an example:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app)

@app.route("/")
def index():
    return "Hello, World!"

if __name__ == "__main__":
    app.run()

This example enables CORS for all routes in your Flask application. If you only want to enable cross-domain requests for a specific route, you can pass the CORS object as a decorator to the route function like this:


@app.route("/")
@cors.cross_origin()
def index():
    return "Hello, World!"
Configuration

The CORS constructor can take several optional parameters to customize the behavior of the CORS middleware. Some of the most useful parameters are:

  • origins: A list of origins that are allowed to access the Flask application. Defaults to '*', which means any origin is allowed.
  • methods: A list of HTTP methods that are allowed for cross-domain requests. Defaults to ['GET', 'HEAD', 'POST', 'OPTIONS', 'PUT', 'PATCH', 'DELETE'].
  • allow_headers: A list of headers that are allowed for cross-domain requests. Defaults to ['Content-Type', 'Authorization'].
  • expose_headers: A list of headers that are exposed to the browser. Defaults to None.
  • supports_credentials: A boolean flag indicating whether the Flask application supports credentials for cross-domain requests. Defaults to False.
  • max_age: The maximum age (in seconds) of the CORS preflight request. Defaults to None.

You can pass these parameters to the CORS constructor as keyword arguments:

cors = CORS(app, origins=['https://example.com'], allow_headers=['X-Requested-With', 'Content-Type'])
Conclusion

Flask CORS is a powerful extension that allows you to enable Cross Origin Resource Sharing in your Flask applications. Whether you need to make cross-domain requests from your JavaScript application or build a RESTful API that supports cross-domain requests, Flask CORS has got you covered.

For more information on Flask CORS, check out the official documentation at https://flask-cors.readthedocs.io/en/latest/.