I just found this neat Python module called TinyDB. It’s a document based database that is written in pure Python with ~1800(!) lines of code, 40% of which I hear is comments(!!). And there’s full(!!!) test coverage? Which implies that they performed any kind of testing at all? Crazy stuff. In this post I’ll provide a small sample of inserting recipes and querying them.
Database Creation and Data Entry
The first part is pretty straight forward–we import the database, a function called where, and then we create a database called “tiny.db”, because we’re programmers, and unoriginal.
import tinydb
from tinydb import where
db = tinydb.TinyDB("tiny.db")
Next we create a list of dicts called recipes, and then insert them into our database.
recipes = [{"name":"Fried Rice", "ingredients":["rice","onion","garlic","carrot","egg","peas","soy sauce"]},
{"name":"Thai Street Pancakes", "ingredients":["wheat","green onion","garlic","shrimp","onion","mushroom","crab","soy sauce","sesame oil","lemon juice"]}]
Find a Specific Value
This is easy thanks to the where() method imported separately at the top.
db.search( where("name") == "Fried Rice" )
[{u'ingredients': [u'rice',
u'onion',
u'garlic',
u'carrot',
u'egg',
u'peas',
u'soy sauce'],
u'name': u'Fried Rice'}]
Find an Element in a List
Then we can search the value of the "ingredients" key using the .any method and this returns what we’d expect,
db.search( where("ingredients").any("onion") )
[{u'ingredients': [u'rice',
u'onion',
u'garlic',
u'carrot',
u'egg',
u'peas',
u'soy sauce'],
u'name': u'Fried Rice'},
{u'ingredients': [u'wheat',
u'green onion',
u'garlic',
u'shrimp',
u'onion',
u'mushroom',
u'crab',
u'soy sauce',
u'sesame oil',
u'lemon juice'],
u'name': u'Thai Street Pancakes'}]
There is also a .all() method that works similar to the built-in all() function in Python. More advanced usage, such as grabbing element ids, or searching with regex can be found on the Advanced Usage page.