Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Install a handler instead of a hook.</p> <p>There are two complementary ways I've done this in the past: decorator, or Bottle plugin. I'll show you both and you can decide whether one (or both) of them suit your needs. In both cases, the general idea is: a handler intercepts the response before it's sent back to the client, inserts the CORS headers, and then proceeds to return the response.</p> <h3>Method 1: Install Per-route (Decorator)</h3> <p>This method is preferable when you only want to run the handler on some of your routes. Just decorate each route that you want it to execute on. Here's an example:</p> <pre><code>import bottle from bottle import response # the decorator def enable_cors(fn): def _enable_cors(*args, **kwargs): # set CORS headers 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('/cors', method=['OPTIONS', 'GET']) @enable_cors def lvambience(): response.headers['Content-type'] = 'application/json' return '[1]' app.run(port=8001) </code></pre> <h3>Method 2: Install Globally (Bottle Plugin)</h3> <p>This method is preferable if you want the handler to execute on all or most of your routes. You'll just <a href="http://bottlepy.org/docs/dev/plugindev.html" rel="noreferrer">define a Bottle plugin</a> once, and Bottle will automatically call it for you on every route; no need to specify a decorator on each one. (Note that you can use a route's <code>skip</code> parameter to avoid this handler on a per-route basis.) Here's an example that corresponds to the one above:</p> <pre><code>import bottle from bottle import response class EnableCors(object): name = 'enable_cors' api = 2 def apply(self, fn, context): def _enable_cors(*args, **kwargs): # set CORS headers 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('/cors', method=['OPTIONS', 'GET']) def lvambience(): response.headers['Content-type'] = 'application/json' return '[1]' app.install(EnableCors()) app.run(port=8001) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload