Python 谷歌日历API入门
我正在努力熟悉谷歌日历api。在入门指南中,他们有以下代码示例:Python 谷歌日历API入门,python,oauth-2.0,google-calendar-api,google-oauth,Python,Oauth 2.0,Google Calendar Api,Google Oauth,我正在努力熟悉谷歌日历api。在入门指南中,他们有以下代码示例: from __future__ import print_function import datetime import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests
from __future__ import print_function
import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
def main():
"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
# Call the Calendar API
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Getting the upcoming 10 events')
events_result = service.events().list(calendarId='primary', timeMin=now,
maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = events_result.get('items', [])
if not events:
print('No upcoming events found.')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'])
if __name__ == '__main__':
main()
在本例中,如果我们还没有通过pickle文件进行访问,我们会自动打开一个窗口,要求用户访问他们的日历。问题是,我不希望此窗口自动打开,我希望打印一个链接,用户可以单击以进行身份验证。我查阅了文档,但似乎找不到任何有用的东西。如果能得到任何帮助,我将不胜感激,谢谢
对于授权过程,您希望只显示URL。您不想自动打开浏览器。
您希望通过使用googleapis和python来实现这一点。
如果我的理解是正确的,那么这个答案呢?请把这看作是几个可能的答案之一
在这种情况下,请使用Flow.from_client_secrets_文件,而不是InstalledAppFlow.from_client_secrets_文件
修改脚本:
修改脚本时,请按以下方式修改
发件人:
致:
及
发件人:
致:
在这种情况下,当您在token.pickle不存在的情况下运行脚本时,将向控制台显示授权的URL。浏览器未打开。因此,请打开浏览器访问URL并授权作用域。然后,请将复制的授权码输入控制台并输入enter键。这样,将检索访问令牌并创建token.pickle文件。
注:
如果发生与重定向uri相关的错误,请将其修改为http://localhost 然后再测试一次。
参考:
如果我误解了你的问题,而这不是你想要的方向,我道歉
补充:
从我想打印一个链接,而不是用户可以单击以在您的问题中进行身份验证开始,我提出了上面的示例脚本。
从某种程度上说,在您的回复中不需要手动确认授权代码,我认为上面的示例脚本不适合。
在这种情况下,如何使用服务帐户?使用服务帐户时,不需要授权代码。使用服务帐户的脚本如下所示
示例脚本:
注:
为了使用服务帐户访问谷歌日历,首先,请将谷歌日历与服务帐户的电子邮件共享。请小心这个。
参考:
是的,你正确地理解了我的问题,这正是我想要的方向。然而,我觉得他们可能不会以某种方式手动确认授权代码。你知道有什么办法吗?需要什么?也许该如何“监听”使用我的客户机密的身份验证?再次感谢你@谢谢你的回复。给您带来不便,我深表歉意。根据您的问题,我提出了上述示例脚本。但是,从你的回答中,我可以知道我的理解是不正确的。这是因为我的英语水平差。对此我深表歉意。为了您的回复,我又添加了一个方法和示例脚本。你能确认一下吗?如果这不是你想要的方向,我道歉。我也在考虑服务帐户。因为它们可以用来访问别人的日历,对吗?@WilliamG谢谢你的回复。我认为当Google日历与包含服务帐户的脚本一起使用时,可以让多个用户使用它。
from google_auth_oauthlib.flow import InstalledAppFlow
from google_auth_oauthlib.flow import Flow
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
# Create the flow using the client secrets file from the Google API
# Console.
flow = Flow.from_client_secrets_file('client_secret.json', SCOPES, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
# Tell the user to go to the authorization URL.
auth_url, _ = flow.authorization_url(prompt='consent')
print('Please go to this URL: {}'.format(auth_url))
# The user will get an authorization code. This code is used to get the
# access token.
code = input('Enter the authorization code: ')
flow.fetch_token(code=code)
creds = flow.credentials
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
from google.oauth2 import service_account
from googleapiclient.discovery import build
SERVICE_ACCOUNT_FILE = 'service-account-credentials.json' # Here, please set the creadential file of the service account.
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('calendar', 'v3', credentials=creds)