【发布时间】:2020-05-30 02:50:05
【问题描述】:
我正在尝试从 Django 视图连接到 Google Sheets 的 API。我从这个链接中获取的大部分代码: https://developers.google.com/sheets/api/quickstart/python
不管怎样,代码如下:
sheets.py(从上面的链接复制粘贴,函数重命名)
from __future__ import print_function
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/spreadsheets.readonly']
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Class Data!A2:E'
def test():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
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('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[4]))
urls.py
urlpatterns = [
path('', views.index, name='index')
]
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .sheets import test
# Views
def index(request):
test()
return HttpResponse('Hello world')
视图函数所做的只是调用 sheets.py 模块中的test() 方法。无论如何,当我运行我的服务器并访问 URL 时,会为 Google oAuth2 打开另一个选项卡,这意味着检测到凭据文件和所有内容。但是,在此选项卡中,Google 会显示以下错误消息:
Error 400: redirect_uri_mismatch The redirect URI in the request, http://localhost:65262/, does not match the ones authorized for the OAuth client.
在我的 API 控制台中,我将回调 URL 完全设置为 127.0.0.1:8000 以匹配我的 Django 的视图 URL。我什至不知道http://localhost:65262/ URL 来自哪里。解决这个问题有什么帮助吗?有人可以向我解释为什么会这样吗?提前致谢。
编辑
我尝试删除注释中提到的流方法中的port=0,然后与http://localhost:8080/ 发生URL 不匹配,这再次很奇怪,因为我的Django 应用程序在8000 端口中运行。
【问题讨论】:
-
虽然我不确定这是否是直接的解决方案,但当
creds = flow.run_local_server(port=0)的port=0像creds = flow.run_local_server()一样被删除时,你会得到什么结果? -
@Tanaike 您使用的
flow方法是什么? -
感谢您的回复。对于不完整的评论,我深表歉意。而且,我不得不道歉,我的评论没有解决你的问题。关于google_auth_oauthlib.flow模块,文档见here。
-
您可以在
credentials.json文件中看到哪些重定向 URI? -
@RafaGuillermo 我有这个:
http://127.0.0.1:8000/
标签: python django google-api google-oauth google-sheets-api