如何在远程服务器通过Python实现Google Drive账号授权与用户文件上传
解决服务器端用PyDrive实现用户Google Drive授权上传的问题
问题根源
LocalWebserverAuth是为本地开发设计的,回调地址指向localhost:8080,用户端没有对应本地服务,无法完成授权回调。CommandLineAuth依赖的urn:ietf:wg:oauth:2.0:oob离线授权码模式已被Google OAuth弃用,服务器端运行必然报错。
正确解决方案:配置Web应用类型凭据+服务器回调授权
1. 调整Google控制台凭据类型
- 进入Google Cloud控制台,找到目标项目,进入「API和服务」→「凭据」。
- 删除原「桌面应用」凭据,创建新的「Web应用」类型凭据。
- 在「已获授权的重定向URI」中添加服务器公网回调地址,比如
https://你的服务器域名/auth/callback(后续代码需对应此地址)。
2. 配置PyDrive授权参数
在代码同目录创建settings.yaml文件,内容如下:
client_config_backend: file client_config: client_id: 你的Web应用客户端ID client_secret: 你的Web应用客户端密钥 auth_uri: https://accounts.google.com/o/oauth2/auth token_uri: https://oauth2.googleapis.com/token redirect_uri: https://你的服务器域名/auth/callback save_credentials: True save_credentials_backend: file save_credentials_file: credentials.json get_refresh_token: True
3. 编写服务器端授权逻辑(以Flask为例)
适配服务器场景处理授权请求与回调,示例代码如下:
from flask import Flask, request, redirect, session from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive app = Flask(__name__) app.secret_key = "你的随机密钥" @app.route('/auth') def auth(): gauth = GoogleAuth() gauth.LoadSettingsFile("settings.yaml") auth_url = gauth.GetAuthUrl() session['gauth_state'] = gauth.credentials.state return redirect(auth_url) @app.route('/auth/callback') def auth_callback(): gauth = GoogleAuth() gauth.LoadSettingsFile("settings.yaml") code = request.args.get('code') gauth.Auth(code) gauth.SaveCredentialsFile("credentials.json") # 初始化Drive客户端,添加上传逻辑 drive = GoogleDrive(gauth) test_file = drive.CreateFile({'title': 'server_upload_test.txt'}) test_file.SetContentString('文件由服务器端上传至Google Drive') test_file.Upload() return "授权完成,测试文件已上传" if __name__ == '__main__': app.run(host='0.0.0.0', port=80)
4. 核心注意事项
- 确保服务器回调地址公网可访问,无防火墙拦截。
get_refresh_token: True配置可让凭据自动刷新,避免频繁授权。- 生产环境建议用环境变量管理
client_secret,不要硬编码在代码中。
内容的提问来源于stack exchange,提问作者Dioswison
相关产品推荐
相关产品推荐

