我正在尝试抽象我的 sqlalchemy 查询调用,完整的未修改调用如下所示:
Session.query(User).options(FromCache('redis1')).filter(User.id == user_id).all()
我需要控制的动态部分是User,redis1和最后一次调用all() 我想调用类似上面的代码,并且可以在参数中更改上面粗体的内容。
我的第一次尝试结果是这样的:
# Abstracts the final chained method
def q(obj, action):
return getattr(obj, action)()
# Removes a lot of boiler plate code
# but doesn't give me control over the cache argument
# which I need in the same method as the action above
def query(model):
return Session.query(model).options(FromCache('redis1'))
# Called like this
result = q(query(User).filter(User.id == user_id), 'all')
但我显然只想要一个功能而不是两个,这样我就可以控制动作和模型。这样做的原因是我想将.one()或.all()调用包装在一个 try-except 块中,以防查询失败,该块将通过 FromCache 选项中的不同缓存服务器。但是每次我写查询时都这样做会很烦人。
我正在寻找这样的东西(代码不起作用,显然):
def q(model, filters, action):
data = None
servers = ['redis1', 'redis2']
for server in servers:
try:
call = Session.query(model).options(FromCache(redis)).filters_here_somehow()
data = getattr(call, obj)() # Final call from action added
except:
continue
break;
return data
# and called something like this.. (or some other way)
result = q(User, the filter/between/limit/whatnot here, 'all')
有什么想法还是我完全偏离了基础?还是有更聪明的方法来做到这一点?