Created
September 26, 2012 16:55
-
-
Save richard-flosi/3789163 to your computer and use it in GitHub Desktop.
Bottle with Cross-origin resource sharing (CORS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Example of setting up CORS with Bottle.py. | |
""" | |
from bottle import Bottle, request, response, run | |
app = Bottle() | |
@app.hook('after_request') | |
def enable_cors(): | |
""" | |
You need to add some headers to each request. | |
Don't use the wildcard '*' for Access-Control-Allow-Origin in production. | |
""" | |
response.headers['Access-Control-Allow-Origin'] = '*' | |
response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS' | |
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token' | |
@app.route('/examples', method=['OPTIONS', 'GET']) | |
def examples(): | |
""" | |
If you are using something like Spine.js you'll need to | |
handle requests for the OPTIONS method. I haven't found a | |
DRY way to handle this yet. I tried setting up a hook for before_request, | |
but was unsuccessful for now. | |
""" | |
if request.method == 'OPTIONS': | |
return {} | |
else: | |
return {'examples': [{ | |
'id': 1, | |
'name': 'Foo'},{ | |
'id': 2, | |
'name': 'Bar'} | |
]} | |
if __name__ == '__main__': | |
from optparse import OptionParser | |
parser = OptionParser() | |
parser.add_option("--host", dest="host", default="localhost", | |
help="hostname or ip address", metavar="host") | |
parser.add_option("--port", dest="port", default=8080, | |
help="port number", metavar="port") | |
(options, args) = parser.parse_args() | |
run(app, host=options.host, port=int(options.port)) |
No, I was wrong. The code on top does work. Thank you for your prompt response.
@bosborne cool. I'm glad something I created 8 years ago is still relevant. Funny how that works. :)
@stemid sorry I never responded to you or anyone else here before. I don't remember seeing any of these comments before or getting any notifications until yesterday.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Which code are you using? Are there additional error messages? This post was from 8 years ago, so I'm not sure how relevant it is anymore.
My guess is that your request requires additional options set in
Access-Control-Allow-Methods
and/orAccess-Control-Allow-Headers
.What does the request look like? What are the request headers? Is there something additional in the request headers that is missing from the response headers in your case?