To enable CORS (Cross-Origin Resource Sharing) in Python, especially if you’re using a simple HTTP server, you can either use a custom server script with CORS headers added or use a library like Flask for more control. Here are a few approaches to add CORS support depending on your setup.
The built-in Python HTTP server (http.server) does not support CORS by default, but you can customize it to add the necessary headers.
Create a file, say cors_server.py, and use the following code:
from http.server import HTTPServer, SimpleHTTPRequestHandler
class CORSRequestHandler(SimpleHTTPRequestHandler):
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
# Start the HTTP server with the custom CORS handler
if __name__ == "__main__":
server_address = ('', 8000) # Bind to all available IP addresses on port 8000
httpd = HTTPServer(server_address, CORSRequestHandler)
print("Serving on port 8000 with CORS enabled...")
Run this script:
This script:
- Creates an HTTP server on port
8000 that includes the necessary CORS headers, allowing all origins (*).
- Adds
GET, POST, and OPTIONS methods for broader compatibility.
You can now access the server with CORS enabled from other devices or browsers.
For more complex applications, or if you’re already using Flask, you can easily add CORS support using the flask-cors package.
-
Install Flask and flask-cors:
pip install Flask flask-cors
-
Create a Flask server with CORS enabled:
from flask import Flask, send_from_directory
from flask_cors import CORS
CORS(app) # This enables CORS for all routes
@app.route('/<path:filename>')
def serve_file(filename):
return send_from_directory('.', filename)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000)
-
Run the Flask app:
python3 your_flask_server.py
This Flask app will serve files from the current directory with CORS enabled for all routes, making it a good fit for local DASH or HLS testing.
If you prefer a simpler approach, use the http.server package combined with the cors option of http-server for CORS support:
npx http-server -p 8000 --cors
This allows for quick CORS-enabled file serving without additional Python scripting.