flask之请求响应
一、请求响应
from flask import Flask
from flask import request
from flask import render_template
from flask import redirect
from flask import make_response
app = Flask(__name__)
@app.route('/login.html', methods=['GET', "POST"])
def login():
# 请求相关信息
# request.method 提交的方法
# request.args get请求提及的数据
# request.form post请求提交的数据
# request.values post和get提交的数据总和
# request.cookies 客户端所带的cookie
# request.headers 请求头
# request.path 不带域名,请求路径
# request.full_path 不带域名,带参数的请求路径
# request.script_root
# request.url 带域名带参数的请求路径
# request.base_url 带域名请求路径
# request.url_root 域名
# request.host_url 域名
# request.host 127.0.0.1:500
# request.files
# obj = request.files['the_file_name']
# obj.save('/var/www/uploads/' + secure_filename(f.filename))
# 响应相关信息
# return "字符串"
# return render_template('html模板路径',**{})
# return redirect('/index.html')
#return jsonify({'k1':'v1'})
# response = make_response(render_template('index.html'))
# response是flask.wrappers.Response类型
# response.delete_cookie('key')
# response.set_cookie('key', 'value')
# response.headers['X-Something'] = 'A value'
# return response
return "内容"
if __name__ == '__main__':
app.run()
二、session
cookie:存放在客户端的键值对
session:存放在客户端的键值对
token:存放在客户端,通过算法来校验
再使用session之前必须设置一下密钥
app.secret_key="asdas" #值随便
使用session
设置:session['username'] = 'xxx'
#在django中发什么三件事,1,生成一个随机的字符串 2 往数据库存 3 写入cookie返回浏览器
#在flask中他没有数据库,但session是怎样实现的?
# 生成一个密钥写入这个cookie,然后下次请求的时候,通过这个cookie解密,然后赋值给session
#我们通过app.session_interface来查看
删除:session.pop('username', None)
from flask import Flask,session
app = Flask(__name__)
app.secret_key="sdasjdiashdiah"
app.config["SESSION_COOKIE_NAME"]="jason"
# app.session_interface
@app.route("/")
def index():
# 设置session
session['name']="jason"
return "ok"
@app.route("/index")
def index1():
# 取出session
print(session['name'])
return "123"
if __name__ == '__main__':
app.run()
三、小案例
from flask import Flask,render_template,request,redirect,session,url_for
app = Flask(__name__)
app.debug = True
app.secret_key = 'asodjoasijdas'
USERS = {
1:{'name':'张三','age':18,'gender':'男','text':"道路千万条"},
2:{'name':'李四','age':28,'gender':'男','text':"安全第一条"},
3:{'name':'王五','age':18,'gender':'女','text':"行车不规范"},
}
# 使用路由转换器(有名分组)+指定请求方式
@app.route('/detail/<int:nid>',methods=['GET'])
def detail(nid):
# 取session
user = session.get('user_info')
if not user:
return redirect('/login')
info = USERS.get(nid)
# 模板渲染并传值
return render_template('detail.html',info=info)
@app.route('/home',methods=['GET'])
def home():
# 取出session
user = session.get('user_info')
if not user:
# 反向解析到login页面
url = url_for('l1')
return redirect(url) # 重定向
# 模板渲染饼传值
return render_template('home.html',user_dict=USERS)
# 指定请求方式,指定别名
@app.route('/login',methods=['GET','POST'],endpoint='l1')
def login():
# 请求方式
if request.method == "GET":
return render_template('login.html')
else:
# 获取post请求的数据
user = request.form.get('user')
pwd = request.form.get('pwd')
if user == 'cxw' and pwd == '123':
# 设置session
session['user_info'] = user
return redirect('/home')
return render_template('login.html',error='用户名或密码错误')
if __name__ == '__main__':
app.run()
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户登录</h1>
<form method="post">
<input type="text" name="user">
<input type="text" name="pwd">
<input type="submit" value="登录">{{error}}
</form>
</body>
</html>
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table>
{% for index,items in user_dict.items() %}
<tr>
<td>{{index}}</td>
<td>{{items.name}}</td>
<td>{{items['name']}}</td>
<td>{{items.get('name')}}</td>
<td><a href="{{url_for('detail',nid=index)}}">查看详细</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>
detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>详细信息 {{info.name}}</h1>
<div>
{{info.text}}
</div>
</body>
</html>