0

我的问题专门针对 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)
4

1 回答 1

1

查看来自Microsoft Graph示例的 Python 控制台应用程序中的此代码。

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('/'))
于 2020-02-26T21:12:45.140 回答