Python 怎么将 requests 模块的发送请求打入到日志里面

啊神 · July 06, 2022 · Last by 啊神 replied at July 07, 2022 · 4101 hits

我想知道我执行的接口测试用例中,接口发送的请求是否正确,所以我想把 requests 发送的内容加入日志里面,
但一直只能在控制台输出相关信息,不能把请求写到日志文件里面

import requests
import logging
try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
a=http_client.HTTPConnection.debuglevel = 1
logger = logging.getLogger("requests.packages.urllib3")
file_handler = logging.FileHandler(r'C:\Users\ason\PycharmProjects\pythonProject\Zsk_Auto_API\Test_Data\log.txt',
                                   "a+", "UTF-8")
file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
# logger.propagate = True
logger.addHandler(file_handler)
logger.debug(requests.get("https://www.codenong.com/16337511/"))

最佳回复
import curlify
@staticmethod
def show_response(response):
    attach_text(f'以「{response.request.method}」方式请求「{response.url}」;'
                f'返回状态码为「{response.status_code}」'
                f'返回内容为「{response.text}」',
                "接口请求")
    attach_text(curlify.to_curl(response.request), "cURL")
    attach_text(response.url, "url")
    attach_text(response.request.method, "请求方式")
    attach_text(response.status_code, "状态码")
    attach_text(response.text, "返回内容-text")
    attach_text(response.json(), "返回内容-json")

把 attach_text 换成 logger.info

共收到 4 条回复 时间 点赞

我想知道我执行的接口测试用例中,接口发送的请求是否正确

  1. 直接查看脚本
  2. debug 跟踪下
啊神 #2 · July 07, 2022 Author
测试游记 回复

可以的,我查了一下 response 里面还有个 request 用来查发送的内容,把 request 调用起来就行了。

import curlify
@staticmethod
def show_response(response):
    attach_text(f'以「{response.request.method}」方式请求「{response.url}」;'
                f'返回状态码为「{response.status_code}」'
                f'返回内容为「{response.text}」',
                "接口请求")
    attach_text(curlify.to_curl(response.request), "cURL")
    attach_text(response.url, "url")
    attach_text(response.request.method, "请求方式")
    attach_text(response.status_code, "状态码")
    attach_text(response.text, "返回内容-text")
    attach_text(response.json(), "返回内容-json")

把 attach_text 换成 logger.info

啊神 #4 · July 07, 2022 Author
Thirty-Thirty 回复

如果批量跑用例,不能一直盯住去 DEBUG~,我还是趋向写进日志,报错了就可以去分析哪里错了

啊神 关闭了讨论 07 Jul 10:23
需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up