如何保存令牌以便在O365 python库中重用?

2024-06-16 09:31:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pythono365库阅读和发送我的office365帐户的邮件,以自动执行一些常规任务。每次我想使用这个API,我都要进行验证并获得一个新的令牌,这个令牌每60分钟过期一次。所以经过一番彻底的研究,我发现了一个名为FileSystemTokenBackend的方法,但是我仍然无法保存令牌。这就是我要拯救的方式

token_backend = O365.FileSystemTokenBackend(token_path='G:/Newfolder', token_filename='my_token.txt')

即使在执行此命令之后,也不会保存任何令牌。在


Tags: path方法tokenapibackend方式邮件帐户
2条回答

根据docs,当您验证时,您的令牌将存储在指定的路径。在

第一次验证后,令牌将在指定的路径上读取。当您使用指向此路径的令牌后端创建和帐户时,此帐户将自动登录。在

token_backend = FileSystemTokenBackend(token_path='token_dir', token_filename='o365_token.txt')
account = Account(CREDENTIALS, token_backend=token_backend)
# If it's your first login, you will have to visit a website to authenticate and paste the redirected URL in the console. Then your token will be stored.
# If you already have a valid token stored, then account.is_authenticated is True.
if not account.is_authenticated:
    account.authenticate(scopes=['basic', 'message_all'])

这取决于你的需要。您可以选择将其存储在文件或内存中。在

要存储在文件中:

import uuid


def write_token(token: str):
    with open('.secret_token', 'w') as file:
        file.write(token)


def get_token():
    with open('.secret_token', 'r') as file:
        return file.read()


if __name__ == '__main__':
    my_token = str(uuid.uuid4())
    print("Using token: {}".format(my_token))

    # store it
    write_token(my_token)

    # prove we stored the value
    print("Stored token: {}".format(get_token()))

要在内存中存储,只需将文件替换为dict

^{pr2}$

不管是哪种方式,您都应该得到与此类似的输出

$ python3 test.py
Using token: 79e9bb1b-0159-4065-9bee-d9fee383ae09
Stored token: 79e9bb1b-0159-4065-9bee-d9fee383ae09

相关问题 更多 >