LoginSignup
4

More than 5 years have passed since last update.

Bottleのhookを使ってレスポンスヘッダを付与する

Last updated at Posted at 2016-05-22

概要

Pythonの軽量フレームワークであるBottleで、CORS(Cross-Origin Resource Sharing)のためにレスポンスヘッダを付与します。この記事では、公式ドキュメントのRecipeに書かれている標準的な方法を記載しています。

Recipes — Bottle 0.13-dev documentation

コード

Bottleではhookというデコレータを使って、関数が実行される前後に処理を追加することができます。これを使うことにより以下のコードのように@hook('after_request')でWebAPIから返されるレスポンスすべてにレスポンスヘッダを設定することができます。


from bottle import hook, response

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

感覚的にはレスポンスヘッダはとりあえず全部@hook('after_request')の中に記述しておけば良いということで、内部処理実装と分けて管理することができて便利です。

最後に、実際にcurlを使ってレスポンスヘッダに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

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4