例如请求前和请求后各来一条日志,这样就不需要在自己的每个代码都去加日志了。

其实也可以直接记录'urllib3.connectionpool'  logger name的日志。


修改了requests,所有requests的地方将自动打印日志,前提要给custom_request添加handlers
import requests
from app.utils.utils_ydf import LogManager logger = LogManager('custom_request').get_logger_without_handlers() class CustomSession(requests.Session):
def request(self, method, url,
params=None, data=None, headers=None, cookies=None, files=None,
auth=None, timeout=None, allow_redirects=True, proxies=None,
hooks=None, stream=None, verify=None, cert=None, json=None):
"""Constructs a :class:`Request <Request>`, prepares it and sends it.
Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query
string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send
in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the
:class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the
:class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the
:class:`Request`.
:param files: (optional) Dictionary of ``'filename': file-like-objects``
for multipart encoding upload.
:param auth: (optional) Auth tuple or callable to enable
Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Set to True by default.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
:param stream: (optional) whether to immediately download the response
content. Defaults to ``False``.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param cert: (optional) if String, path to ssl client cert file (.pem).
If Tuple, ('cert', 'key') pair.
:rtype: requests.Response
"""
# Create the Request.
req = requests.Request(
method=method.upper(),
url=url,
headers=headers,
files=files,
data=data or {},
json=json,
params=params or {},
auth=auth,
cookies=cookies,
hooks=hooks,
)
logger.debug('start {} this url --> {} '.format(method, url))
prep = self.prepare_request(req) proxies = proxies or {} settings = self.merge_environment_settings(
prep.url, proxies, stream, verify, cert
) # Send the request.
send_kwargs = {
'timeout': timeout,
'allow_redirects': allow_redirects,
}
send_kwargs.update(settings)
resp = self.send(prep, **send_kwargs)
logger.debug('{} {} {} {} {} {}'.format(method, resp.url, resp.status_code, resp.elapsed.total_seconds(), resp.is_redirect, resp.text.__len__()))
return resp def custom_request(method, url, **kwargs):
with CustomSession() as session:
return session.request(method=method, url=url, **kwargs) def patch_request():
LogManager('custom_request').get_logger_and_add_handlers()
requests.api.request = custom_request if __name__ == '__main__':
patch_request()
resp = requests.get('http://www.sina.com.cn')
requests.get('https://www.baidu.com')

1、结果就是这样。这样所有地方的requests请求都会生效了。

正常情况下我有自己围绕Session类实例包装的SessionWrapper类,通常情况下我不会直接去使用requests的那些函数请求接口,但同事都是直接requests,然后每个地方打印print一下请求和返回,以便能看看到发了什么请求,那样有些重复。而且项目有几百个文件,突然蹦出来的print语句,根本不知道哪里print的。

使用这种猴子技术后,不用修改库源码,就能生效。

2、使用猴子技术要注意的是,patch的地方并不是随便替换就能生效的。

如果库里面的那个地方是from xx import yy

你直接yy.function = yourfunction

这是无效的,一定要找到正确的地方替换,要搞清除到底怎么才能生效,必须要熟悉python的模块导入机制。可以看我的上上篇的三个试验文件。

python 模块会导入几次?猴子补丁为什么可以实现?

