你可以只继承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://stackoverflow.com/')
session.get('documentation') # https://stackoverflow.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 ...>
我喜欢这个答案,但它只适用于基础url没有sublevels之类的情况,因为'urljoin'用覆盖它们的URL作为获取和发布方法的URL。我需要它在我的情况下,所以我用简单的字符串连接替换了'urljoin'调用 –