我正在使用 Flask 和 Flask-SQLAlchemy 編寫一個應(yīng)用程序。我希望用戶能夠使用特定于域的查詢語言來查詢數(shù)據(jù)庫,例如parent.name = "foo" AND (name = "bar" OR age = 11).我使用 Pyparsing 為這種語言編寫了一個解析器:import pyparsing as ppquery = 'parent.name = "foo" AND (name = "bar" OR age = 11)'and_operator = pp.oneOf(['and', '&'], caseless=True)or_operator = pp.oneOf(['or', '|'], caseless=True)identifier = pp.Word(pp.alphas + '_', pp.alphas + '_.')comparison_operator = pp.oneOf(['=','!=','>','>=','<', '<='])integer = pp.Regex(r'[+-]?\d+').setParseAction(lambda t: int(t[0]))float_ = pp.Regex(r'[+-]?\d+\.\d*').setParseAction(lambda t: float(t[0]))string = pp.QuotedString('"')comparison_operand = string | identifier | float_ | integercomparison_expr = pp.Group(comparison_operand + comparison_operator + comparison_operand)grammar = pp.operatorPrecedence(comparison_expr, [ (and_operator, 2, pp.opAssoc.LEFT), (or_operator, 2, pp.opAssoc.LEFT) ])result = grammar.parseString(query)print(result.asList())這給了我以下輸出:[[['parent.name', '=', 'foo'], 'and', [['name', '=', 'bar'], 'or', ['age', '=', 11]]]]現(xiàn)在我不知道該怎么辦。如何動態(tài)生成 SQLAlchemy 查詢?是否有任何圖書館可以幫助解決這個問題?生成原始 SQL 會更容易嗎?
添加回答
舉報
0/150
提交
取消