python flask access-control-allow-origin

  1. Import the necessary modules:
from flask import Flask, jsonify
  1. Create a Flask application:
app = Flask(__name__)
  1. 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)
  1. 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
  1. Run the Flask application:
if __name__ == '__main__':
    app.run(debug=True)
  1. 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.