TinyDB : A Python No-SQL Flatfile Database

Cornelius Tantius
Bina Nusantara IT Division
3 min readApr 2, 2021
Photo by Pisit Heng on Unsplash

When working on your python application project, you will definitely find yourself at a situation where you have to store some application data. Of course you can directly store your data into a text file or sort, but parsing and processing that data might need a lot of work. Another option is by setting a MsSQL server, but that option might be a bit too overkill for your small application project too. At this chance, we will talk about TinyDB, a lightweight python library that allows you to store your data in a single JSON file and requires no sophisticated codes to operate.

TinyDB is a lightweight document oriented database optimized for your happiness 😊

TinyDB will store everything in JSON file, directly to your disk that made this DB is document oriented. This JSON file make our data represented as dictionary in python. Also, since this library is written in pure python, you don’t need to think about any external dependencies.

Installation

Console command to install python tinydb library
Console command to install python tinydb library

The installation process of this library is pretty straight forward just like installing any other python library. We can simply run command above and we are good to go.

Usage

At this part, we will try to use TinyDB to store our Pokémon data. The first step we need to do is importing the library and the library’s submodules (TinyDB to initialize our DB class and Query to help us building query when searching data).

Library and submodules import

Next step is initializing (or read existing) flatfile database.

Database initializing

With our Db initialized, we can start inserting data to our data in dictionary shape.

Data insertion

With all of that step covered, we can now run our code, and we can saw that the file tinydb.json is created inside data folder. To view all of our data, we can use the db variable we created before and call the all() method. Since calling all() method will return us a list, we will iterate each item in the list just to get proper viewing result.

Viewing all data

But at this case, suppose we would like to search Pokémon that has ‘dex’ number 7. In order to search that Pokémon, we will use need to put some query which we can do by using the Query submodule we imported.

Searching data using query

Deleting and updating data is made simple too by this library.

Updating and deleting data

Summary

There are still lots of module we can play around from this library, such as purge, upsert, caching middleware and much more. At the end of the day, this library is a lightweight and easy library to use. However, I personally will only recommend this library when it comes to simple, quick and small application projects only due to the pretty-decent performance.

--

--