Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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))
@remkoning

This comment has been minimized.

Copy link

commented Feb 11, 2014

Thanks! Wouldn't of been able to get my angular app api calls to work otherwise.

@smancke

This comment has been minimized.

Copy link

commented Feb 17, 2014

Thanks, very helpful!

@poliveira89

This comment has been minimized.

Copy link

commented May 27, 2014

Awesome! :) Great gist, sure it will help me and other users of Bottle :) Thank you! 👍

@stemid

This comment has been minimized.

Copy link

commented Mar 5, 2015

I love your work because I had not been introduced to the concept of after_request hooks in bottle yet.

Though I have some questions you might be able to answer @richard-flosi. For one, this method is in essence the same as extending Bottle with a plugin.

Secondly, I know this might seem superfluous when the route is restricted to the methods in the method list but I still feel like the optimal way to handle CORS would be with a decorator that took optional arguments or a decorator that could access the routes method list. Because this way you could specify only the methods that your route supports in the 'Access-Control-Allow-Methods' header.

I tried creating such a decorator but it was pretty difficult and I failed, I started down a winding path of creating a decorator for my decorator with the end goal being that my real decorator could accept optional keyword arguments. Have you had any luck with this @richard-flosi?

@neatnick

This comment has been minimized.

Copy link

commented Jun 17, 2015

Very helpful gist. One thing that I would point out is that, for a DRY way of handling OPTIONS requests, rather than using the before_request hook, would be to create a custom decorator. The custom decorator could create a route for the OPTIONS method for every path specified in your app.

def route(**kwargs):
    def decorator(callback):
        kwargs['callback'] = callback
        app.route(**kwargs)

        kwargs['method'] = 'OPTIONS'
        kwargs['callback'] = lambda: {}
        app.route(**kwargs)
        return callback
    return decorator

@route(path='/examples', method='GET')
def examples():
    return {'examples': [{
        'id': 1,
        'name': 'Foo'},{
        'id': 2,
        'name': 'Bar'}
    ]}

Using the decorator as above would be the same as defining the two routes as shown below:

@app.route('/examples', method='OPTIONS')
def examples():
    return {}

@app.route('/examples', method='GET')
def examples():
    return {'examples': [{
        'id': 1,
        'name': 'Foo'},{
        'id': 2,
        'name': 'Bar'}
    ]}
@x2a-io

This comment has been minimized.

Copy link

commented May 31, 2016

Much love!

@AlexandreProenca

This comment has been minimized.

Copy link

commented Jun 30, 2016

Good!!!! thank you for share 🎯

@nidzrai

This comment has been minimized.

Copy link

commented Sep 11, 2016

and what to do if i have to make a post a call. i did something like this.

import bottle
from bottle import response
import json
import request
def enable_cors(fn):
def _enable_cors(_args, _kwargs):
response.headers['Access-Control-Allow-Origin'] = '
'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

    if bottle.request.method != 'OPTIONS':
        # actual request; reply with the actual response
        return fn(*args, **kwargs)
return _enable_cors

app = bottle.app()
@app.route('/api/postData', method=['OPTIONS','POST'])
@enable_cors
def get_counts():
data = json.loads(request.data.decode())
print (data);
return 'returning data'
app.run(port=8001)

@kevinlondon

This comment has been minimized.

Copy link

commented Feb 28, 2017

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

This comment has been minimized.

Copy link

commented Jul 13, 2017

Gracias, gran aporte

@karelv

This comment has been minimized.

Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.