1 request
1.1 get请求
from flask import request
#get参数
variable = 'abcd'
request.args.get('variable')
#form数据
<form>
<input name="variable" type="text">
</form>
request.form.get('variable')
# json数据
{
"key":"xindaqi"
}
request.json.get("key")
1.2 post请求
from flask import request
{'variable':'abce', 'v':'value1'}
request.json['variable']
request.form['variable']
2 requests
2.1 请求方式
序号 | 请求方式 | 描述 |
---|---|---|
1 | HEAD | 请求页面头部 |
2 | GET | 请求指定的页面信息,并返回实体主体 |
3 | POST | 向指定资源提交数据进行处理请求,数据包含在请求体中,POST请求可能会导致新的资源建立或已有资源的修改 |
4 | PUT | 从客户端向服务器传送的数据取代指定的文档内容 |
5 | DELETE | 请求服务器删除指定页面 |
2.2 注意:配置Content-Type
post请求有请求体时,必须指定请求体类型:Content-Type
多个属性使用逗号隔开
headers = {"token": token, 'Content-Type': 'application/json'}
- 将数据转换为json格式的请求体
使用list作为参数,使用json.dumps(data)将请求体转换为json数据。
import requests
import json
"""构造请求头"""
headers = {"token": token, 'Content-Type': 'application/json'}
"""构造请求体"""
data = [{"uid":"0x111","name":"xiaoxiao"}, {"uid":"0x112","name":"xiaolan"}]
"""发送请求"""
response = requests.post(url, headers = headers, data=json.dumps(data))
"""将请求结果转换为json数据格式(dict)
供进一步解析
"""
json_response = response.json()
2.2 请求数据
- get
res = requests.get(url, data=None, json=None, headers=headers, **kwargs)
url:请求链接
data:请求数据,字典类型
json:请求数据,json类型
headers:请求头,json类型
**kwargs:request携带的参数
- post
res = requests.post(url, data=None, json=None, headers=headers, **kwargs)
url:请求链接
data:请求数据,字典类型
json:请求数据,json类型
headers:请求头,json类型
**kwargs:request携带的参数
2.2.1 字典类型数据
import requests
data = {'key1':'value1', 'key2':'value2'}
res = requests.post(url, data=data)
2.2.2 json数据
import requests, json
data = {'key1':'value1','data':{'key2':'value2'}}
headers = {"X-AuthToken":"from client"}
res = request.post(url, json=data, headers=headers)
2.2.3 form-data数据
import requests, json
url = "object url"
data = {
"name":(None, "xindaqi"),
"sex":(None, "male")
"image":("image.jpg", open("./path/image.jpg", "rb"))
}
res = requests.post(url, data=data)
print("Request body: {}".format(res.request.body))
print("Request headers: {}".format(res.request.headers))
- 结果信息
Request body: name=xindaqi&sex=male
Request headers: {'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '84', 'Content-Type': 'application/x-www-form-urlencoded'}
2.3 响应内容
序号 | 响应内容 | 描述 |
---|---|---|
1 | res.encoding | 获取当前编码 |
2 | res.encoding=‘utf-8’ | 设置编码 |
3 | res.text | 以encoding解析返回内容,返回数据类型为字符串 |
4 | res.content | 以字节形式bytes返回响应体 |
5 | res.headers | 以字典对象存储服务器响应头,该字典较特殊,字典的键不区分大小写,若键不存在返回None |
6 | res.status_code | 响应状态码 |
7 | res.raw | 返回原始响应体,及urllib的response对象,使用res.raw.read |
8 | res.ok | 查看res.ok的布尔值可知登陆是否成功 |
9 | res.json | 以json格式返回请求内容,返回数据类型为字典类型dict |
10 | res.raise_for_status() | 失败请求(非200响应)抛出异常 |
2.4 返回数据
- requests.models.Response格式
res = requests.post(url, json=data)
print(type(res))
# 结果
<class 'requests.models.Response'>
- dict格式
res = requests.post(url, json=data)
res = res.json()
print(type(res))
# 结果
<class 'dict'>
- str格式
res = requests.post(url, json=data)
res = res.json()
res = json.dumps(res)
print(type(res))
# 结果
<class 'str'>
- flask.wrappers.Response格式(Json格式)
res = requests.post(url, json=data)
res = res.json()
res = json.dumps(res)
res = Response(res, mimeType="application/json")
print(type(res))
# 结果
<class 'flask.wrappers.Response'>
- flask.wrappers.Response格式(Json格式)
import requests
from flask import jsonify
res = requests.post(url, json=data)
res = res.json()
res = jsonify(res)
print(type(res))
# 结果
<class 'flask.wrappers.Response'>
2.5 头信息及请求体数据获取
2.5.1 场景
客户端:请求服务端,携带头信息和请求体信息;
服务端:接受客户端请求,获取客户端携带的头信息和请求体信息;
2.5.2 应用
- 客户端client.py
import requests
url = "http://127.0.0.1:8090/api/header-infos"
data = {"name":"xiaohong", "address":"heilongjiang"}
headers = {"X-AuthToken":"from client"}
res = requests.post(url, json=data, headers=headers)
- 服务端server.py
from flask import Flask, request, Blueprint
from flask_cors import CORS
header_infos = Blueprint("header_info", __name__, url_prefix="/api")
@header_infos.route("/header-infos", methods=["GET", "POST"])
def header_test():
'''
headers: Cache-Control: no-cache
Postman-Token: f5c59a9a-475d-466b-bb2d-64c48ad8f07a
User-Agent: PostmanRuntime/7.2.0
Accept: */*
Host: localhost:8090
Cookie: JSESSIONID=F86435226AF347A3890C6D2D5CE39ED8
Accept-Encoding: gzip, deflate
Connection: keep-alive
'''
header_full_infos = request.headers
# reqeuest header information
header_authentication = header_full_infos["X-AuthToken"]
# reqeust body information
request_body = request.json["name"]
print("header full information:\n{}".format(header_full_infos))
print("type of headers:\n{}".format(type(header_full_infos)))
print("Header authentication:\n{}".format(header_authentication))
print("Body:\n{}".format(request_body))
return "success"
def init_app():
app = Flask(__name__)
app.register_blueprint(header_infos)
return app
app = init_app()
CORS(app, supports_credentials=True)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8090, debug=True)
- 过程
运行服务端:
python3.6 server.py
运行客户端
python3.6 client.py
- 结果
header full information:
Host: 127.0.0.1:8090
User-Agent: python-requests/2.22.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
X-Authtoken: from client
Content-Length: 47
Content-Type: application/json
type of headers:
<class 'werkzeug.datastructures.EnvironHeaders'>
Header authentication:
from client
Body:
xiaohong
3 urllib
请求url并解析参数模块。
3.1 py2和py3请求模块
python3使用:urllib.request
python2使用:urllib2
3.2 源
【python2:urllib2】
def py2request(url):
import urllib2
response = urllib2.urlopen(url)
response = response.read()
return type(response), response
if __name__ == "__main__":
url = "https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac071eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes"
# type_res, res = py2request(url)
type_res, res = py3request(url)
print("type of response: {}\n resposne: {}".format(type_res, res))
【Result】
type of response: <type 'str'>
resposne: {
0: 'tench, Tinca tinca',
1: 'goldfish, Carassius auratus',
2: 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias',
3: 'tiger shark, Galeocerdo cuvieri',
4: 'hammerhead, hammerhead shark',
}
【python3:urllib.request】
def py3request(url):
import urllib.request
# 打开url获取数据
response = urllib.request.urlopen(url)
# 数据解析,bytes格式
response = response.read()
return type(response), response
if __name__ == "__main__":
url = "https://gist.githubusercontent.com/aaronmarkham/cd3a6b6ac071eca6f7b4a6e40e6038aa/raw/9edb4038a37da6b5a44c3b5bc52e448ff09bfe5b/alexnet_codes"
# type_res, res = py2request(url)
type_res, res = py3request(url)
print("type of response: {}\n resposne: {}".format(type_res, res))
# python3中解码,转为字符串
response = res.decode("utf-8")
print("Response: {}".format(response))
【Result】
type of response: <class 'bytes'>
resposne: b'{\n 0: \'tench, Tinca tinca\',\n 1: \'goldfish, Carassius auratus\',\n 2: \'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias\',\n 3: \'tiger shark, Galeocerdo cuvieri\',\n 4: \'hammerhead, hammerhead shark\',}
Response: {
0: 'tench, Tinca tinca',
1: 'goldfish, Carassius auratus',
2: 'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias',
3: 'tiger shark, Galeocerdo cuvieri',
4: 'hammerhead, hammerhead shark',}
4 总结
- flask通过request及requests请求用于获取不同参数;
- request是flask内置,获取用户输入参数;
- requests获取url参数;
- python后台需返回字符串,基本以json字符串为主;
- python2请求url使用模块:urllib2,请求结果直接read()方法解析为字符串;
- python3请求url使用模块:urllib.request,请求结果使用read()方法解析为bytes,需要解码decode(“utf-8”)为字符串;
[参考文献]
[1]https://blog.csdn.net/mr_evanchen/article/details/77879967
[2]https://www.cnblogs.com/insane-Mr-Li/p/9145152.html
[3]https://blog.csdn.net/z714405489/article/details/83061867
[4]https://www.cnblogs.com/derek1184405959/p/8448875.html