使用monkey技术修改python requests模块的更多相关文章

  1. 使用python requests模块搭建http load压测环境

    网上开源的压力测试工具超级的多,但是总有一些功能不是很符合自己预期的,于是自己动手搭建了一个简单的http load的压测环境 1.首先从最简单的http环境着手,当你在浏览器上输入了http://w ...

  2. Python requests模块学习笔记

    目录 Requests模块说明 Requests模块安装 Requests模块简单入门 Requests示例 参考文档   1.Requests模块说明 Requests 是使用 Apache2 Li ...

  3. Python—requests模块详解

    1.模块说明 requests是使用Apache2 licensed 许可证的HTTP库. 用python编写. 比urllib2模块更简洁. Request支持HTTP连接保持和连接池,支持使用co ...

  4. Windows下安装Python requests模块

    在使用自己写的或者别人的python小工具时可能会出现类似ImportError: No module named Requests的问题: D:\tool\python\fuzz>Fuzz.p ...

  5. Python requests模块params、data、json的区别

    json和dict对比 json的key只能是字符串,python的dict可以是任何可hash对象(hashtable type): json的key可以是有序.重复的:dict的key不可以重复. ...

  6. python requests模块session的使用建议及整个会话中的所有cookie的方法

    话不多说,直接上代码 测试代码 服务端 下面是用flask做的一个服务端,用来设置cookie以及打印请求时的请求头 # -*- coding: utf-8 -*- from flask import ...

  7. Python requests模块

    import requests 下面就可以使用神奇的requests模块了! 1.向网页发送数据 >>> payload = {'key1': 'value1', 'key2': [ ...

  8. python requests模块的两个方法content和text

    requests模块下有两个获取内容的方法,很奇怪,都是获取请求后内容的方法,有什么区别呢?? 一.区别 content:返回bytes类型的数据也就是二进制数据 text:返回的就是纯文本(Unic ...

  9. Python Requests模块讲解4

    高级用法 会话对象 请求与响应对象 Prepared Requests SSL证书验证 响应体内容工作流 保持活动状态(持久连接) 流式上传 块编码请求 POST Multiple Multipart ...

随机推荐

  1. Linux(Centos7)yum安装最新redis

    正如我们所知的那样,Redis是一个开源的.基于BSD许可证的,基于内存的.键值存储NoSQL数据库.Redis经常被视为一个数据结构服务器,因为Redis支持字符串strings.哈希hashes. ...

  2. os.walk函数

    import os# g = os.walk("D:\aaa") for i in os.walk(R"D:\aaa"): print(i)#执行结果如下('D ...

  3. Java G1学习笔记

    引子 最近遇到很多朋友过来咨询G1调优的问题,我自己去年有专门学过一次G1,但是当时只是看了个皮毛,因此自己也有不少问题.总体来讲,对于G1我有几个疑惑,希望能够在这篇文章中得到解决. G1出现的初衷 ...

  4. Python 内置方法new

    class Dog(object): def __new__(self): print("i am new .") def __init__(self): print(" ...

  5. 关于Unity中旧版动画系统的使用

    Unity在5.X以后,有一个旧版的动画系统和新版的动画系统. 新版的动画系统是使用Unity动画编辑器来调的,调动画和控制动画 旧版的动画系统是用其他的第三方软件调好后导出到一个FBX文件里面,就是 ...

  6. android Toast大全(五种情形)建立属于你自己的Toast

    Toast用于向用户显示一些帮助/提示.下面我做了5中效果,来说明Toast的强大,定义一个属于你自己的Toast. 1.默认效果 代码 Toast.makeText(getApplicationCo ...

  7. 【转】【Python】python使用urlopen/urlretrieve下载文件时出现403 forbidden的解决方法

    第一:urlopen出现403 #!/usr/bin/env python # -*- coding: utf- -*- import urllib url = "http://www.go ...

  8. 【转载】Exchange 2010配置与安装实用手册

    Exchange 2010配置与安装实用手册 在Exchange 2010配置的时候主要分三大部分,这分别是网络配置.准备存储以及相关的安装策略和过程.同时还需要注意和其他的Windows软件相协调. ...

  9. 【转帖】Windows下PostgreSQL安装图解

    Windows下PostgreSQL安装图解     这篇文章主要为大家介绍了如果在Windows下安装PostgreSQL数据库的方法,需要的朋友可以参考下     现在谈起免费数据库,大多数人首先 ...

  10. iOS笔记UI--使用storyboard加入约束

    申明:此为本人学习笔记,若有纰漏错误之处的可留言共同探讨 可视化的搭建UI效率是很高的.所以官方苹果也是很推荐的.那么我们来学一学怎样利用系统自带的故事版(storyboard)来搭建UI.可视化搭建 ...