[PYTHON] Add response headers using Bottle hook

Overview

Bottle, a lightweight Python framework, adds response headers for CORS (Cross-Origin Resource Sharing). This article describes the standard method described in the official documentation Recipe.

Recipes — Bottle 0.13-dev documentation

code

Bottle allows you to add processing before and after the function is executed using a decorator called hook. By using this, you can set the response header for all the responses returned from the Web API with @hook ('after_request') as shown in the code below.


from bottle import hook, response

@hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'

It is convenient to manage all response headers separately from the internal processing implementation because all response headers should be described in @hook ('after_request') for the time being.

Finally, use curl to see if the response header contains Access-Control-Allow-Origin.

$ curl --head http://localhost:8080/
HTTP/1.0 200 OK
Date: Sun, 22 May 2016 05:26:09 GMT
Server: WSGIServer/0.2 CPython/3.4.3
Content-Length: 12
Access-Control-Allow-Origin: *
Content-Type: text/html; charset=UTF-8

reference

Recommended Posts

Add response headers using Bottle hook
How to add arbitrary headers to response with FastAPI
Web application using Bottle (1)