你可以只繼承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'調用 –