动态解析和构建TinyDB查询

时间:2015-05-29 13:12:54

标签: python parsing tinydb

是否可以在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'}]

有更好更优雅的方法吗?非常感谢。

1 个答案:

答案 0 :(得分:3)

以下是支持以下运算符的 minimal 解决方案:

==!=>=<-><

查询的语法是:

<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
  • 我改变了你的测试数据&#34;包括&#34;真实&#34;数据类型

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