【发布时间】:2020-04-22 07:48:46
【问题描述】:
目标
包装gspread模块的每个类的每个函数。
我知道有无数关于这个主题的帖子,并且最一致地指示使用装饰器。 我对装饰器不太熟悉,感觉这种方法并不像我希望的那样无缝。可能我没听懂。
但是,我发现这个answer“感觉”就像我要找的东西。
(差)尝试
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os
import inspect
class GoogleSheetAPI:
def __init__(self):
f = os.path.join(os.path.dirname(__file__), 'credentials.json')
os.environ.setdefault('GOOGLE_APPLICATION_CREDENTIALS', f)
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name(f, scope)
self.client = gspread.authorize(credentials)
self.client.login()
def SafeCall(f):
try:
print 'before call'
f()
print 'after call'
except:
print 'exception caught'
return None
for class_name, c in inspect.getmembers(gspread, inspect.isclass):
for method_name, f in inspect.getmembers(c, inspect.ismethod):
setattr(c, f, SafeCall(f)) # TypeError: attribute name must be string, not 'instancemethod'
g = GoogleSheetAPI()
spreadsheet = g.client.open_by_key('<ID>') # calls a function in gspread.Client
worksheet = spreadsheet.get_worksheet(0) # calls a function in gspread.Spreadsheet
worksheet.add_rows(['key','value']) # calls a function in gspread.Worksheet
注意事项
- 当我使用“无缝”这个词时,我的意思是考虑到我的代码对许多
gspread函数有很多调用,我希望尽可能少地进行更改。使用inspect/setattr似乎是完美/无缝的技巧。
【问题讨论】:
标签: python-2.7