0

我尝试在 python 中编写程序以将约会添加到Microsoft To Do 我正在使用带有以下代码的 Microsoft Graph API:

import requests
import msal
import atexit
import os.path

TENANT_ID = 'X
CLIENT_ID = 'Y'


AUTHORITY = 'https://login.microsoftonline.com/' + TENANT_ID
ENDPOINT = 'https://graph.microsoft.com/v1.0'

SCOPES = [
    'Files.ReadWrite.All',
    'Sites.ReadWrite.All',
    'User.Read',
    'User.ReadBasic.All',
    'Tasks.ReadWrite'
]


cache = msal.SerializableTokenCache()

if os.path.exists('token_cache.bin'):
    cache.deserialize(open('token_cache.bin', 'r').read())

atexit.register(lambda: open('token_cache.bin', 'w').write(cache.serialize()) if cache.has_state_changed else None)

app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY, token_cache=cache)

accounts = app.get_accounts()
result = None
if len(accounts) > 0:
    result = app.acquire_token_silent(SCOPES, account=accounts[0])

if result is None:
    flow = app.initiate_device_flow(scopes=SCOPES)
    if 'user_code' not in flow:
        raise Exception('Failed to create device flow')

    print(flow['message'])

    result = app.acquire_token_by_device_flow(flow)
   
if 'access_token' in result:
    print(result['access_token'])
    result = requests.get(f'https://graph.microsoft.com/v1.0/me/todo/lists', headers={'Authorization': 'Bearer ' + result['access_token']})
    print(result.json())

else:
    raise Exception('no access token in result')


这是我得到的错误:

{'error': {'code': 'UnknownError', 'message': 'The service is unavailable.', 'innerError': {'date': '2022-01-25T18:52:03', 'request-id': 'X', 'client-request-id': 'X'}}}

我试图用谷歌搜索该错误,但没有找到任何适合我的解决方案。

4

2 回答 2

1

只是出于好奇,我想知道您是否输入了您的 TENANT_Id 和 CLIENT_ID 来代替“X”和“Y”。如果是,但仍然无法正常工作。

您能否尝试在Graph explorer和 postman上运行 URL - https://graph.microsoft.com/v1.0/me/todo/lists 。如果您仍然面临这个问题,请告诉我们。

于 2022-02-07T10:16:38.427 回答
1

您能否检查一下您的令牌到期时间(exp),它可能已过期。去jwt.ms查看token详细信息,找到附图看看哪里可以找到token时间。 检查exp时间

如果令牌过期,请文档获取新令牌。

于 2022-02-09T07:31:28.020 回答