python flask access-control-allow-origin
- Import the necessary modules:
from flask import Flask, jsonify
- Create a Flask application:
app = Flask(__name__)
- Define a route with a sample endpoint that returns a JSON response:
@app.route('/sample_endpoint')
def sample_endpoint():
data = {'message': 'Hello, this is a sample endpoint!'}
return jsonify(data)
- Enable CORS (Cross-Origin Resource Sharing) by using the
after_request
decorator to modify response headers:
@app.after_request
def add_cors_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*' # Allow requests from any origin
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE' # Specify allowed HTTP methods
response.headers['Access-Control-Allow-Headers'] = 'Content-Type' # Specify allowed headers
return response
- Run the Flask application:
if __name__ == '__main__':
app.run(debug=True)
- Optionally, you can specify the host and port when running the application:
app.run(debug=True, host='0.0.0.0', port=5000)
Note: This example provides a basic structure for a Flask application with CORS support. Adjust the route, endpoint, and CORS headers according to your specific requirements.