You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Requests导出Google Sheet为PDF的OAuth2认证问题求助

解决方案

1. 修正OAuth2权限范围

当前你的scope仅请求了用户信息权限,没有访问Google Sheets的权限,必须添加Sheets相关权限才能导出文件。将scope修改为:

scope = [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
    'https://www.googleapis.com/auth/spreadsheets.readonly'  # 只读权限足够支持PDF导出
]

若需要对表格执行编辑操作,可替换为https://www.googleapis.com/auth/spreadsheets。

2. 使用已认证的OAuth2Session发起请求

你之前直接调用request.get(CALL)未携带认证信息,应该用初始化好的oauth对象发起请求,它会自动携带已获取的token:

# 替换原有的request.get(CALL)
response = oauth.get(CALL)

# 保存导出的PDF文件
if response.status_code == 200:
    with open('sheet_export.pdf', 'wb') as f:
        f.write(response.content)
    print("PDF导出成功")
else:
    print(f"请求失败,状态码:{response.status_code},响应内容:{response.text}")

完整修正后的代码示例

from requests_oauthlib import OAuth2Session
import os

os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = ' '

client_id = "xxx"
client_secret = "xxx"
redirect_uri = 'http://localhost'

# 修正权限范围
scope = [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
    'https://www.googleapis.com/auth/spreadsheets.readonly'
]

oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope)
authorization_url, state = oauth.authorization_url(
    "https://accounts.google.com/o/oauth2/auth",
    access_type="offline",
    prompt="select_account"
)

print(f'请访问此链接授权:{authorization_url}')
authorization_response = input('输入回调的完整URL:')

token = oauth.fetch_token(
        "https://oauth2.googleapis.com/token",
        code=authorization_response,
        client_secret=client_secret
)

# 验证用户信息(可选操作)
r = oauth.get('https://www.googleapis.com/oauth2/v1/userinfo')
print(r.json())

# 构建PDF导出链接
URL = "https://docs.google.com/spreadsheets/d/"
ID = "1ZUG5Xlesc-e1EfGg_T16vamQ_igMXvPb6VNQoWZegDE"

PARAM = [
    '/export?exportFormat=pdf&format=pdf',
    '&size=LETTER',
    '&portrait=true',
    '&fitw=true',
    '&top_margin=0.75',
    '&bottom_margin=0.75',
    '&left_margin=0.7',
    '&right_margin=0.7',
    '&sheetnames=false&printtitle=false',
    '&pagenum=UNDEFINED',
    '&gridlines=true',
    '&fzr=FALSE'
]

params = ''.join(PARAM)
CALL = URL + ID + params

# 发起认证请求并保存PDF
response = oauth.get(CALL)
if response.status_code == 200:
    with open('sheet_export.pdf', 'wb') as f:
        f.write(response.content)
    print("PDF已成功导出")
else:
    print(f"导出失败:{response.status_code} - {response.text}")

关键注意事项

  • 确保授权的Google账号拥有目标Sheet的访问权限(只读或编辑权限均可)
  • access_type="offline"会返回refresh_token,后续可通过它刷新access_token,无需重复手动授权

内容的提问来源于stack exchange,提问作者Anish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 20:14:52