Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify domains for Flask-CORS

Tags:

python

cors

flask

I have a Python script serving as web api and many domains will call this to get data they want. So to make this workable I need to enable CORS. I read through the Flask documentation but did not find the way to specify multiples domains to allows CORS for them.

Here is code snippet that enables CORS:

from flask_cors import cross_origin

@app.route("/")
@cross_origin()

The above snippet enables CORS for all the domains. I want to restrict this to some specific list of domains. All I want to know how I can specify this list. Here is what I am trying to do:

@cross_origin(["www.domain1.com, www.domain2.com"])
like image 797
D Deshmane Avatar asked Feb 06 '23 11:02

D Deshmane


1 Answers

From the documentation of CORS: http://flask-cors.corydolphin.com/en/latest/api.html?highlight=origin#flask_cors.cross_origin

flask_cors.cross_origin(*args, **kwargs)

The origin, or list of origins to allow requests from. The origin(s) may be regular expressions, case-sensitive strings, or else an asterisk

So, here you need to give list of string. Like:

cross_origin(["http://www.domain1.com", "http://www.domain2.com"]) 

Notice here that you were giving all domain in a single string. But you needed to provide a list. Also notice that you provide Fully Qualified Domain Name (FQDN) as per RFC 6454 and W3C Recommendation.

You can also do something like this:

cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

Here we're allowing every path in our app which starts with /api. Depending on your requirement, you can define appropriate path here. Here you can also specify origins to a list of domains you want to enable CORS for, like this:

cors = CORS(app, resources={r"/api/*": {"origins": ["http://www.domain1.com", "http://www.domain2.com"]}})

Here is the link to the code I've written: https://github.com/Mozpacers/MozStar/

CORS doesn't do anything special; you just need to reply to the request with a special header which says that Access-Control-Allow-Origin contains the domain request is coming from.

For pre-flight requests, you can see how you can reply with custom headers with Flask before_request and after_request decorators: https://github.com/CuriousLearner/TrackMyLinks/blob/master/src/server/views.py#L130

like image 67
Sanyam Khurana Avatar answered Feb 13 '23 07:02

Sanyam Khurana