python-web框架Flask-(三)request模块
request模块方法:客户端请求,flask中获取客户端的信息,需要用到request首先要引入模块:from flask import request1、request.method 查看请求方式# 用户请求http://localhost:5000/login 会执行下边视图函数@app.route('/login',methods=['GET','POST...
request模块方法:
客户端请求,flask中获取客户端的信息,需要用到request
首先要引入模块:
from flask import request
1、request.method 查看请求方式
# 用户请求http://localhost:5000/login 会执行下边视图函数
@app.route('/login',methods=['GET','POST'])
def fn():
if request.method == 'POST': # 判断用户请求是否是post请求
pass
else:
pass
2、request.form 获取 " POST " 相关请求提交过来的数据
@app.route('/login',methods=['GET','POST'])
def fn():
if request.method == 'POST': # 判断用户请求是否是post请求
print(request.form) # ImmutableMultiDict([('user_name', '吕星辰'), ('user_password', '123456')])
print(request.form.get('user_name')) # 吕星辰
print(request.form.to_dict()) # {'user_name': '吕星辰', 'user_password': '123456'}
上边代码,模拟了前端表单 post请求,在flask中,对于post请求,获取数据使用form,获取到的是一个对象,可使用get方法获取对应的数据(如果没有数据,get方法会返回None,但是用其他获取单个数据方式会报错!!!),也可以使用to_dict( )方法转化为字典。
3、request.args 获取 " GET " 提交过来的请求参数
@app.route('/login',methods=['GET','POST'])
def fn():
print(request.args) # ImmutableMultiDict([('user_name', '吕星辰'), ('user_password', '123')])
print(request.args.get('user_name')) # 吕星辰
print(request.args.to_dict()) # {'user_name': '吕星辰', 'user_password': '123'}
上边代码,同上,模拟前端表单get请求,在flask中,对于get请求,获取数据使用args,获取到的是一个对象,也可使用get方法获取对应的数据,也可以使用to_dict( )方法转化为字典。
4、request.path 获取斜线后边的url路径 (不包含根路径)
# 请求的是 http://0.0.0.0:9527/req?id=10
print(request.path) # '/req'
5、request.base_url 获取路径,包含根路径
#请求 http://0.0.0.0:9527/req?id=10
print(request.base_url) # 'http://0.0.0.0:9527/req'
6、request.headers 获取请求头信息
'''
Accept: text/html, application/xhtml+xml, */*
Content-Type: application/x-www-form-urlencoded
Accept-Language: zh-CN
Accept-Encoding: gzip, deflate
Host: localhost:5000
Content-Length: 55
Connection: Keep-Alive
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like GeckoCore/1.70.3704.400 QQBrowser/10.4.3587.400
'''
7、request.host获取根路径
# 请求路径为 http://0.0.0.0:9527/req?id=10
print(request.host) # http://0.0.0.0:9527
8、request.host_url 获取根路径,包含后边斜线
# 请求路径为 http://0.0.0.0:9527/req?id=10
print(request.host) # http://0.0.0.0:9527/
9、request.remote_addr 访问的远端ip地址
10、request.files 文件上传
补充下:
ImmutableMultiDict([ ]) 是一个类字典,是不可变的数据类型(元祖、字符串也是不可变的);与字典不同的是,类字典可以储存相同key,args和form都是类字典对象,从ImmutableMultiDict获取数据,有两种方法:
(1) dict[ 'param' ]
(2) dict.get( 'param' ) ( 推荐 )
如果key对应多个值:dict.getList( ‘param’ ) 获取的是一个列表
二、Request 中methods
如果视图中含有多种请求方式,需要在路由中添加methods参数,配置请求方式,上边事例中已经出现过:
# 用户请求http://localhost:5000/login 会执行下边视图函数
@app.route('/login',methods=['GET','POST'])
def fn():
pass
以后会补充,先写这么多!!!
三、Request 中get_json( force=False,silent= False,cache=True)
先来看下源码:
@property
def json(self):
"""This will contain the parsed JSON data if the mimetype indicates
JSON (:mimetype:`application/json`, see :meth:`is_json`), otherwise it
will be ``None``.
"""
return self.get_json()
def _get_data_for_json(self, cache):
return self.get_data(cache=cache)
def get_json(self, force=False, silent=False, cache=True):
"""Parse and return the data as JSON. If the mimetype does not
indicate JSON (:mimetype:`application/json`, see
:meth:`is_json`), this returns ``None`` unless ``force`` is
true. If parsing fails, :meth:`on_json_loading_failed` is called
and its return value is used as the return value.
:param force: Ignore the mimetype and always try to parse JSON.
:param silent: Silence parsing errors and return ``None``
instead.
:param cache: Store the parsed JSON to return for subsequent
calls.
"""
request.json调用的是request.get_json( ) 这个函数,但是get_json这个函数默认情况下只对minmetype为 application/json的请求可以正确解析。并将数据作为json输出。
如果 minetype 不是Json格式( application/json ),则返回None,解决方法:除非force为True,get_json ( force=True ),它会忽略mimetype并始终尝试解析json。
--------------------------------------------------------------------------------------------------------------------------
看一个小例子:
我使用表单发送数据,后端用get_json( ) 输出结果为None !!!
<form action="http://localhost:5000/home" method="POST">
<input type="text" placeholder="请输入姓名" name="name">
<input type="password" placeholder="请输入密码" name="pass">
<input type="submit" placeholder="click">
</form>
@app.route('/home',methods=["GET","POST"])
def fn1():
if request.method == "POST":
data = request.get_json()
print(data) # None
return "POST"
这里有个坑,当表单提交为post请求时,post的数据其实是一个FormData,也就是说不是json格式的( FormData是客户端主体部分组装数据的一种方式 )

而请求头中,content-type 为 Content-Type : application/x-www-form-urlencoded ,不是application/json 所以使用get_json 解析数据 返回的是None。
上述请求,使用flask接收请求的方式用:request.form 方法

下边我们把发送方式改成使用axios发送,在看下结果输出了的解析好的数据:
前端代码:
<input type="text" placeholder="请输入姓名" name="name" v-model="getUser">
<input type="password" placeholder="请输入密码" name="pass" v-model="getPass">
<button @click="sendInfo">click</button>
export default {
name:'play',
methods:{
sendInfo(){
this.$axios.post('http://localhost:5000/home',{
userName:this.getUser,
userPass:this.getPass
})
.then(res=>{
console.log(res)
})
}
}
}
后端代码:
@app.route('/home',methods=["GET","POST"])
def fn():
if request.method == "POST":
data = request.get_json()
print(data) # ImmutableMultiDict([('name', 'safda'), ('pass', 'dsaf')])
return "POST"
之所以使用axios发送数据,后端使用get_json 可以正常获取数据原因,使用axios发送的数据是一个PayLoad,它是一种以json格式进行数据传输的一种方式,也就是说是json格式的:

请求头content-type 为 application /json ,所以要使用get_json( ) 方法去获取数据,使用request.form 无法获取 用时axios post请求的数据!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

四、request .get_json( ) 和 request .form的区别
针对前端get请求没有区别,使用表单 post请求数据时,使用request.form无法获取数据,需要使用get_json()来获取数据!!!
什么是mimetype
(
mimetype说穿了其实指的就是文件后缀名。
你向web服务器请求一个文件,服务器会根据你的后缀名去匹配对应的值设置为response中content-type的值。
而content-type是正文媒体类型,游览器根据content-type的不同来分别处理你返回的东西。
)
更多推荐



所有评论(0)