まず、pip3でtinydbを入れる
[vagrant@localhost python]$ pip3 install tinydb
Collecting tinydb
Downloading https://files.pythonhosted.org/packages/97/6c/fb150f2c09d8b6f23b8f080396673794f970fa7ca0d50900fbe5fe07b8b9/tinydb-3.10.0-py2.py3-none-any.whl
Installing collected packages: tinydb
Successfully installed tinydb-3.10.0
続いて、python
from tinydb import TinyDB, Query
filepath = "test-tynydb.json"
db = TinyDB(filepath)
db.purge_table('fruits')
table = db.table('fruits')
table.insert({'name':'Banana', 'price':600})
table.insert({'name':'Orange', 'price':1200})
table.insert({'name':'Mango', 'price':840})
print(table.all())
Item = Query()
res = table.search(Item.name == 'Orange')
print('Orange is', res[0]['price'])
print("800円以上のもの:")
res = table.search(Item.price >= 800)
for it in res:
print("-", it['name'])
うーん、 jsonですね。phpからmongodbのinsert, fetchよりもコード量が少ないので、書きやすいかもしれませんね。
[vagrant@localhost python]$ python3 app.py
[{‘name’: ‘Banana’, ‘price’: 600}, {‘name’: ‘Orange’, ‘price’: 1200}, {‘name’: ‘Mango’, ‘price’: 840}]
Orange is 1200
800円以上のもの:
– Orange
– Mango