Flask-CORS is an extension for Flask that simplifies the process of handling Cross-Origin Resource Sharing (CORS) in web applications. CORS is a security feature implemented by browsers to prevent web pages from making requests to a different domain than the one that served the web page. This is particularly important for APIs that need to be accessed from different origins. By using Flask-CORS, developers can easily control which domains are allowed to make requests to their API endpoints, enhancing both security and functionality.
In this scenario, you have a Flask API that needs to allow requests from a frontend application hosted on a different domain. You want to enable CORS for all routes in your Flask app.
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # Enable CORS for all routes
@app.route('/data')
def data():
return {'message': 'Hello from Flask!'}
if __name__ == '__main__':
app.run(debug=True)
You have a public API and want to allow requests only from a specific frontend application hosted on https://myfrontend.com
. This approach improves security by limiting which domains can access your API.
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r'/data': {'origins': 'https://myfrontend.com'}})
@app.route('/data')
def data():
return {'message': 'Data sent to a specific origin!'}
if __name__ == '__main__':
app.run(debug=True)
origins
parameter, e.g., origins=['https://myfrontend.com', 'https://anotherdomain.com']
.In this example, your API needs to allow cross-origin requests for GET and POST methods but deny others, such as DELETE. This is useful for APIs where you want tighter control over which operations can be performed from different origins.
from flask import Flask, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r'/data': {'origins': '*', 'methods': ['GET', 'POST']}})
@app.route('/data', methods=['GET', 'POST'])
def data():
if request.method == 'POST':
return {'message': 'Data received!'}, 201
return {'message': 'Data sent!'}
if __name__ == '__main__':
app.run(debug=True)