如何通过Django在实时站点上向Google授权应用程序

问题描述 投票:1回答:1

我正在使用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()
python django heroku google-api authorization
1个回答
1
投票

说明:

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属性告诉您的程序,这是在本地环境上安装的应用程序。


解决方案:

  1. 进入您的project's credentials
  2. 单击,“ 创建凭据”,然后单击“ OAuth客户端ID”]
  3. 在下一页上,选择“ Web应用程序”并添加您的重定向URI(即,您希望Google在验证用户身份后使用该URL)]
  4. 单击“创建”
  5. 您将回到主凭据页面,您将在“ OAuth 2.0客户端ID”下看到新的凭据。单击新创建的凭据的链接。
  6. 现在您处于凭据页面的设置中,现在可以单击“ DOWNLOAD JSON

假设一切正常,您现在应该拥有一个包含以下内容的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>"
    ]
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.