Introduction to tinyDB

TinyDB is a Python library that offers a simple document oriented (any document represented as dict can be stored in TinyDB) approach to storing and managing data.

TinyDB is simple and easy to use, making it perfect for rapid development and small-scale projects. Check this post for the most popular python web development frameworks to create your next project. However, for larger applications with complex data requirements or demanding concurrency needs, consider using more robust database solutions.

Common TinyDB Methods

Before building a Contact Manager project below, let’s go over the most common TinyDB methods:

First, you need to install TinyDB, and you can do this using pip:

pip install tinydb
from tinydb import TinyDB, Query

# Create a database
# This initializes a TinyDB database and stores the data in 'example_db.json'
db = TinyDB('example_db.json')

# Insert data
# This inserts a document into the database
db.insert({'name': 'John Doe', 'age': 30, 'email': 'john@example.com'})
db.insert({'name': 'Jane Smith', 'age': 25, 'email': 'jane@example.com'})

# Read data
# Fetch all documents from the database
all_docs = db.all()
print("All Documents:", all_docs)

# Querying specific data
User = Query()
john = db.search(User.name == 'John Doe')
print("John's Record:", john)

# Update data
# Update John's age
db.update({'age': 31}, User.name == 'John Doe')

# Verify the update
updated_john = db.search(User.name == 'John Doe')
print("Updated John's Record:", updated_john)

# Remove data
# Remove John's record
db.remove(User.name == 'John Doe')

# Verify the removal
remaining_docs = db.all()
print("Remaining Documents:", remaining_docs)

# Drop the entire database
# This will remove all documents from the database
db.truncate()

# Verify the database is empty
empty_docs = db.all()
print("Documents after truncation:", empty_docs)

Let’s create a basic contact manager app with TinyDB that allows you to add, view, and delete contacts.

Beginner Project

Step 1: Install TinyDB

First, you need to install TinyDB. You can do this using pip:

pip install tinydb

Step 2: Create the Contact Manager App

Create a Python script, for example contact_manager.py, and add the following code:

from tinydb import TinyDB, Query

# Initialize the database
db = TinyDB('contacts.json')

# Function to add a new contact
def add_contact(name, phone, email):
    db.insert({'name': name, 'phone': phone, 'email': email})
    print(f"Added contact: {name}")

# Function to view all contacts
def view_contacts():
    contacts = db.all()
    if contacts:
        for contact in contacts:
            print(f"Name: {contact['name']}, Phone: {contact['phone']}, Email: {contact['email']}")
    else:
        print("No contacts found.")

# Function to delete a contact by name
def delete_contact(name):
    Contact = Query()
    result = db.remove(Contact.name == name)
    if result:
        print(f"Deleted contact: {name}")
    else:
        print(f"No contact found with the name: {name}")

# Menu to interact with the contact manager
def menu():
    while True:
        print("\nContact Manager")
        print("1. Add Contact")
        print("2. View Contacts")
        print("3. Delete Contact")
        print("4. Exit")

        choice = input("Choose an option: ")

        if choice == '1':
            name = input("Enter name: ")
            phone = input("Enter phone: ")
            email = input("Enter email: ")
            add_contact(name, phone, email)
        elif choice == '2':
            view_contacts()
        elif choice == '3':
            name = input("Enter the name of the contact to delete: ")
            delete_contact(name)
        elif choice == '4':
            print("Exiting...")
            break
        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    menu()

Step 3: Run the App

Save the script and run it from your command line:

python contact_manager.py

You should see a menu allowing you to add, view, and delete contacts. Each contact will be stored in a contacts.json file, managed by TinyDB.

Explanation of the Code

  • Initialization: TinyDB('contacts.json') initializes the database and stores data in contacts.json.
  • Functions:
  • add_contact inserts a new contact into the database.
  • view_contacts retrieves and displays all contacts.
  • delete_contact removes a contact by name.
  • Menu: Provides a simple text-based interface to interact with the contact manager.

This app demonstrates how to use TinyDB for basic CRUD (Create, Read, Update, Delete) operations in a simple and straightforward manner.

Video Tutorial

Similar Posts