python - Google Calendar API 授权在本地主机上工作,但在 Heroku 上不工作
问题描述
我想为我的 Django 应用程序使用 Google Calendar API。我已按照此处的说明进行操作:https ://karenapp.io/articles/how-to-automate-google-calendar-with-python-using-the-calendar-api/
我还在 Google API 中添加了重定向 uri - 似乎浏览器试图在服务器端打开(就像在本地一样,但我无法操作它,因为服务器端的浏览器没有出现)。在终端中,我确实看到“请访问此 URL 以授权此应用程序:https://accounts.google.com/...”
关于我能做什么的任何想法?
view.py 中的代码:
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
SCOPES = ['https://www.googleapis.com/auth/calendar']
CREDENTIALS_FILE = 'path_to_file/credentials.json'
def get_calendar_service():
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
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_FILE, SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('calendar', 'v3', credentials=creds)
return service
解决方案
您遇到的问题是您正在使用已安装的应用程序流。
flow = InstalledAppFlow.from_client_secrets_file(
CREDENTIALS_FILE, SCOPES)
creds = flow.run_local_server(port=0)
此代码设计用于已安装的应用程序,将在当前运行的机器上打开 Web 浏览器窗口。
import google.oauth2.credentials
import google_auth_oauthlib.flow
# Use the client_secret.json file to identify the application requesting
# authorization. The client ID (from that file) and access scopes are required.
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json',
scopes=['https://www.googleapis.com/auth/drive.metadata.readonly'])
# Indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required. The value must exactly
# match one of the authorized redirect URIs for the OAuth 2.0 client, which you
# configured in the API Console. If this value doesn't match an authorized URI,
# you will get a 'redirect_uri_mismatch' error.
flow.redirect_uri = 'https://www.example.com/oauth2callback'
# Generate URL for request to Google's OAuth 2.0 server.
# Use kwargs to set optional request parameters.
authorization_url, state = flow.authorization_url(
# Enable offline access so that you can refresh an access token without
# re-prompting the user for permission. Recommended for web server apps.
access_type='offline',
# Enable incremental authorization. Recommended as a best practice.
include_granted_scopes='true')
推荐阅读
- tomcat - 为什么当我尝试运行我的网页时 Tomcat 返回 HTTP 404?
- sql - Toad:查询几乎一样,一个完成得很快,另一个根本没有完成
- mysql - Mysql交叉矩阵
- sql - 如何提取部分列名并将值传递给 SSIS 中的变量
- azure - 无法添加带有实体标签的话语
- c - 将 char 数组传递给函数并将内容复制到另一个 char 数组
- php - 未定义的类常量“CONDITION_OPTIONS”
- windows - 启动时无法通过 PS 重新启动后登录到网络共享
- sqlite - 使用 sqlite、flutter app 导入数据库
- macros - Confluence UI-Expand 宏的全部展开