簡體   English   中英

我可以為所有 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)

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('/'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM