以下是一个简单的 Flask 应用程序,演示如何使用 Cookie:
from flask import Flask, request, render_template, make_response
app = Flask(__name__)
@app.route('/')
def index():
# 从请求中获取名为 'username' 的 Cookie,如果不存在则返回 'Guest'
username = request.cookies.get('username', 'Guest')
return render_template('index.html', username=username)
@app.route('/set_cookie/<username>')
def set_cookie(username):
# 设置名为 'username' 的 Cookie,有效期为 1 小时
response = make_response(render_template('set_cookie.html', username=username))
response.set_cookie('username', username, max_age=3600)
return response
@app.route('/clear_cookie')
def clear_cookie():
# 清除名为 'username' 的 Cookie
response = make_response(render_template('clear_cookie.html'))
response.delete_cookie('username')
return response
if __name__ == '__main__':
app.run(debug=True)
在这个例子中,有三个路由:
1. /:显示一个欢迎页面,从请求中获取名为 'username' 的 Cookie,如果 Cookie 不存在则默认为 'Guest'。
2. /set_cookie/<username>:设置名为 'username' 的 Cookie,有效期为 1 小时。
3. /clear_cookie:清除名为 'username' 的 Cookie。
在模板文件中,你可以使用 {{ username }} 来显示 Cookie 中的值。
模板文件 index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Cookies</title>
</head>
<body>
<h1>Welcome, {{ username }}!</h1>
<p><a href="{{ url_for('set_cookie', username='John') }}">Set Cookie</a></p>
<p><a href="{{ url_for('clear_cookie') }}">Clear Cookie</a></p>
</body>
</html>
模板文件 set_cookie.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Cookie</title>
</head>
<body>
<h1>Cookie set for {{ username }}</h1>
<p><a href="{{ url_for('index') }}">Go back</a></p>
</body>
</html>
模板文件 clear_cookie.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clear Cookie</title>
</head>
<body>
<h1>Cookie cleared</h1>
<p><a href="{{ url_for('index') }}">Go back</a></p>
</body>
</html>
这只是一个简单的示例,你可以根据需要扩展和修改。在实际应用中,务必注意安全性和隐私问题,不要将敏感信息存储在 Cookie 中。
转载请注明出处:http://www.zyzy.cn/article/detail/7307/Flask