Skip to content

Instantly share code, notes, and snippets.

@richard-flosi
Created September 26, 2012 16:55
Show Gist options
  • Save richard-flosi/3789163 to your computer and use it in GitHub Desktop.
Save richard-flosi/3789163 to your computer and use it in GitHub Desktop.
Bottle with Cross-origin resource sharing (CORS)
"""
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))
@kevinlondon
Copy link

I implemented it as two separate decorators, one for cors as a bottle.hook('after_request') and a separate one for allowing OPTIONS by doing something like this:

from functools import wraps

@bottle.install
def allow_options_requests(callback):
    @wraps(callback)
    def wrapper(*args, **kwargs):
        if bottle.request.method.lower() == 'options':
            return
        else:
            return callback(*args, **kwargs)
    return wrapper

@marymatt
Copy link

Gracias, gran aporte

@karelv
Copy link

karelv commented Sep 18, 2017

Here is also good article about cors in bottle:
https://www.toptal.com/bottle/building-a-rest-api-with-bottle-framework

from bottle import hook, route, response

_allow_origin = '*'
_allow_methods = 'PUT, GET, POST, DELETE, OPTIONS'
_allow_headers = 'Authorization, Origin, Accept, Content-Type, X-Requested-With'

@hook('after_request')
def enable_cors():
    '''Add headers to enable CORS'''

    response.headers['Access-Control-Allow-Origin'] = _allow_origin
    response.headers['Access-Control-Allow-Methods'] = _allow_methods
    response.headers['Access-Control-Allow-Headers'] = _allow_headers

@route('/', method = 'OPTIONS')
@route('/<path:path>', method = 'OPTIONS')
def options_handler(path = None):
    return

The hook decorator allows us to call a function before or after each request. In our case, to enable CORS we must set the Access-Control-Allow-Origin, -Allow-Methods and -Allow-Headers headers for each of our responses. These indicate to the requester that we will serve the indicated requests.

Also, the client may make an OPTIONS HTTP request to the server to see if it may really make requests with other methods. With this sample catch-all example, we respond to all OPTIONS requests with a 200 status code and empty body.

To enable this, just save it and import it from the main module.

@bosborne
Copy link

bosborne commented Mar 8, 2020

This code doesn't work for me unfortunately, I still see a "No 'Access-Control-Allow-Origin' header is present on the requested resource." error. I have localhost:4000 doing a POST to the Bottle server, on localhost:8080. Perhaps this is some sort of special case?

@richard-flosi
Copy link
Author

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/or Access-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?

@bosborne
Copy link

bosborne commented Mar 9, 2020

No, I was wrong. The code on top does work. Thank you for your prompt response.

@richard-flosi
Copy link
Author

@bosborne cool. I'm glad something I created 8 years ago is still relevant. Funny how that works. :)

@richard-flosi
Copy link
Author

@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