def get(cls, *args, **kwargs):
"""Generic 'smart' get function. Does different things based
on number of arguments. Some would call this a 'not smart'
idea but we are not asking them.
Single positional argument and no kwargs:
args[0] is not of type ClauseElement:
Looks up model by primary key of model specified by cls.PKEY
args[0] is of type ClauseElement:
Adds the clause emelemt to a where clause for a query on cls.
Anything Else (any combination of multiple args and any kwargs):
Converts all kwargs to clause elements, adds the args (all
should be clause elements), and passes them together in as
the where filter (all combined with AND) to a query on cls.
"""
if len(args) == 1 and not isinstance(args[0], ClauseElement):
terms = [getattr(cls, cls.PKEY) == args[0]]
else:
terms = list(args) + \
[getattr(cls, k) == v for k, v in kwargs.items()]
obj = cls.query.filter(*terms).first()
if obj:
return obj
cause = dict(kwargs) if kwargs else list(args)
raise ApiException(
"Failed to get %s: %s" % (cls.__name__, cause),
cause=list(cause.keys()) if kwargs else cause)
评论列表
文章目录