7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

bottleでCORSに対応

Posted at

bottleでCORSを使う方法について自分なりにまとめてみた

#きっかけ
自作APIと外部APIの連携する処理を作ったが正常に処理されない...

#結論
CORSへの対応が必要

参考
CORSまとめ
https://qiita.com/tomoyukilabs/items/81698edd5812ff6acb34

#解決策
こちらのgithubのソースをいただいた

参考
Bottle with Cross-origin resource sharing (CORS)
https://gist.github.com/richard-flosi/3789163

hook機能を使ってリクエスト処理の最後にヘッダを付与している

Allow-Originヘッダがワイルドカードだと外部API側で警告っぽい応答をされてしまったので、リクエストヘッダからURLを打ち込んでやった

そしてAllow-HeadersヘッダにAuthorizationが必要だったので追加

routes.py
@app.hook('after_request')
def enable_cors():

    if not 'Origin' in request.headers.keys():
        return

    response.headers['Access-Control-Allow-Origin']  = request.headers['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, Authorization'

また、OPTIONSメソッドにレスポンスを返す処理が必要だったので以下のように実装

routes.py
@app.route('<any:path>', method='OPTIONS')
def response_for_options(**kwargs):
    return {}

hook機能についてはこちら

参考
API Reference
http://bottlepy.org/docs/dev/api.html#bottle.Bottle.add_hook
Recipes
http://bottlepy.org/docs/dev/recipes.html#using-the-hooks-plugin

毎リクエスト毎に実施する処理があればhookに置き換えていきたい

7
5
0

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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?