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

如何用Google Drive API Python创建token.json实现免重复登录

实现Google Drive批量删除代码的凭证持久化(保存token.json避免重复登录)

修改后的代码会自动将登录凭证保存到token.json文件中,后续运行时优先读取该文件,无需重复进行账号授权操作:

import os
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.http import BatchHttpRequest

SCOPES = ['https://www.googleapis.com/auth/drive']

def callback(request_id, response, exception):
    if exception:
        print(f"发生错误: {exception}")
    else:
        print(f"已删除文件ID: {request_id}")


def main():
    creds = None
    # 检查是否存在已保存的token文件
    if os.path.exists('token.json'):
        with open('token.json', 'rb') as token:
            creds = pickle.load(token)
    # 没有有效凭证时,重新授权
    if not creds or not creds.valid:
        flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
        # 保存凭证到token.json
        with open('token.json', 'wb') as token:
            pickle.dump(creds, token)
    
    service = build('drive', 'v3', credentials=creds)

    results = service.files().list(pageSize=100, fields="nextPageToken, files(id)").execute()
    items = results.get('files', [])

    if not items:
        print('未找到文件。')
    else:
        batch = service.new_batch_http_request(callback=callback)
        for item in items:
            batch.add(service.files().delete(fileId=item['id']))
        batch.execute()
        

if __name__ == '__main__':
    main()

关键修改点:

  • 导入os模块用于检查文件是否存在,pickle模块用于序列化/反序列化凭证对象
  • 启动时优先读取token.json中的已保存凭证,无需重复授权
  • 首次授权成功后,自动将凭证写入token.json,供后续运行使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 23:20:59