
在使用python程序与google apps script api进行交互时,尤其是在构建自动化工作流(例如,将数据从数据库推送到google sheets并触发apps script进行格式化)时,开发者常会遇到一个阻碍:每次运行python脚本,系统都会要求用户进行oauth 2.0认证。这种交互式的认证流程,通过浏览器弹出窗口进行授权,显然无法满足无人值守的自动化部署需求,导致端到端自动化方案难以实现。
问题的根源在于,默认的OAuth 2.0认证流程是为交互式应用设计的,它会生成临时的访问令牌。为了实现自动化,我们需要一种机制来持久化这些认证凭据,以便在后续运行时无需用户再次手动授权。
解决重复认证问题的关键在于利用OAuth 2.0的刷新令牌(Refresh Token)机制。当用户首次完成认证并授权后,除了获得一个短期的访问令牌(Access Token),还会获得一个长期的刷新令牌。通过这个刷新令牌,Python程序可以在访问令牌过期后,自动向Google认证服务器请求新的访问令牌,而无需用户再次介入。
实现这一机制的核心是创建一个本地文件(通常命名为token.json),用于安全地存储这些授权凭据。当脚本首次运行时,它会引导用户完成认证并将获得的凭据保存到token.json。后续运行时,脚本会优先检查token.json是否存在且凭据是否有效。如果凭据有效,则直接使用;如果凭据过期但刷新令牌可用,则自动刷新;否则,才会再次引导用户进行认证。
在编写Python代码之前,需要完成以下准备工作:
立即学习“Python免费学习笔记(深入)”;
Google Cloud项目设置
Apps Script部署
Python依赖安装
pip install google-api-python-client google-auth-oauthlib google-auth-httplib2
以下是实现Python免认证调用Google Apps Script的示例代码。此代码封装了认证逻辑,并展示了如何执行一个Apps Script函数。
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient import errors
# 定义API权限范围(Scopes)。请根据您的Apps Script实际操作选择最小必要的权限。
# 示例中包含了常见的Apps Script、Drive和Sheets操作权限。
SCOPES = [
"https://www.googleapis.com/auth/script.projects", # 管理Apps Script项目
"https://www.googleapis.com/auth/script.external_request", # 允许Apps Script进行外部请求
"https://www.googleapis.com/auth/drive.readonly", # 读取Google Drive文件
"https://www.googleapis.com/auth/drive", # 修改Google Drive文件
"https://www.googleapis.com/auth/spreadsheets", # 操作Google Sheets
# 根据Apps Script的实际功能,可能还需要其他权限,例如:
# "https://www.googleapis.com/auth/script.scriptapp", # 允许Apps Script访问自身环境
# "https://www.googleapis.com/auth/script.processes", # 管理Apps Script进程
]
def authenticate_and_run_apps_script(script_id: str, function_name: str):
"""
处理Google Apps Script的认证流程并执行指定函数。
如果token.json不存在或过期,将引导用户进行认证并保存凭据。
"""
creds = None
token_file = "token.json"
credentials_file = "credentials.json" # 从Google Cloud下载的客户端密钥文件
# 1. 尝试从token.json加载已保存的凭据
if os.path.exists(token_file):
creds = Credentials.from_authorized_user_file(token_file, SCOPES)
# 2. 如果凭据不存在、无效或已过期,则进行认证流程
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
# 凭据过期但有刷新令牌,尝试自动刷新
print("凭据已过期,尝试使用刷新令牌更新...")
try:
creds.refresh(Request())
except Exception as refresh_error:
print(f"刷新令牌失败: {refresh_error}。将进行重新认证。")
# 刷新失败,需要重新进行交互式认证
flow = InstalledAppFlow.from_client_secrets_file(credentials_file, SCOPES)
creds = flow.run_local_server(port=0)
else:
# 首次认证或刷新令牌无效,进行交互式认证
print("进行首次认证或重新认证,请在浏览器中完成授权...")
flow = InstalledAppFlow.from_client_secrets_file(credentials_file, SCOPES)
creds = flow.run_local_server(port=0)
# 3. 将新获取或刷新的凭据保存到token.json,以便后续使用
with open(token_file, "w") as token:
token.write(creds.to_json())
print(f"凭据已成功保存到 {token_file}")
try:
# 4. 构建Apps Script API服务客户端
service = build("script", "v1", credentials=creds)
# 5. 准备Apps Script函数的执行请求
request_body = {"function": function_name}
print(f"正在执行Apps Script函数: '{function_name}' (部署ID: {script_id})...")
# 6. 执行Apps Script函数
response = service.scripts().run(body=request_body, scriptId=script_id).execute()
# 7. 处理Apps Script函数的执行结果
if 'error' in response:
# Apps Script内部执行失败
error_details = response['error']['details']
print(f"Apps Script执行失败: {error_details}")
# 可以在这里解析error_details以获取更详细的错误信息
for detail in error_details:
print(f" 错误类型: {detail.get('errorType')}, 消息: {detail.get('errorMessage')}")
else:
# Apps Script函数执行成功
print(f"Apps Script函数 '{function_name}' 执行成功!")
# 如果Apps Script函数有返回值,可以通过response['response']['result']获取
if 'response' in response and 'result' in response['response']:
print(f"函数返回结果: {response['response']['result']}")
except errors.HttpError as error:
# Google API调用本身发生错误(例如权限不足、API不可用、script_id错误等)
print(f"Google API调用发生错误: {error}")
print(f"错误内容: {error.content.decode('utf-8')}")
except Exception as e:
# 捕获其他未知异常
print(f"发生未知错误: {e}")
if __name__ == "__main__":
# 请替换为您的Apps Script部署ID和要执行的函数名
YOUR_SCRIPT_ID = "AKfycbxtDnDYa2mTZKB6WoqK_D9PDsLZyqb7GQAh7pvER-K-rMFXYNa6oVOhzXHsyfyl8vLz" # 示例ID
YOUR_FUNCTION_NAME = "helloWorld" # 示例Apps Script函数名
# 首次运行时,会弹出浏览器窗口进行认证。认证成功后,会在当前目录生成token.json。
# 后续运行将直接使用token.json进行认证,无需人工干预。
authenticate_and_run_apps_script(YOUR_SCRIPT_ID, YOUR_FUNCTION_NAME)Apps Script helloWorld 示例 (可选):
如果您需要一个简单的Apps Script函数来测试,可以在您的Apps Script项目中添加以下代码:
function helloWorld() {
Logger.log("Hello from Apps Script!");
return "Hello from Apps Script!";
}然后将此Apps Script项目部署为API可执行文件。
安全性
最小权限原则
错误处理
无头环境部署
Apps Script函数返回值
通过本文介绍的方法,您已经掌握了如何在Python中实现Google Apps Script的免认证自动化执行。核心在于利用OAuth 2.0的刷新令牌机制,通过token.json文件持久化用户凭据。这不仅解决了重复认证的痛点,更使得Python与Google Apps Script的集成在自动化场景下变得高效和可行。遵循最佳实践,特别是关于安全性和权限管理的建议,将确保您的自动化解决方案既强大又可靠。
以上就是Python调用Google Apps Script实现免认证自动化执行的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号