django - Search criteria language parser in Python? -
i writing web app django , djangorestframework internal app school. replacement old homegrown app written in microsoft access 2003. 1 of functionalities users have able search field (e.g. donation_amount in donationtable) not exact amount query such this:
< 130 , > 125 access allows sort of functionality , useful, unaware of way implement without inserting queries directly sql (extremely dangerous) or using eval in python expression (even more dangerous).
are there libraries or sub-languages permit this?
i'm not familiar django's ecosystem, python standard library contains ast.parse, parses valid python expression string , produces abstract syntax tree, can dissect , translate query - or serie of function calls, or whatever need. if can't find more specific, might of use.
this code:
ast.parse('donation_amount < 130 , donation_amount > 125') returns following ast structure:
ast.module( ast.expr([ ast.boolop(ast.and(), [ ast.compare( [ast.lt()], ast.name('donation_amount', ast.load()), [ast.num(130)]), ast.compare( [ast.gt()], ast.name('donation_amount', ast.load()), [ast.num(125)])])])) so takes care of parsing, you'll still need translate query of own. looks need handle small number of node types:
boolop -> and, or compare -> ==, !=, >, <, >=, <=, in, not in name -> identifiers (column names, true/false/null, etc.) num -> numbers str -> strings and perhaps ast.call nodes, if want support database functions, , ast.tuple or ast.list nodes, if want support in functionality. if ast contains other node types can reject invalid query.
Comments
Post a Comment