我试图从一个Django视图连接到Google Sheets的API。大部分的代码我都是从这个链接中获取的。https:/developers.google.comsheetsapiquickstartpython。
总之,以下是代码。
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')
]
视图.py
from django.http import HttpResponse
from django.shortcuts import render
from .sheets import test
# Views
def index(request):
test()
return HttpResponse('Hello world')
视图函数所做的只是调用 test()
的方法 单子.py 模块。无论如何,当我运行我的服务器和去的URL,另一个标签打开谷歌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来自。有谁能帮我解决这个问题?谁能给我解释一下为什么会出现这种情况?先谢谢你。
EDIT我试着去掉 port=0
的流转方法中,那么就会出现URL不匹配的情况,如评论中提到的 http://localhost:8080/
这又是一个很奇怪的问题,因为我的Django应用是运行在 8000
端口。
你不应该使用 Flow.run_local_server() 除非你不打算部署代码。这是因为 run_local_server
在服务器上启动一个浏览器来完成流程。
如果你是在本地为自己开发项目,这样做就很好。
如果你打算使用本地服务器来协商OAuth流程。你的秘密中配置的重定向URI必须与之匹配,本地服务器默认的主机是 localhost
和端口是 8080
.
如果你想部署代码,你必须通过用户的浏览器,你的服务器和Google之间的交换来执行流程。
由于你已经有一个Django服务器在运行,你可以用它来协商流程。
比如说
说在Django项目中,有一个推文应用,其内容为 urls.py
模块如下。
from django.urls import path, include
from . import views
urlpatterns = [
path('google_oauth', views.google_oath, name='google_oauth'),
path('hello', views.say_hello, name='hello'),
]
urls = include(urlpatterns)
您可以为需要凭证的视图实现如下守护。
import functools
import json
import urllib
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from django.shortcuts import redirect
from django.http import HttpResponse
SCOPES = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'openid']
def provides_credentials(func):
@functools.wraps(func)
def wraps(request):
# If OAuth redirect response, get credentials
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES,
redirect_uri="http://localhost:8000/tweet/hello")
existing_state = request.GET.get('state', None)
current_path = request.path
if existing_state:
secure_uri = request.build_absolute_uri(
).replace('http', 'https')
location_path = urllib.parse.urlparse(existing_state).path
flow.fetch_token(
authorization_response=secure_uri,
state=existing_state
)
request.session['credentials'] = flow.credentials.to_json()
if location_path == current_path:
return func(request, flow.credentials)
# Head back to location stored in state when
# it is different from the configured redirect uri
return redirect(existing_state)
# Otherwise, retrieve credential from request session.
stored_credentials = request.session.get('credentials', None)
if not stored_credentials:
# It's strongly recommended to encrypt state.
# location is needed in state to remember it.
location = request.build_absolute_uri()
# Commence OAuth dance.
auth_url, _ = flow.authorization_url(state=location)
return redirect(auth_url)
# Hydrate stored credentials.
credentials = Credentials(**json.loads(stored_credentials))
# If credential is expired, refresh it.
if credentials.expired and creds.refresh_token:
creds.refresh(Request())
# Store JSON representation of credentials in session.
request.session['credentials'] = credentials.to_json()
return func(request, credentials=credentials)
return wraps
@provides_credentials
def google_oauth(request, credentials):
return HttpResponse('Google OAUTH <a href="/tweet/hello">Say Hello</a>')
@provides_credentials
def say_hello(request, credentials):
# Use credentials for whatever
return HttpResponse('Hello')
请注意,这只是一个例子,如果你决定走这条路,我建议你将OAuth流提取到自己的Django App中。如果你决定走这条路,我建议你考虑将OAuth流提取到自己的Django App中。
重定向URI告诉谷歌你希望授权被返回的位置。 这必须在google开发者控制台中正确设置,以避免任何人劫持你的客户端。 它必须完全匹配。
到 谷歌开发者控制台. 编辑您当前使用的客户端,并添加以下内容作为重定向URLi。
http://localhost:65262/
小贴士 点击小铅笔图标来编辑客户端 :)
TBH,而在开发中,它更容易只是添加端口,谷歌说,你从调用,然后摆弄你的应用程序中的设置。