English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask Cookie処理

Cookieはクライアントのコンピュータ上にテキストファイルの形式で保存されます。目的は、顧客の使用に関するデータを覚え、追跡し、より良いアクセス体験とウェブサイト統計を提供することです。

リクエストオブジェクトにはcookieの属性が含まれています。これは、クライアントが送信したすべてのcookie変数および対応する値の辞書オブジェクトです。これに加えて、cookieには有効期限、パス、ドメイン名が保存されます。

Flaskでは、cookiesはレスポンスオブジェクト上に設定されます。ビュー関数の返り値からレスポンスオブジェクトを取得するためにmake_response()関数を使用します。その後、レスポンスオブジェクトのset_cookie()関数を使用してcookieを保存します。

cookieを再読み込みするのは簡単です。request.cookies属性のget()メソッドを使用してcookieを読み取ることができます。

以下のFlaskアプリケーションでは、URL => / この場合、簡単なフォームが開かれます。

# Filename: example.py
# Copyright : 2020 By w3codebox
# Author by: ja.oldtoolbag.com
# Date : 2020-08-08
@app.route('/)
 def index():
     return render_template('index.html')

このHTMLページにはテキスト入力が含まれており、以下の完全なコードが示されています -

# Filename: example.py
# Copyright : 2020 By w3codebox
# Author by: ja.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Cookiesサンプル</title>
 </head>
    <body>
       <form action=""/setcookie" method="POST">
          <p><h3>userIDを入力</h3></p>
          <p><input type='text' name='name'>/></p>
          <p><input type='submit' value='ログイン'>/></p>
       </form>
    </body>
 </html>

フォームはURL => /setcookie。関連するビュー関数は、:userIDという名前のcookieを設定し、別のページで表示します。

# Filename: example.py
# Copyright : 2020 By w3codebox
# Author by: ja.oldtoolbag.com
# Date : 2020-08-08
@app.route('/setcookie, methods=['POST', 'GET'])
 def setcookie():
    if request.method == 'POST':
         user = request.form['name']
         resp = make_response(render_template('readcookie.html'))
         resp.set_cookie('userID', user)
         return resp

readcookie.htmlには、別の関数getcookie()にリンクする超リンクが含まれており、その関数はcookie値を読み取り、ブラウザで表示します。

# Filename: example.py
# Copyright : 2020 By w3codebox
# Author by: ja.oldtoolbag.com
# Date : 2020-08-08
@app.route('/getcookie)
 def getcookie():
     name = request.cookies.get('userID')
     return '<h1>welcome ''+name+"</h1"

以下は完全なアプリケーションコードです -

# Filename: example.py
# Copyright : 2020 By w3codebox
# Author by: ja.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask
 from flask import render_template
 from flask import request
 from flask import make_response
 app = Flask(__name__)
 @app.route('/)
 def index():
     return render_template('index.html')
 @app.route('/setcookie, methods=['POST', 'GET'])
 def setcookie():
     if request.method == 'POST':
         user = request.form['name']
         resp = make_response(render_template('readcookie.html'))
         resp.set_cookie('userID', user)
         return resp
 @app.route('/getcookie)
 def getcookie():
     name = request.cookies.get('userID')
     print(name)
     return '<h1>ようこそ、"+name+"</h1"
 if __name__ == '__main__':
     app.run(debug=True)

このアプリケーションを実行し、URLにアクセス => http://localhost:5000/cookieの設定結果は以下の通りです -

cookieの読み出しの出力は以下の通りです -