You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Python中手动刷新Google OAuth2的access_token?

手动刷新Google OAuth2 Access Token(适配非官方支持的API场景)

嘿,我来帮你搞定这个问题!当你用Google官方客户端库调用Drive这类支持的服务时,token自动刷新是因为库已经帮你封装好逻辑了,但像Gmail Atom Feed这种没被官方库覆盖的接口,就得咱们自己手动处理token刷新。下面是一步步的具体操作和代码示例:

先搞懂核心逻辑

首先要明确:你通过oauthlib拿到的Credentials对象里,除了access_token,还有个关键的refresh_token(前提是你授权时请求了offline权限)。这个refresh_token就是用来获取新access_token的钥匙,所以第一步必须确保你授权时加对参数。

具体实现步骤

1. 首次授权时确保拿到refresh_token

授权流程里一定要加上access_type='offline'prompt='consent'(第一次授权用,强制获取refresh_token),示例代码:

from google_auth_oauthlib.flow import InstalledAppFlow

# 定义权限范围,Gmail Atom Feed需要mail.readonly权限
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

flow = InstalledAppFlow.from_client_secrets_file(
    'credentials.json', SCOPES)
# 关键参数:access_type='offline' 确保拿到refresh_token
creds = flow.run_local_server(port=0, access_type='offline', prompt='consent')

# 把credentials保存到本地,方便后续使用
with open('token.json', 'w') as token_file:
    token_file.write(creds.to_json())

2. 每次调用API前检查并刷新token

下次启动程序时,先加载保存的credentials,检查是否过期,如果过期就用refresh_token刷新:

from google.oauth2.credentials import Credentials
import requests

# 加载本地保存的credentials
creds = Credentials.from_authorized_user_file('token.json')

# 检查token是否过期,且有可用的refresh_token
if creds.expired and creds.refresh_token:
    # 用requests.Request()作为刷新的请求对象
    creds.refresh(requests.Request())
    # 刷新后一定要把新的credentials重新保存,覆盖旧文件
    with open('token.json', 'w') as token_file:
        token_file.write(creds.to_json())

3. 调用Gmail Atom Feed接口

现在拿着刷新后的access_token去请求接口就行:

# 示例:获取Gmail收件箱的Atom Feed
gmail_feed_url = 'https://mail.google.com/mail/feed/atom'
headers = {'Authorization': f'Bearer {creds.token}'}

response = requests.get(gmail_feed_url, headers=headers)
if response.status_code == 200:
    # 这里可以处理返回的XML内容,比如解析成字典或者直接使用
    print("Feed获取成功:")
    print(response.text[:500])  # 打印前500个字符示例
else:
    print(f"请求失败,状态码:{response.status_code},响应内容:{response.text}")

几个关键注意点

  • refresh_token是核心:如果授权时没加access_type='offline',是拿不到refresh_token的,这种情况下无法手动刷新,只能重新走授权流程加上这个参数。
  • 及时保存刷新后的凭据:每次刷新后,access_token和过期时间都会更新,一定要覆盖保存旧的token文件,不然下次启动还是用过期的token。
  • 处理刷新失败的情况:如果用户后来撤销了你的应用权限,refresh_token会失效,这时候需要重新引导用户完成OAuth授权,获取新的refresh_token。

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

火山引擎 最新活动