前回はRequestの色々(Current_appなど)をご紹介しましたが、今回はResponseをご紹介します。
Responseは
1. HTTPのステータスコード:Flaskは200しかデフォルトで用意していないので、404のページは自分で作ります。
アプリケーションのエラーの処理 — Flask Documentation (2.0.x)
2. make_response:HTTPのステータスコードの返しより、カスタマイズした表示を設定できます。
3. redirect:どこかのURLにリダイレクトでページを飛ばします。
4. abort:リクエストを早い段階でエラーコードと一緒に異常終了させる際に使います。
クイックスタート — Flask Documentation (2.0.x)
1.の例
@app.route('/')
def index():
return '<h1>Bad Request</h1>', 400
2.の例
from flask import make_response
@app.route('/')
def index():
response = make_response('<h1>This document carries a cookie!</h1>')
response.set_cookie('answer', '42')
return response
3.の例
from flask import redirect
@app.route('/')
def index():
return redirect('https://cloud.google.com/functions/docs/first-python?hl=ja')
4.の例
from flask import abort
@app.route('/user/<id>')
def get_user(id):
user = load_user(id)
if not user:
abort(404)
return '<h1>Hello, %s</h1>' % user.name
全て
from flask import Flaskapp = Flask(__name__)
と
if __name__=='__main__':
app.run(debug=True)
の間に書いて、http://127.0.0.1:5000/で表示させて確認してね。
Amazon | Flask Web Development: Developing Web Applications with Python | Grinberg, Miguel | Software Development
Amazon配送商品ならFlask Web Development: Developing Web Applications with Pythonが通常配送無料。更にAmazonならポイント還元本が多数。Grinberg, Miguel作品ほか、お急ぎ便対象商品は当日お届けも可能。
前回の記事はこちら
次回の記事はこちら
コメント
[…] […]