这是一个支持以下运算符的最小解决方案:
==
, !=
, >=
, <-
, >
,<
查询的语法是:
<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
以任何方式尝试解析输入并构建查询对象。