我正在使用Google Calendar API,但这将适用于它们的任何API。
我遵循了quickstart example that they provide,在本地环境中,效果很好。我面临的主要问题是,在本地环境中,他们提供的代码设置为一旦需要授权就自动打开URL来授权应用程序。在实时环境中并非如此,这与代码的这一部分有关:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
但是,我不太了解应该在哪里打电话。
这里是他们提供的完整代码:
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()
Google在该页面上提供的示例应在实际环境中实际运行。我相信您会卡住的区域是启用API后Google告诉您下载的凭据文件。
假设您使用的是在启用API后可以下载的凭证文件,则凭证文件将如下所示:
{
"installed": {
"client_id": "<CLIENT_ID>",
"project_id": "<PROJECT_ID>",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "<CLIENT_SECRET>",
"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"]
}
}
installed
属性告诉您的程序,这是在本地环境上安装的应用程序。
假设一切正常,您现在应该拥有一个包含以下内容的json文件:
{
"web": {
"client_id": "<CLIENT_ID>",
"project_id": "<PROJECT_ID>",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "<CLIENT_SECRET>",
"redirect_uris": [
"<YOUR_REDIRECT_URIS>"
]
}
}