How to enable cors in Python flask?

Estimated read time 2 min read

In Flask, a popular Python web framework, you can enable Cross-Origin Resource Sharing (CORS) to allow cross-origin requests from web browsers. CORS is a security feature implemented by web browsers that restricts web pages from making requests to a different domain than the one that served the web page. Here’s an example of how you can enable CORS in Flask:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

# Enable CORS for all routes
CORS(app)

# Your Flask routes and application logic go here

if __name__ == '__main__':
    app.run()

In this example, the flask_cors library is used to enable CORS in Flask. The CORS() function is called with the Flask app object as an argument to enable CORS for all routes in the Flask application. This will allow cross-origin requests from any domain to access your Flask application.

You can also configure CORS settings with more options, such as specifying origins, methods, headers, and other CORS-related parameters. Here’s an example of how you can specify CORS options:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

# Specify CORS options
cors = CORS(app, origins='http://example.com', methods=['GET', 'POST'], allow_headers=['Content-Type'])

# Your Flask routes and application logic go here

if __name__ == '__main__':
    app.run()

In this example, the origins parameter is set to 'http://example.com', which restricts cross-origin requests to only be allowed from the specified origin. The methods parameter is set to ['GET', 'POST'], which specifies the allowed HTTP methods for cross-origin requests. The allow_headers parameter is set to ['Content-Type'], which specifies the allowed request headers for cross-origin requests. You can customize these options based on your specific requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply