
在构建基于Python与Google服务(特别是Google Apps Script)的自动化解决方案时,开发者常会遇到一个挑战:每次运行脚本时,系统都要求用户进行浏览器认证。这对于需要端到端自动化、无人值守执行的场景来说,是一个巨大的障碍。本教程将详细阐述如何通过妥善管理OAuth 2.0认证凭据,实现Python脚本对Google Apps Script的无感(非交互式)调用。
Python通过Google API客户端库与Google服务交互时,通常采用OAuth 2.0协议进行身份验证和授权。首次运行时,google_auth_oauthlib库会引导用户在浏览器中完成授权流程,生成一个访问令牌(Access Token)和一个刷新令牌(Refresh Token)。访问令牌具有较短的有效期(通常为1小时),过期后需要重新获取。如果每次脚本运行时都重新执行完整的OAuth 2.0认证流程,就会导致重复的浏览器认证弹窗,从而阻碍自动化。
要实现无感认证,核心在于持久化存储首次认证后获得的凭据,并在访问令牌过期时,利用刷新令牌自动获取新的访问令牌,而无需用户再次手动干预。
解决重复认证问题的关键在于使用一个token.json文件来持久化存储用户的OAuth 2.0凭据。这个文件会保存访问令牌、刷新令牌、令牌类型以及过期时间等信息。当脚本再次运行时:
立即学习“Python免费学习笔记(深入)”;
通过这种机制,只有在首次运行或刷新令牌失效(例如用户撤销了授权)时才需要手动认证,极大地方便了自动化部署。
在编写Python代码之前,请确保完成以下准备工作:
pip install google-api-python-client google-auth-oauthlib google-auth-httplib2
以下是实现持久化认证并调用Google Apps Script的Python代码示例:
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 import errors
from googleapiclient.discovery import build
# 定义所需的API权限范围
# 请根据你的Apps Script实际操作,选择最小化的权限集。
# 过多的权限会增加安全风险,并可能导致用户在认证时犹豫。
SCOPES = [
"https://www.googleapis.com/auth/script.projects",
"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.scripts",
"https://www.googleapis.com/auth/script.processes",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/script.scriptapp",
]
def run_apps_script_with_persistent_auth(script_id: str, function_name: str):
"""
使用持久化认证调用Google Apps Script API。
在首次运行时会进行浏览器认证并生成token.json,后续运行将自动加载和刷新令牌。
Args:
script_id (str): 要执行的Google Apps Script项目的ID。
function_name (str): Apps Script中要调用的函数名称。
"""
creds = None
# 1. 尝试从token.json加载已存储的凭据
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
# 2. 如果没有有效凭据,或者凭据已过期且可刷新,则进行认证或刷新
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
# 凭据过期但有刷新令牌,尝试刷新
print("凭据已过期,尝试使用刷新令牌更新...")
creds.refresh(Request())
else:
# 没有有效凭据或无法刷新,启动新的认证流程
print("首次运行或刷新令牌失效,启动新的认证流程...")
flow = InstalledAppFlow.from_client_secrets_file(
"credentials.json", SCOPES
)
creds = flow.run_local_server(port=0) # 在本地启动Web服务器进行认证
# 3. 将新的或刷新的凭据保存到token.json,以便后续使用
with open("token.json", "w") as token:
token.write(creds.to_json())
print("凭据已保存/更新到 token.json。")
try:
# 4. 使用获取到的凭据构建Apps Script服务客户端
service = build("script", "v1", credentials=creds)
# 5. 构建执行请求
request = {"function": function_name}
# 6. 执行Apps Script函数
print(f"正在执行Apps Script函数: {function_name} (Script ID: {script_id})...")
response = service.scripts().run(body=request, scriptId=script_id).execute()
print("Apps Script函数执行成功。")
# 可以根据需要处理Apps Script函数的返回值
if 'error' in response:
print(f"Apps Script执行错误: {response['error']}")
else:
print(f"Apps Script函数返回值: {response.get('response', {}).get('result')}")
except errors.HttpError as error:
# 捕获API调用错误
print(f"调用Apps Script API时发生错误: {error.content}")
except Exception as e:
print(f"发生未知错误: {e}")
# 示例用法
if __name__ == "__main__":
# 替换为你的实际Google Apps Script项目ID和要调用的函数名
my_script_id = "你的Google Apps Script项目ID" # 例如: AKfycbxtDnDYa2mTZKB6WoqK_D9PDsLZyqb7GQAh7pvER-K-rMFXYNa6oVOhzXHsyfyl8vLz
my_function_name = "helloWorld" # Apps Script中的函数名
run_apps_script_with_persistent_auth(my_script_id, my_function_name)通过本文介绍的持久化认证方法,开发者可以有效地解决Python调用Google Apps Script时重复认证的问题。利用token.json文件存储和管理OAuth 2.0凭据,实现了访问令牌的自动刷新,从而构建了无需人工干预的自动化流程。这对于数据同步、报表生成、工作流自动化等场景至关重要,极大地提升了自动化解决方案的效率和可靠性。在实施过程中,务必关注权限管理和凭据安全,以确保系统的稳健运行。
以上就是Python调用Google Apps Script实现无感认证自动化教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号