gpt4 book ai didi

python - 如何在不提示授权我的脚本的情况下设置对 Google 表格的身份验证?

转载 作者:行者123 更新时间:2023-12-05 07:24:30 25 4
gpt4 key购买 nike

我正在尝试使用 Python 通过他们的 API 查询 Google 表格,但对设置有点困惑。使用他们的 documentation guide ,我对自己进行了身份验证,并下载了一个 OAuth 2.0 客户端 ID JSON 文件,并批准了对我的应用程序的访问,这是我的脚本吗?

但是,每次我运行脚本时,系统都会提示我授权我的应用程序。我执行该脚本,它会在我的浏览器中自动打开一个类似于 Google 登录的页面,询问我是否希望 Quickstart 访问您的 Google 帐户

我直接从该页面复制了认证部分,但对于在他们的 API 和服务页面中更改或执行哪些操作以使其无缝运行感到困惑

SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

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("googlesheetscreds.json",
SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)

我需要更改范围吗?

最佳答案

看起来你想使用服务帐户,你应该回到你的谷歌云控制台,设置它并下载新的 JSON 文件。

有关凭据类型及其设置方式的 Google 文档 here

然后您必须更改您的代码以使用服务帐户而不是常规的 oauth 加载和运行,问题是“InstalledAppFlow”,这是完整的代码:

import os.path
import pickle

from google.auth.transport.requests import Request
from google.oauth2 import service_account
from googleapiclient.discovery import build


def create_credential():
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("googlesheetscreds.json", SCOPES)
# creds = flow.run_local_server()
creds = service_account.Credentials.from_service_account_file('googlesheetscreds.json')
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)

# Tip: return the spreadsheet already created and re-use it along with your code,
# if you create a new one in every request it will leak around 30MB each time
return service.spreadsheets()

关于python - 如何在不提示授权我的脚本的情况下设置对 Google 表格的身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55403321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com