前言
requests 是 Hooks 即钩子方法,用于在某个框架固定的某个流程执行是捎带执行(钩上)某个自定义的方法。
requests 库只支持一个 response 的钩子,即在响应返回时可以捎带执行我们自定义的某些方法。
可以用于打印一些信息,做一些响应检查或想响应对象中添加额外的信息
使用示例
requests 库只支持一个 response 的钩子,即在响应返回时可以捎带执行我们自定义的某些方法.
# 作者-上海悠悠 微信/QQ交流:283340479
# blog地址 https://www.cnblogs.com/yoyoketang/
import requests
url = 'https://httpbin.org/get'
def response_status(resopnse, *args, **kwargs):
print('url', resopnse.url)
resopnse.status = 'PASS' if resopnse.status_code < 400 else 'FAIL'
res = requests.get(url, hooks={'response': response_status})
print(res.status)
执行结果
url https://httpbin.org/get
PASS
重写响应内容
我们在做接口自动化测试的时候,有时候会遇到响应的内容是加密的内容,需要对返回的内容先解密再输出加密后的内容,这样方便断言
以下是requests 库的 Response 部分源码
class Response:
"""The :class:`Response <Response>` object, which contains a
server's response to an HTTP request.
"""
__attrs__ = [
"_content",
"status_code",
"headers",
"url",
"history",
"encoding",
"reason",
"cookies",
"elapsed",
"request",
]
可以自己定义一个NewResponse类,重写几个属性和方法
# 作者-上海悠悠 微信/QQ交流:283340479
# blog地址 https://www.cnblogs.com/yoyoketang/
import requests
def decrypt_response(response, *args, **kwargs):
# print(response.text) 原始数据
class NewResponse:
text = '{"code": 0, "data": {"token": "yo yo"}}' # response.text解密
history = response.history
raw = response.raw
is_redirect = response.is_redirect
content = b'{"code": 0, "data": {"token": "yo yo"}}' # response.text解密
elapsed = response.elapsed
@staticmethod
def json():
# 拿到原始的response.json() 后解码
return {"code": 0, "data": {"token": "yo yo"}}
return NewResponse
url = "https://www.cnblogs.com/yoyoketang/"
r = requests.get(url, hooks={"response": decrypt_response})
print(r.text)
print(r.content)
print(r.json())
标签:status,yo,python,44,hook,url,print,requests,response
From: https://www.cnblogs.com/yoyoketang/p/16936869.html