Yes, we are going to study one of the easiest databases that we can use. It's a JSON format database.
We will be using TinyDB and making a sort of Todo application which we will further extend into an API and use it for any application that we want. If you did not check my previous article on how we can make any API within 10 minutes you can check it out and see how easy it is to make APIs
Ok, now we will start off with the article for TinyDB and how we will use it.
Basic Functionalities of the Application
- Add any field in the Database
- Delete any field in the Database
- Query the Database
- Update the Database
These are all functionalities required for any Database and we require the same for the Todo application
So starting off with creating a database
Step 1
from tinydb import TinyDB, Query
db = TinyDB('db.json')
In the above code, we have imported both the tiny DB as well as the Query and defined a database. For installing tinydb on your system. we can simply use:-
pip install tinydb
And you will be up and running for writing your own databases. Now we move onto the next part ie. Inserting rows in the Database
Step 2
db.insert({'task': 'Go on the walk', 'time': '7:30am', 'id': 1})
db.insert({'task': 'Do Homework', 'time': '10:30am', 'id': 2})
If you want to see the who database you use db.all()
and will get all the entries in the database
Step 3
Now Let's say we want a certain row as the output then we have to query the database. Now we learn to query the database
Task = Query()
db.search(Task.task == 'Do Homework')
#{'task': 'Do Homework', 'time': '10:30am'}
Step 4
Now let's say that you want to update any field of a row. We can do it as...
db.update({'time': "10:40am"}, Task.task == 'Do Homework')
The above will change the time from 10:30 am to 10:40 am.
Step 4
Deleting any data from the database. Let's delete all the tasks which have id == 2
db.remove(Task.id == 2)
In the db.remove(condition) your condition can be anything that you want.
Now let's say you want to delete the whole database.
db.truncate()
You can refer to the above if you want to use the database.
That's it for this article. What you can do is make any small database and play around with it. Till then in the next article, we will make an API of this and try to use it for our use.
Follow me on Github:-
Happy Coding
Sarvesh Dubey