如何在实时网站上的 Django 中向 Google 授权应用程序

Joh*_*rry 3 python django authorization google-api heroku

我正在使用 Google Calendar API,但这适用于他们的任何 API。

我按照他们提供的快速入门示例进行操作,在本地环境中,这效果很好。我面临的主要问题是,在本地环境中,他们提供的代码设置为在需要授权时自动打开 URL 来授权应用程序。在实际环境中情况并非如此,它与这部分代码有关:

flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
Run Code Online (Sandbox Code Playgroud)

但是,我不太明白我应该调用什么。


这是他们提供的完整代码:

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()
Run Code Online (Sandbox Code Playgroud)

Joh*_*rry 5

解释:

Google 在该页面上提供的示例实际上应该在实际环境中运行。我相信您遇到困难的地方是 Google 告诉您在启用 API 后下载的凭证文件。

假设您使用的是启用 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"]
  }
}
Run Code Online (Sandbox Code Playgroud)

installed属性告诉您的程序这是本地环境中安装的应用程序,这不是您想要的


解决方案:

  1. 进入您的项目的凭据
  2. 单击“创建凭据”,然后单击“ OAuth 客户端 ID
  3. 在下一页上,选择“ Web 应用程序”并添加您的重定向 URI(即您希望 Google 在用户经过身份验证后获取的 url)
  4. 点击“创建”
  5. 您将返回到主凭据页面,并且您将在“ OAuth 2.0 客户端 ID ”下看到您的新凭据。单击新创建的凭据的链接。
  6. 现在您已进入凭据页面的设置,现在可以单击“下载 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>"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)