- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试从 Django View 连接到 Google Sheets 的 API。我从这个链接中获取的大部分代码:
https://developers.google.com/sheets/api/quickstart/python
无论如何,这里是代码:
sheet.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]))
urlpatterns = [
path('', views.index, name='index')
]
from django.http import HttpResponse
from django.shortcuts import render
from .sheets import test
# Views
def index(request):
test()
return HttpResponse('Hello world')
test()
来自
的方法sheet.py 模块。无论如何,当我运行我的服务器并访问 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.
127.0.0.1:8000
匹配我的 Django 的查看 URL。我什至不知道
http://localhost:65262/
在哪里网址来自。解决这个问题有什么帮助吗?有人可以向我解释为什么会这样吗?提前致谢。
port=0
在注释中提到的 flow 方法中,URL 不匹配会出现
http://localhost:8080/
,这又很奇怪,因为我的 Django 应用程序在
8000
中运行港口。
最佳答案
你不应该使用 Flow.run_local_server()除非您不打算部署代码。这是因为 run_local_server
在服务器上启动浏览器以完成流程。
如果您在本地为自己开发项目,这很好用。
如果您打算使用本地服务器来协商 OAuth 流程。您的 secret 中配置的重定向 URI 必须匹配,主机的本地服务器默认值为 localhost
and port is 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')
关于python - 收到错误 400 : redirect_uri_mismatch when trying to use OAuth2 with Google Sheets from a Django view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62097219/
我在 Android 中使用 Google Sheets API v4。 https://developers.google.com/sheets/api/quickstart/android 我需要
我想使用 googlesheetv4 api 在 googlesheet 中使用 rowno 删除一行。有人可以给我提供一个示例代码吗?我创建了一个删除行的方法公共(public)无效deleteRo
我想使用 googlesheetv4 api 在 googlesheet 中使用 rowno 删除一行。有人可以给我提供一个示例代码吗?我创建了一个删除行的方法公共(public)无效deleteRo
如何在 Google 表格中获取数据透视表,其中一列显示值在列中出现的次数? 我知道可以使用 countif 来完成。功能,但我想使用数据透视表来完成。 最佳答案 转到顶部菜单 Data--> Piv
在 Google 表格中,我尝试使用作用于其他两个单元格的条件格式公式将文本添加到不同的单元格。 例如,我有几列......“C”和“E”。我正在比较 C25 和 E25 中的值,如下所示:=E25<
假设我有一个带有随机工作表名称的工作簿,“Bob”、“Sally”、“Billy”、“John”或类似的非连续名称。我还有另一张名为“总计”的表格。我怎样才能对特定单元格的值求和,比如所有单元格的“H
我已经能够使用 Google Sheet 的 SEQUENCE为我提供 Partner 1 的顺序日期的公式但随后公式停止并且不会继续到 Partner 2 . 我曾尝试在 Google 的 Arra
我需要对字符串中的所有数字求和,在字符串中不会有任何字母只有数字。单元格包含 112121 . 我尝试使用 SUM和 CASE与 QUERY函数,但是 CASE不支持。 示例:1121 = 5。 最佳
在 Google Sheets 上,我试图在一个单元格中使用文本(比如 B4 包含:“Janet”)并在另一个单元格中的句子中引用它(比如 G4 是:“嗨{在此处输入 B4},我正在到达今天给你……”
我正在创建一个锻炼电子表格来跟踪我每周的表现,每张表格都涵盖了一周的锻炼。每张纸(除了第一张)都是前一张纸的副本,我想从上一张纸中继承一些值;例如,前一周的练习次数。 我已经阅读了一些 API,但似乎
我尝试使用示例“读取多个范围”: https://sheets.googleapis.com/v4/spreadsheets/{SpreadsheetID}/values:batchGet?range
我有一个从 Google 电子表格中获取数据的网站。我希望我的用户在不登录的情况下查看获取的数据。这可能吗?怎么做? 为了获取和更新工作表数据,我只需要一个帐户,最好在服务器端登录。但是,我没有看到任
我正在 Google Sheets 中使用 COUNTIF 公式进行一些动态蒙特卡罗模拟。有些事情不像我想象的那样工作,但我无法解决。我有两列要比较,我需要计算一列中的值大于另一列中的值的实例。如果我
我正在使用 Google Sheets 中的一个大(但简单)的公式,该公式重复使用相同的公式块。要从一堆不同的选项卡中获取一堆数据,我必须在该公式块中使用 708 个字符。但是随后我需要在 1 个单元
我在我的工作表中使用以下查询为艺术家导入总 Spotify 流。例子:=IMPORTXML("https://chartmasters.org/spotify-streaming-numbers-to
我正在尝试做一个非常简单的 lookup在数据验证字段上: 我有 4 个简单的值: 无风险 低 中级 高 除此之外,我还有以下值(value)观: 0 0.1 0.2 0.5 我使用 lookup公式
我有一个专栏 COLUMN H | Column R trading type | Closed P&L Lotto | 100% Lotto | 200% | 100% Day |
我正在寻找一种通过Google Sheets API创建一组行的方法-有没有办法做到这一点?我看不到找到可以做到这一点的API,但似乎应该是相当普遍的格式设置需求。 通过选择一组行,右键单击,该选项在
我有一个表,基本上显示了另一个表的数据。问题是:我在原始表中有一些脚本程序,这些程序涉及删除行,当它发生时,我丢失了对行所在位置的引用。 我怎样才能解决这个问题? 已经试过了:='INVENTORY'
我想通过 API v4 隐藏谷歌电子表格中的给定列,但我很难这样做。 有谁知道这是否可能并设法做到了? 我们在 Apps 脚本中有一个 dedicated method这样做,如果 REST API
我是一名优秀的程序员,十分优秀!