【发布时间】:2022-06-10 19:04:32
【问题描述】:
我有一个小的 python 脚本,它收集一些数据并使用 gmail api 在电子邮件中发送。我的目标是把这个脚本放在我的树莓上,创建一个每天调用它的 cronjob,然后忘记它。但是,我完成 google 身份验证的方式使我无法将其自动化。目前我必须使用我的浏览器进行身份验证(用户需要按下允许按钮),然后我可以使用凭据几天,然后它们过期并且再次需要用户输入。我怎样才能让它验证一次,然后开始自动刷新它的凭据?
当前代码:
def get_creds():
creds = None
if os.path.exists(os.path.join(dir,'token.json')):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
print("refreshing")
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
os.path.join(dir,'credentials.json'), SCOPES)
creds = flow.run_local_server(port=0)
with open(os.path.join(dir,'token.json'), 'w') as token:
token.write(creds.to_json())
return creds
【问题讨论】:
-
我最近回答了这样的问题。解决方案是使用您的代码示例已经拥有的刷新令牌,但为了防止令牌过期,您需要发布项目或将其设置为内部。见avoid auth token to expire
标签: python authentication google-api gmail-api credentials