14. CORS on Flask
CORS, or Cross-Origin Resource Sharing, is a security feature implemented by web browsers to restrict scripts running on one origin from making requests to another origin. This restriction helps prevent malicious websites from accessing sensitive data on other sites.
In Flask, if your application serves resources that need to be accessed from a different origin (domain, protocol, or port), you might encounter CORS issues. To allow cross-origin requests in Flask, you typically use the Flask-CORS extension. Here’s a brief explanation with an example:
Installing Flask-CORS
First, you need to install the Flask-CORS extension. You can do this via pip:
pip install flask-corsExample of Using Flask-CORS
Let’s say you have a simple Flask application that serves some data through an API. Here’s how you might enable CORS:
Import and Initialize CORS:
from flask import Flask, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) # This will enable CORS for all routesCreating an API Endpoint:
@app.route('/api/data', methods=['GET']) def get_data(): data = {'message': 'Hello, CORS!'} return jsonify(data)Running the Flask Application:
if __name__ == '__main__': app.run(debug=True)
Explanation:
Importing and Initializing CORS:
from flask_cors import CORS: Import theCORSclass from theflask_corsmodule.CORS(app): This line initializes CORS on your Flask application (app). This allows all origins to access resources served by your Flask app. You can also specify more granular options, such as origins, methods, headers, etc., depending on your requirements.
Creating an API Endpoint:
@app.route('/api/data', methods=['GET']): Defines a route/api/datathat responds to GET requests.def get_data():Function that returns a JSON response ({'message': 'Hello, CORS!'}) when/api/datais accessed.
Running the Flask Application:
app.run(debug=True): Starts the Flask development server.
Additional Configuration:
You can configure CORS further by passing additional parameters to CORS():
This configuration allows all origins (*) to access routes under /api.
Conclusion:
Enabling CORS in Flask using Flask-CORS is straightforward and allows your web application to interact safely with resources from different origins. It's crucial for building modern web applications that involve AJAX requests or cross-domain API calls.
Last updated