add cors headers to a http server in python

To add CORS headers to a HTTP server in Python, you can use the Flask framework.

First, install Flask:

main.py
pip install flask
18 chars
2 lines

Then, add the following code to your server file:

main.py
from flask import Flask, jsonify

app = Flask(__name__)

# Add CORS headers to every response
@app.after_request
def after_request(response):
    header = response.headers
    header['Access-Control-Allow-Origin'] = '*'
    return response

# Define your server routes below
@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run()
379 chars
19 lines

This code adds a CORS header to every HTTP response by using the after_request decorator to modify the response headers. Specifically, it sets the Access-Control-Allow-Origin header to *, which allows cross-domain requests from any client.

You can define your server routes under the app.route decorator. For example, the code above defines a simple / route that returns Hello, World!.

Note that this code adds a very permissive CORS header (Access-Control-Allow-Origin: *), which may not be appropriate for all production use cases. To restrict CORS access to specific domains, you can replace * with the domain(s) you want to allow. For example, Access-Control-Allow-Origin: https://example.com allows requests from https://example.com only.

related categories

gistlibby LogSnag