如何通过代理(主机、端口)使用服务账号上传文件至Google Drive?
为Google Drive服务账号上传脚本配置代理
方法一:通过环境变量自动配置
httplib2(googleapiclient的底层网络库)会自动读取系统的HTTP_PROXY和HTTPS_PROXY环境变量,你可以通过两种方式设置:
方式1:运行脚本前在终端设置
# Linux/macOS export HTTP_PROXY=http://proxy-host:port export HTTPS_PROXY=https://proxy-host:port # Windows(PowerShell) $env:HTTP_PROXY="http://proxy-host:port" $env:HTTPS_PROXY="https://proxy-host:port"
设置完成后直接运行脚本即可,无需修改原有代码。
方式2:在脚本内部设置环境变量
在main函数开头添加环境变量配置:
os.environ['HTTP_PROXY'] = 'http://proxy-host:port' os.environ['HTTPS_PROXY'] = 'https://proxy-host:port'
方法二:手动配置带代理的HTTP客户端(适合需要认证的代理)
如果你的代理需要用户名和密码认证,或者需要更精细的控制,可以手动创建带代理的httplib2.Http实例,传给googleapiclient的build方法。修改后的完整代码如下:
import os import googleapiclient.http from googleapiclient.discovery import build from google.oauth2 import service_account import httplib2 key_file_location = 'service_account.json' # path to json file def upload_file(service, file_path, folder_id): file_name = os.path.basename(file_path) file_metadata = { 'name': file_name, 'parents': [folder_id] } media = googleapiclient.http.MediaFileUpload(file_path) file = service.files().create(body=file_metadata, media_body=media, fields='id').execute() print(f'File uploaded with ID: {file["id"]}') def main(): # 代理配置 proxy_host = 'proxy-host' proxy_port = 8080 # 如果代理需要认证,取消下面两行注释并填写实际信息 # proxy_user = 'your-proxy-username' # proxy_pass = 'your-proxy-password' # 创建带代理的httplib2客户端 proxy_info = httplib2.ProxyInfo( httplib2.socks.PROXY_TYPE_HTTP, proxy_host, proxy_port, # proxy_user=proxy_user, # proxy_pass=proxy_pass ) http = httplib2.Http(proxy_info=proxy_info) # 获取服务账号凭证,明确指定所需权限 credentials = service_account.Credentials.from_service_account_file( key_file_location, scopes=['https://www.googleapis.com/auth/drive'] ) # 将凭证与带代理的HTTP客户端绑定 http = credentials.authorize(http) # 创建Drive服务时传入自定义HTTP客户端 service = build('drive', 'v3', http=http) cho = "y" while cho == "y": file_to_upload_path = input("Enter the path to the file you want to upload: ") folder_id = input("Enter the ID of the Google Drive folder where you want to upload the file: ") upload_file(service, file_to_upload_path, folder_id) cho = input("Do you want to upload another file? (y/n): ") if __name__ == '__main__': main()
注意事项
- 若代理无需认证,直接删除
proxy_user和proxy_pass相关代码即可 - 确保服务账号已获得目标Drive文件夹的写入权限(需在Drive中共享文件夹给服务账号邮箱)
- 明确指定scopes可避免权限不足问题,示例中使用的
https://www.googleapis.com/auth/drive为全权限,若需更严格权限可替换为https://www.googleapis.com/auth/drive.file
内容的提问来源于stack exchange,提问作者P Moto500
相关产品推荐
相关产品推荐

