create = service.files().create(body=file_metadata, media_body=media, **create_params) 捕获超时异常
时间: 2023-09-01 17:11:27 浏览: 92
实现捕获应用的运行时异常
5星 · 资源好评率100%
好的,您可以使用try-except语句来捕获超时异常,如下所示:
```
import google.auth
from google.auth.transport.requests import Request
from googleapiclient.errors import HttpError
from googleapiclient.discovery import build
# 创建服务对象
creds = None
if creds and creds.valid:
service = build('drive', 'v3', credentials=creds)
else:
creds = google.auth.default(scopes=['https://www.googleapis.com/auth/drive'])
service = build('drive', 'v3', credentials=creds)
try:
file_metadata = {'name': 'test.txt'}
media = MediaFileUpload('test.txt',
mimetype='text/plain')
create_params = {'fields': 'id'}
create = service.files().create(body=file_metadata,
media_body=media,
**create_params)
result = None
while result is None:
status, result = create.next_chunk()
if status:
print("上传进度: {}%".format(int(status.progress() * 100)))
print('文件已上传,文件ID:{0}'.format(result.get('id')))
except HttpError as error:
if error.resp.status == 429:
print('请求频率过高,请稍后再试')
elif error.resp.status == 500 or error.resp.status == 502 or error.resp.status == 503 or error.resp.status == 504:
print('服务器错误,请稍后再试')
else:
print('An error occurred: %s' % error)
except TimeoutError:
print('请求超时,请稍后再试')
```
在上面的代码中,我们使用try-except语句来包含文件上传代码,并使用HttpError来捕获其他异常,使用TimeoutError来捕获超时异常。如果发生超时异常,程序将打印出“请求超时,请稍后再试”的提示。
阅读全文