Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

bottleでCORSに対応

More than 1 year has passed since last update.

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に置き換えていきたい

rysk_lunch
楽するために苦労する
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away