我可以为所有 OAuth2Session 请求设置一个基础 URL 吗?
Can I set a base URL for all OAuth2Session requests?
我的问题专门针对 Microsoft Graph API,但欢迎提供更广泛适用的解决方案。
我有一个会话实例化如下:
# Token acquisition code left out
session = OAuth2Session(token=token)
此会话的 HTTP 请求如下所示:
# List files in OneDrive
response = session.get("https://graph.microsoft.com/v1.0/me/drive/root/children")
是否可以设置基数 URL 以便我每次都可以省略 base_url
?我希望能够像这样拨打电话:
# List files in OneDrive
response = session.get("me/drive/root/children")
我可以通过子类化 OAuth2Session
和重载 Session.request()
方法来做到这一点,但我认为这是错误的方法。
# Bad hack
class GraphSession (OAuth2Session):
def request(self, *args, **kwargs):
if len(args) > 1: # url as non-kw arg
args = list(args) # can't assign to a tuple
args[1] = 'https://graph.microsoft.com/v1.0/' + args[1]
else: # url must be a kw arg
kwargs['url'] = 'https://graph.microsoft.com/v1.0/' + kwargs['url']
return super(GraphSession, self).request(*args, **kwargs)
看看 this code from Python console application for Microsoft Graph 示例。
def api_endpoint(url):
"""Convert a relative path such as /me/photo/$value to a full URI based
on the current RESOURCE and API_VERSION settings in config.py.
"""
if urllib.parse.urlparse(url).scheme in ['http', 'https']:
return url # url is already complete
return urllib.parse.urljoin(f'{config.RESOURCE}/{config.API_VERSION}/',
url.lstrip('/'))
我的问题专门针对 Microsoft Graph API,但欢迎提供更广泛适用的解决方案。
我有一个会话实例化如下:
# Token acquisition code left out
session = OAuth2Session(token=token)
此会话的 HTTP 请求如下所示:
# List files in OneDrive
response = session.get("https://graph.microsoft.com/v1.0/me/drive/root/children")
是否可以设置基数 URL 以便我每次都可以省略 base_url
?我希望能够像这样拨打电话:
# List files in OneDrive
response = session.get("me/drive/root/children")
我可以通过子类化 OAuth2Session
和重载 Session.request()
方法来做到这一点,但我认为这是错误的方法。
# Bad hack
class GraphSession (OAuth2Session):
def request(self, *args, **kwargs):
if len(args) > 1: # url as non-kw arg
args = list(args) # can't assign to a tuple
args[1] = 'https://graph.microsoft.com/v1.0/' + args[1]
else: # url must be a kw arg
kwargs['url'] = 'https://graph.microsoft.com/v1.0/' + kwargs['url']
return super(GraphSession, self).request(*args, **kwargs)
看看 this code from Python console application for Microsoft Graph 示例。
def api_endpoint(url):
"""Convert a relative path such as /me/photo/$value to a full URI based
on the current RESOURCE and API_VERSION settings in config.py.
"""
if urllib.parse.urlparse(url).scheme in ['http', 'https']:
return url # url is already complete
return urllib.parse.urljoin(f'{config.RESOURCE}/{config.API_VERSION}/',
url.lstrip('/'))