तुम बस 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
मौजूदा codebase को संशोधित करने से बचने के लिए (इस कार्यान्वयन होना चाहिए सकता है 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 ...>
मैं इस सवाल का जवाब चाहते हैं, लेकिन यह काम करता है केवल जब आधार यूआरएल की तरह है क्योंकि 'urljoin' उन्हें क्या और यूआरएल पाने के लिए पोस्ट तरीकों के रूप में प्रदान की जाती है के साथ अधिलेखित कर देता है कोई sublevels है। मुझे अपने मामले में इसकी आवश्यकता थी, इसलिए मैंने सरल स्ट्रिंग कॉन्सटेनेशन के साथ 'urljoin' कॉल को बदल दिया –