Home  >  Article  >  Backend Development  >  How to use Flask-CORS to achieve cross-domain resource sharing

How to use Flask-CORS to achieve cross-domain resource sharing

王林
王林Original
2023-08-02 14:03:341283browse

How to use Flask-CORS to achieve cross-origin resource sharing

Introduction:
In network application development, cross-origin resource sharing (Cross Origin Resource Sharing, referred to as CORS) is a mechanism that allows servers to Share resources with specified sources or domain names. Using CORS, we can flexibly control data transmission between different domains and achieve safe and reliable cross-domain access. In this article, we will introduce how to use the Flask-CORS extension library to implement CORS functionality.

1. What is CORS
CORS is a security mechanism provided by the browser, which is used to control access to resources between different domains. In the traditional same-origin policy, browsers only allow web pages under the same domain name to interact, while CORS allows web pages under different domain names to initiate cross-domain requests. CORS is controlled through HTTP header fields and interacts between the client and server.

2. Introduction to Flask-CORS
Flask-CORS is a CORS extension library based on the Flask framework. It provides a simple and flexible solution for implementing CORS functions. Flask-CORS can control the behavior of CORS by setting parameters, such as allowed sources, request methods, request headers, etc.

3. Install Flask-CORS
You can use the pip command to install Flask-CORS:

pip install flask-cors

4. Use Flask-CORS
The following is a basic Flask application that demonstrates How to use Flask-CORS to achieve cross-domain resource sharing:

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 允许应用的所有视图都可以跨域访问

@app.route('/api/data', methods=['GET'])
def get_data():
    data = {
        'name': '小明',
        'age': 18,
        'gender': '男'
    }
    return jsonify(data)

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

In the above code, we first imported the Flask and flask_cors modules and created a Flask application. Next, use the CORS(app) statement to set all views of the application to be accessible across domains. Finally, we define a route that returns data in JSON format.

In actual development, we usually use more granular settings to flexibly control the CORS behavior of different views. Here's a more complex example:

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app, resources={
    r"/*": {
        "origins": ["http://example.com", "http://www.example.com"],
        "methods": ["GET", "POST"],
        "headers": ["Content-Type", "Authorization"]
    }
})

@app.route('/api/data', methods=['GET'])
def get_data():
    data = {
        'name': '小明',
        'age': 18,
        'gender': '男'
    }
    return jsonify(data)

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

In the code above, we make more fine-grained settings by passing a resources parameter. In this example, we only allow requests from the two domain names example.com and www.example.com to initiate cross-domain access. We also specify the allowed request methods (GET and POST) and request headers (Content-Type and Authorization).

5. Summary
In this article, we introduced how to use the Flask-CORS extension library to achieve cross-domain resource sharing. By setting different parameters, we can flexibly control data transmission between different domains and achieve safe and reliable cross-domain access. CORS is a security mechanism provided by browsers, providing developers with more freedom and flexibility to meet the needs of different application scenarios.

The above is the detailed content of How to use Flask-CORS to achieve cross-domain resource sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn