python - 处理 SheetsAPI 错误 - Python 2.7

标签 python python-2.7 pycharm google-sheets-api

非常需要你的帮助,我一直在努力解决这个问题,并尝试使用 urllib2 和其他方法来 try catch 加载不存在的工作表时给出的 HttpError。

所以这是初始调用代码

discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?''version=v4')
service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)
result = service.spreadsheets().values().get(spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values', [])

if not values:
     print('No data found.')
     tkMessageBox.showwarning("ERROR", "There is nothing on this page!")
     LoadCSV()
else:

现在好了。当我调用一个不存在的工作表时,我想处理错误并显示一条警告说“没有更多的工作表可以尝试”

这里是错误:

HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/(ID)/values/130%21A2%3AI?alt=json returned "Unable to parse range: 130!A2:I">

我该如何处理这个错误,而不是给出页面不存在的警告并终止程序。

最佳答案

我在使用 sheets-api-quickstart 时看到 googleapiclient.errors.HttpError .这对我有用:

import googleapiclient

discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?''version=v4')
service = discovery.build('sheets', 'v4', http=http, discoveryServiceUrl=discoveryUrl)
try: 
     # The `execute()` call triggers the exception.
     result = service.spreadsheets().values().get(spreadsheetId=spreadsheetId, range=rangeName).execute()
     # deceptively named, custom HttpError
except googleapiclient.errors.HttpError:
     print "page does not exist"
else:
    values = result.get('values', [])

    if not values:
         print('No data found.')
         tkMessageBox.showwarning("ERROR", "There is nothing on this page!")
         LoadCSV()
    else:

关于python - 处理 SheetsAPI 错误 - Python 2.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41155732/

相关文章:

javascript - 我怎样才能让我的 Tornado 服务器渲染 javascript?

python - Selenium with Python - Chromedriver 必须在 PATH 中

python - 循环调用列表中的每个方法?

python - 如何告诉 PyCharm 在测试文件而不是 doctests 上运行 pytest

python - Django,使用数据库中的样式

python - 从celery后端(redis)获取数据

python - 如何在 Odoo 表单中自动填写内容?

python - 如何提示基类函数返回调用它的派生类的实例?

python - 如何使用python获取此图像的某些颜色(RGB)的像素坐标?

python - 如何保存文件夹和子文件夹中的音频文件(.wav)的频谱图?