sqlalchemy Evalulate Criteria based on list of tuple, searching?
I want to apply some access rule type of mechanism, for that I'm planning to use list of tuple for specifying rules for restrictions like below
['|',('name','=','root'), ('role','=','admin')]
using postfix notations...
is there any e开发者_开发百科xisting mechanism in python that may help me to convert such domain into sqlalchemy query lang like
or_(User.name='root', User.role='admin')
Here's a start of one:
I'm going to rewrite your expression in terms of prefix notation; the operator is first and the other values follow, so:
test_expression = ['|',('=','name','root'), ('=','role','admin')]
but, you could probably add some more operator specific checks to handle operators in other locations.
def buildquery(context, expression):
OPERATORS[expression[0]](context, expression[1:])
def build_or(context, args):
return sqlalchemy.or_(*(buildquery(context, arg) for arg in args))
def build_eq(context, args):
colname, value = args
return getattr(context, colname) == value
OPERATORS = {
'|': build_or,
'=': build_eq}
And to use it, pass the mapped class you want to use the query with:
session.query(User).filter(build_query(User, test_expression))
精彩评论