我使用传播的python库制作了一个Worksheet类。这是我的代码:
from oauth2client.service_account import ServiceAccountCredentials
import time
import gspread
import requests
import os
DIRNAME = os.path.dirname(__file__)
class Wksh:
credentials_google_sheet = ServiceAccountCredentials.from_json_keyfile_name(os.path.join(DIRNAME, 'credentials/gs_credentials.json'),['https://spreadsheets.google.com/feeds'])
gc = gspread.authorize(credentials_google_sheet)
worksheet_id = None
sheet_name = None
sheet = None
def __init__(self,wksh_id,sh_name):
while True:
try:
self.worksheet_id = wksh_id
self.sheet_name = sh_name
self.sheet = self.gc.open_by_key(wksh_id).worksheet(sh_name)
break
except (gspread.exceptions.HTTPError, gspread.exceptions.requests, gspread.exceptions.RequestError) as e:
if e[0] == 401:
self.gc.login()
elif e[0] == 500:
time.sleep(10)
else:
print 'init'
print e
break
except requests.exceptions.ConnectionError as e:
time.sleep(10)
except requests.exceptions.ChunkedEncodingError as e:
time.sleep(20)
def write(self,cell,value):
while True:
try:
self.sheet.update_acell(cell,value)
break
except (gspread.exceptions.HTTPError, gspread.exceptions.requests, gspread.exceptions.RequestError) as e:
if e[0] == 401:
self.gc.login()
elif e[0] == 500:
time.sleep(10)
else:
print 'write'
print e
break
except requests.exceptions.ConnectionError as e:
time.sleep(10)
except requests.exceptions.ChunkedEncodingError as e:
time.sleep(20)
这很好用,但是每当有请求错误时,即使我尝试捕获错误也得到:
AttributeError: 'module' object has no attribute 'RequestError' or
AttributeError: 'module' object has no attribute 'HTTPError'
为什么会这样?我需要在例外之前使用self.
吗?
谢谢
答案 0 :(得分:2)