【问题标题】:Dynamically parse and build TinyDB queries动态解析和构建 TinyDB 查询
【发布时间】:2015-05-29 13:12:54
【问题描述】:

是否可以在 TinyDB 中动态构建查询?它的逻辑查询操作是这样的:

>>> from tinydb import TinyDB, where
>>> db = TinyDB('db.json')
>>> # Logical AND:
>>> db.search((where('int') == 1) & (where('char') == 'b'))
[{'int': 1, 'char': 'b'}]

但我需要根据用户的输入条件动态构建查询。我能弄清楚的唯一方法是将条件连接成一个字符串,然后exec 像这样:

#!/usr/bin/env python3
import shlex
from tinydb  import TinyDB, where

# create db sample
db = TinyDB('test.json')
db.insert({'id': '1', 'name': 'Tom', 'age': '10', 'grade': '4'})
db.insert({'id': '2', 'name': 'Alice', 'age': '9', 'grade': '3'})
db.insert({'id': '3', 'name': 'John', 'age': '11', 'grade': '5'})
db.close()

# query test
db = TinyDB('test.json')
q = input("query for name/age/grade: ")
# name='Tom' grade='4'
qdict = dict(token.split('=') for token in shlex.split(q))

result = []
query = "result = db.search("
qlen = len(qdict)
count = 0
for key, value in qdict.items():
    query += "(where('%s') == '%s')" % (key, value)
    count += 1
    if count < qlen:
        query += " & "

query += ')'
exec(query)
print(result)
# [{'age': '10', 'id': '1', 'grade': '4', 'name': 'Tom'}]

有没有更好更优雅的方法来做到这一点?非常感谢。

【问题讨论】:

    标签: python parsing tinydb


    【解决方案1】:

    这是一个minimal的解决方案,支持以下运算符:

    ==、!=、&gt;=、&lt;-、&gt;、&lt;

    查询的语法是:

    <key> <operator> <value>
    

    您必须用空格分隔每个标记。

    代码:

    #!/usr/bin/env python3
    
    
    from __future__ import print_function
    
    
    try:
        import readline  # noqa
    except ImportError:
        print("Warning: No readline support available!")
    
    
    try:
        input = raw_input
    except NameError:
        pass
    
    
    import sys
    from os import path
    from operator import eq, ge, gt, le, lt, ne
    
    
    from tinydb import TinyDB, where
    
    
    ops = {
        "==": eq,
        "!=": ne,
        "<=": le,
        ">=": ge,
        "<": lt,
        ">": gt,
    }
    
    
    def isint(s):
        return all(map(str.isdigit, s))
    
    
    def isfloat(s):
        return "." in s and isint(s.replace(".", ""))
    
    
    def createdb(filename):
        db = TinyDB(filename)
        db.insert({"id": 1, "name": "Tom",   "age": 10, "grade": 4})
        db.insert({"id": 2, "name": "Alice", "age":  9, "grade": 3})
        db.insert({"id": 3, "name": "John",  "age": 11, "grade": 5})
        db.close()
    
    
    def opendb(filename):
        return TinyDB(filename)
    
    
    def parse_query(s):
        qs = []
    
        tokens = s.split("&")
        tokens = map(str.strip, tokens)
    
        for token in tokens:
            try:
                k, op, v = token.split(" ", 3)
            except Exception as e:
                print("Syntax Error with {0:s}: {1:s}".format(repr(s), e))
                return where(None)
    
            opf = ops.get(op, None)
            if opf is None:
                print("Unknown operator: {0:s}".format(op))
                return where(None)
    
            if isfloat(v):
                v = float(v)
            elif isint(v):
                v = int(v)
    
            qs.append(opf(where(k), v))
    
        return reduce(lambda a, b: a & b, qs)
    
    
    def main():
        if not path.exists(sys.argv[1]):
            createdb(sys.argv[1])
    
        db = opendb(sys.argv[1])
    
        while True:
            try:
                s = input("Query: ")
                q = parse_query(s)
                print(repr(db.search(q)))
            except (EOFError, KeyboardInterrupt):
                break
    
        db.close()
    
    
    if __name__ == "__main__":
        main()
    

    演示:

    $ python foo.py test.json
    Query: name == Tom
    [{u'grade': 4, u'age': 10, u'id': 1, u'name': u'Tom'}]
    Query: grade >= 3
    [{u'grade': 4, u'age': 10, u'id': 1, u'name': u'Tom'}, {u'grade': 3, u'age': 9, u'id': 2, u'name': u'Alice'}, {u'grade': 5, u'age': 11, u'id': 3, u'name': u'John'}]
    Query: grade == 3
    [{u'grade': 3, u'age': 9, u'id': 2, u'name': u'Alice'}]
    Query: age <= 13
    [{u'grade': 4, u'age': 10, u'id': 1, u'name': u'Tom'}, {u'grade': 3, u'age': 9, u'id': 2, u'name': u'Alice'}, {u'grade': 5, u'age': 11, u'id': 3, u'name': u'John'}]
    Query: 
    

    注意事项:

    • 我只在 Python 2.7 上测试过这个
    • 我使用了最新的 tinydb 库
    • 我将您的“测试数据”更改为包含“真实”数据类型

    不过最重要的是;这不以任何方式使用eval() 或exec,并尝试解析输入并构建查询对象。

    【讨论】:

    • 非常感谢您精心编写的代码。看起来核心魔法是使用 operator 模块,我直到现在才知道。顺便说一句,Python 3 已将 reduce() 移动到 functools 模块中,Guido 在 [docs.python.org/3.0/whatsnew/3.0.html](Python 3.0 中的新增功能)中说,“删除了 reduce()。如果你真的需要它,请使用 functools.reduce();但是,99显式 for 循环在一定程度上更具可读性。”我想你的代码占了 1% 的时间。 :-)
    • 很高兴您发现这很有用;我希望其他人也会!
    猜你喜欢
    • 2012-11-23
    • 1970-01-01
    • 2019-04-08
    • 2012-12-21
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 2019-06-24
    相关资源
    最近更新 更多