您可以只继承 request.Session 并重载其 __init__ 和 request 方法,如下所示:
# my_requests.py
import requests
class SessionWithUrlBase(requests.Session):
# In Python 3 you could place `url_base` after `*args`, but not in Python 2.
def __init__(self, url_base=None, *args, **kwargs):
super(SessionWithUrlBase, self).__init__(*args, **kwargs)
self.url_base = url_base
def request(self, method, url, **kwargs):
# Next line of code is here for example purposes only.
# You really shouldn't just use string concatenation here,
# take a look at urllib.parse.urljoin instead.
modified_url = self.url_base + url
return super(SessionWithUrlBase, self).request(method, modified_url, **kwargs)
然后你可以在你的代码中使用你的子类而不是requests.Session:
from my_requests import SessionWithUrlBase
session = SessionWithUrlBase(url_base='https://*.com/')
session.get('documentation') # https://*.com/documentation
您还可以对requests.Session 进行猴子补丁以避免修改现有代码库(此实现应 100% 兼容),但请务必在任何代码调用 requests.Session() 之前进行实际修补:
# monkey_patch.py
import requests
class SessionWithUrlBase(requests.Session):
...
requests.Session = SessionWithUrlBase
然后:
# main.py
import requests
import monkey_patch
session = requests.Session()
repr(session) # <monkey_patch.SessionWithUrlBase object at ...>