Flask:Cookie
项目结构:

文件:app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# coding: utf8 from flask import Flask, render_template, request, make_response app = Flask(__name__) @app.route('/') def hello_world(): # return 'Hello World!' return render_template('index.html') @app.route('/cookie-set',methods=['POST','GET']) def setcookie(): if request.method == 'POST': data_message = request.form['str_message'] # return data_message # 没有问题,可以拿到前面表单提交的值 response = make_response(render_template('response.html')) response.set_cookie('Message', data_message) return response @app.route('/cookie-get',methods=['POST','GET']) def getcookie(): if request.method == 'POST': str_cookie_name = request.form['cookie_name'] cookie_value = request.cookies.get(str_cookie_name) return render_template('cookie_result.html', name=str_cookie_name,value=cookie_value) if __name__ == '__main__': app.run() |
文件:index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
< !DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Hello world</title> </head> <body> <h2>Hello world.</h2> <form action="/cookie-set" method="post"> <p>信息:<input type="text" name="str_message" /></p> <p><input type="submit" value="submit" /></p> </form> </body> </html> |
文件:response.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
< !DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Response Page</title> </head> <body> <table border="1"> {% for key,value in request.cookies.items() %} <tr> <th>{{ key }}</th> <td>{{ value }}</td> </tr> {% endfor %} </table> <form action="/cookie-get" method="post"> <input type="text" name="cookie_name" /> <input type="submit" value="Get Target Cookie" /> </form> </body> </html> |
文件:cookie_result.html
1 2 3 4 5 6 7 8 9 10 11 |
< !doctype html> <table border="1"> <tr> <th>Cookie名称</th> <td>Cookie数值</td> </tr> <tr> <th>{{ name }}</th> <td>{{ value }}</td> </tr> </table> |
执行效果:


