我正在使用python O365库阅读和发送Office 365帐户的邮件,以自动执行一些常规任务。每次我想使用此API时,都必须进行验证并获取新令牌,并且该令牌每60分钟失效一次。因此,经过一番深入的研究,我发现了一种名为FileSystemTokenBackend
的方法,但是我仍然无法保存令牌。这就是我要保存的方式
token_backend = O365.FileSystemTokenBackend(token_path='G:/Newfolder', token_filename='my_token.txt')
即使执行此命令,也不会保存令牌。
答案 0 :(得分:0)
这取决于您的需求。您可以选择将其存储在文件或内存中。
要存储在文件中:
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
import uuid
_token_store = {}
_token_store_key = ":token:"
def write_token(token: str):
_token_store[_token_store_key] = token
def get_token():
return _token_store[_token_store_key]
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()))
无论哪种方式,您都应该获得与此类似的输出
$ python3 test.py
Using token: 79e9bb1b-0159-4065-9bee-d9fee383ae09
Stored token: 79e9bb1b-0159-4065-9bee-d9fee383ae09
答案 1 :(得分:0)
根据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'])