猴子修补urllib3之后奇怪的模块加载器行为

时间:2019-01-12 17:29:33

标签: python boto3 monkeypatching

我尝试使用urllib3猴子补丁boto3来跟踪jager请求。代码的简化版本:

from urllib3.connection import HTTPConnection
import os
import sys
import boto3

class TracingHTTPConnection(HTTPConnection):
    def send(self, data):
        print(data)
        HTTPConnection.send(self, data)

sys.modules['urllib3.connection'].HTTPConnection = TracingHTTPConnection

from boto3.session import Session

ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY_ID')
SECRET_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')

session = Session(aws_access_key_id=ACCESS_KEY,
                  aws_secret_access_key=SECRET_KEY)

s3 = session.resource('s3')
your_bucket = s3.Bucket('colleagial-manager')

print(len([file for file in your_bucket.objects.all()]))

但是由于某些原因,此代码不起作用(第8行上没有打印请求)。但是以下代码确实有效:

from urllib3.connection import HTTPConnection
import os
import sys
import boto3

_send = HTTPConnection.send
def send(self, data):
    print(data)
    _send(self, data)

HTTPConnection.send = send

from boto3.session import Session

ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY_ID')
SECRET_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')

session = Session(aws_access_key_id=ACCESS_KEY,
                  aws_secret_access_key=SECRET_KEY)

s3 = session.resource('s3')
your_bucket = s3.Bucket('colleagial-manager')

print(len([file for file in your_bucket.objects.all()]))

我找不到原因。有人可以帮我理解吗?

系统信息:

OS: Windows 10 x64
Python 3.7.2
boto3 1.9.20
botocore 1.12.20
urllib3==1.23

0 个答案:

没有答案