我希望在云函数中使用Google Sheets API,该函数将从我的帐户的默认服务帐户运行,我使用Python。然而,我只在本地验证过Sheets库,使用了以下代码:
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
def gen_creds(path_to_secret: str, rw_vs_ro: str):
"""
Generate the needed credentials to work with the Sheets v4 API based on your secret
json credentials file.
:param path_to_secret: The file path to your credentials json file
:param rw_vs_ro: A string, 'r_o' or 'r_w', representing whether creds should be readonly or readwrite
:return: The built service variable
"""
if rw_vs_ro == 'r_o':
scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly']
creds_nm = 'readonly_token.json'
else:
scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds_nm = 'readwrite_token.json'
creds = None
# The file token.json 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(creds_nm):
creds = Credentials.from_authorized_user_file(creds_nm, scopes)
# 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(
path_to_secret, scopes)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open(creds_nm, 'w') as token:
token.write(creds.to_json())
return build('sheets', 'v4', credentials=creds)
我不完全确定如何将其转化为云功能能够理解的东西,因为云功能不会像我一样运行,并且缺乏我在本地可以访问的操作系统路径。如果你能深入了解这里的翻译过程,我将不胜感激——我只能在JS中找到例子,这对我想要的并不完美。然后,我很想了解如何在GCP中的云函数中实际实现这些代码。谢谢
部署云函数时,主代码将可以访问该函数中部署的所有文件。这意味着您只需要在部署包时包含readwrite_token.json/readonly_token.jsp文件。完成后,由于函数的目录可能与当前工作目录不同,因此不需要简单地将令牌文件作为字符串传递,而是必须正确地包含GCP函数文件系统文档中指定的文件此外,你不能在云功能环境中使用InstalledAppFlow,因为这个流是针对桌面操作系统环境的,所以最好祈祷这个块永远不会被执行或用不同的流替换。
实际上,我最终找到了这个问题的简单答案——在Python的GCP中生成这些凭据非常容易!gen_creds
的精确替换方法是:
import google.auth
from googleapiclient.discovery import build
def gen_creds(rw_vs_ro: str):
"""
Generate the service credentials to be used to query a google sheet
:param rw_vs_ro: A string, 'r_o' or 'r_w', representing whether creds should be readonly or readwrite
:return: The built service variable
"""
if rw_vs_ro == 'r_o':
scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly']
if rw_vs_ro == 'r_w':
scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds, project = google.auth.default(scopes=scopes)
service = build('sheets', 'v4', credentials=creds)
return service
希望这对别人和我一样有帮助!