Python请求requests,request

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 请求方式

序号请求方式描述
1HEAD请求页面头部
2GET请求指定的页面信息,并返回实体主体
3POST向指定资源提交数据进行处理请求,数据包含在请求体中,POST请求可能会导致新的资源建立或已有资源的修改
4PUT从客户端向服务器传送的数据取代指定的文档内容
5DELETE请求服务器删除指定页面

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 响应内容

序号响应内容描述
1res.encoding获取当前编码
2res.encoding=‘utf-8’设置编码
3res.text以encoding解析返回内容,返回数据类型为字符串
4res.content以字节形式bytes返回响应体
5res.headers以字典对象存储服务器响应头,该字典较特殊,字典的键不区分大小写,若键不存在返回None
6res.status_code响应状态码
7res.raw返回原始响应体,及urllib的response对象,使用res.raw.read
8res.ok查看res.ok的布尔值可知登陆是否成功
9res.json以json格式返回请求内容,返回数据类型为字典类型dict
10res.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


更新ing
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天然玩家

坚持才能做到极致

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值