cookie实现案例的代码
时间: 2023-10-26 07:18:27 浏览: 42
以下是一个使用 Flask 框架实现 cookie 的示例代码:
```python
from flask import Flask, render_template, request, make_response
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/setcookie', methods=['POST'])
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')
return '<h1>Welcome ' + name + '!</h1>'
if __name__ == '__main__':
app.run(debug=True)
```
在上述代码中,我们通过 `make_response()` 方法创建一个响应对象,并通过调用 `resp.set_cookie()` 方法来设置 cookie。然后在 `getcookie()` 视图函数中,我们使用 `request.cookies.get()` 方法来获取 cookie 的值,并将其显示在页面上。
同时,我们需要在 HTML 模板中添加表单来提交数据,如下所示:
```html
<!DOCTYPE html>
<html>
<head>
<title>Set Cookie</title>
</head>
<body>
<h1>Enter Your Name</h1>
<form action="{{ url_for('setcookie') }}" method="POST">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
```
最后,我们也需要添加一个读取 cookie 值的 HTML 页面,如下所示:
```html
<!DOCTYPE html>
<html>
<head>
<title>Read Cookie</title>
</head>
<body>
<h1>Cookie has been set</h1>
<a href="{{ url_for('getcookie') }}">Click here to read the cookie</a>
</body>
</html>
```