w3cschool Flask教程中关于cookie的设置代码不完整,完整如下:
主程序:
from flask import Flask, render_template, request,make_response
app = Flask(__name__)
@app.route('/')
def index():
return render_template('new5.html')
@app.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
if request.method == 'POST':
user = request.form['nm']
resp = make_response(render_template('new55.html')) #make_response 创建一个返回对象,不能直接写HTML文件要,从模板引用即render_template('new55.html')
resp.set_cookie('userID', user) #为返回设置 set-cookie字段,字段内容为userID=****
return resp
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
return ('<h1>welcome '+str(name)+'</h1>')
if __name__ == '__main__':
app.run(debug=True)
new5.html 文件
<!DOCTYPE html>
<html>
<body>
<form action = "/setcookie" method = "POST">
<p><h3>Enter userID</h3></p>
<p><input type = 'text' name = 'nm'/></p>
<p><input type = 'submit' value = 'Login'/></p>
</form>
</body>
</html>
new55.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>111111</title>
</head>
<body>
<h1>HIssssssssssss , Cookies UserID is set</h1>
<a href="http://localhost:5000/getcookie">Click to read Cookies</a>
</body>
</html>
request,redirect,make_response用法总结:
一、request 请求
from flask import request
app = Flask(__name__)
@app.route('/get_request', methods=['GET', 'POST'])
def get_request():
if request.method == 'GET':
args = request.args
else:
form = request.form
return '获取request'
flask中,要获取get请求的参数,不是通过request.GET.get(),而是通过request.args.get()获取
二、redirect 跳转
1.参数是url形式
@app.route('/redirect/')
def make_redirect():
return redirect('/hello/index/')
2.参数是 name.html 形式
url_for 是地址的反向解析,可以到达这个html文件在网页中的地址
app.route('/redirect/')
def make_redirect():
return redirect(url_for('first.index'))
三、make_response 响应
1.返回内容
@app.route('/make_respon/')
def make_respon():
response = make_response('<h2>羞羞哒</h2>')
return response, 404
2.返回页面
@app.route('/make_respo/')
def make_respon():
temp = render_template('hello.html')
response = make_response(temp)
return response
#make_response 想要返回页面,不能直接写做:make_response('hello.html'),必须用render_template('hello.html')形式。