How to Get Started with PysonDB: A Beginner‘s Guide

As a full-stack developer, I‘m always on the lookout for tools that make my job easier. When it comes to databases, I prefer lightweight solutions that are fast, simple to use, and don‘t require a lot of setup or maintenance. That‘s why I‘m excited to share PysonDB with you.

PysonDB is a JSON-based database for Python that stores data in memory for lightning-fast performance. It has an intuitive API for basic CRUD (Create, Read, Update, Delete) operations and requires no external server or service to run. This makes it an excellent choice for small to medium-sized Python projects, prototypes, and offline-first applications.

In this beginner‘s guide, I‘ll walk you through how to get started with PysonDB. We‘ll cover installation, core concepts, querying data, and integrating PysonDB into a real Python app. By the end, you‘ll have a solid foundation for using this powerful database in your own projects. Let‘s dive in!

Installing PysonDB

The first step is installing PysonDB. It‘s available as a Python package on PyPI, so you can install it with pip:

pip install pysondb

If you‘re using a virtual environment (which I highly recommend), make sure it‘s activated before running the above command. You can verify PysonDB is installed by importing it in a Python shell:

import pysondb

If no errors appear, you‘re good to go! PysonDB is compatible with Python 3.6+ on Windows, macOS, and Linux.

Creating a Database

With PysonDB installed, let‘s create our first database. PysonDB stores data as collections of JSON documents. A database is simply a directory containing one or more JSON files.

To create a new database, use the pysondb.db() function and pass it the path where you want the data stored:

from pysondb import db

todos_db = db.getDb("data/todos.json")

This code creates a todos_db database that will be saved in the data/todos.json file. If the file doesn‘t exist, PysonDB will create it automatically.

Inserting Documents

Now that we have a database, let‘s add some data. In PysonDB, data is organized as JSON documents. Each document is a dictionary with key-value pairs.

To insert a document into the database, use the add() method:

todo = {
    "title": "Buy groceries",
    "completed": False,
    "priority": "high"
}

todo_id = todos_db.add(todo)
print(f"Added todo with ID: {todo_id}")

This code creates a to-do item and adds it to the todos_db database. The add() method returns the unique identifier (ID) assigned to the new document.

You can insert multiple documents by passing a list to add():

todos = [
    {"title": "Clean the house", "completed": False, "priority": "medium"},
    {"title": "Pay bills", "completed": True, "priority": "high"},
    {"title": "Walk the dog", "completed": False, "priority": "low"}
]

todo_ids = todos_db.add(todos)
print(f"Added {len(todo_ids)} todos")

PysonDB will add each document in the list and return a list of their IDs.

Querying Documents

Retrieving data from PysonDB is done by querying the database using the find() method. You can get all documents by calling find() with no arguments:

all_todos = todos_db.find()

for todo in all_todos:
    print(todo)

This prints every to-do document in the database. To filter the results, pass a dictionary of field names and values to match:

completed_todos = todos_db.find(completed=True)

high_priority_todos = todos_db.find(priority="high")

PysonDB supports complex queries using special operators like $gt (greater than), $lt (less than), $in (match any in a list), and more. Refer to the PysonDB documentation for details.

Updating Documents

To modify existing documents in the database, use the update() method. It takes two arguments:

  1. A dictionary of fields and values to match (like find())
  2. A dictionary of fields and values to update

For example, here‘s how to mark a to-do as completed by its ID:

todos_db.update({"id": todo_id}, {"completed": True})

update() modifies all matching documents by default. To update only the first match, set the multiple parameter to False:

todos_db.update({"priority": "high"}, {"priority": "urgent"}, multiple=False)

Deleting Documents

To remove documents from the database, use the delete() method with a query dictionary:

todos_db.delete(completed=True)

This deletes all to-do items that are marked completed. Like update(), you can set multiple=False to delete only the first match.

To delete documents by their IDs, use the deleteById() method:

todos_db.deleteById(todo_id)

Using PysonDB in a Python App

Let‘s put everything together and build a simple command-line to-do app with PysonDB. Here‘s the code:

from pysondb import db

todos_db = db.getDb("data/todos.json")

def add_todo():
    title = input("Enter a title: ")
    priority = input("Enter a priority (low/medium/high): ")
    todo = {"title": title, "completed": False, "priority": priority}
    todo_id = todos_db.add(todo)
    print(f"Added todo with ID: {todo_id}")

def list_todos():
    todos = todos_db.find()
    print(f"Found {len(todos)} todos:")
    for todo in todos:
        print(f"({todo[‘id‘]}) [{todo[‘priority‘]}] {todo[‘title‘]} - {‘✓‘ if todo[‘completed‘] else ‘ ‘}")

def complete_todo():
    todo_id = input("Enter a todo ID to mark completed: ")
    todos_db.update({"id": todo_id}, {"completed": True})
    print(f"Marked todo {todo_id} completed")

def delete_todo():
    todo_id = input("Enter a todo ID to delete: ")
    todos_db.deleteById(todo_id)
    print(f"Deleted todo {todo_id}")

while True:
    print("\nTo-Do App")
    print("1. Add a todo")
    print("2. List todos")
    print("3. Mark todo completed")
    print("4. Delete a todo")
    print("5. Quit")

    choice = input("Enter a choice (1-5): ")

    if choice == "1":
        add_todo()
    elif choice == "2":
        list_todos()
    elif choice == "3":
        complete_todo()
    elif choice == "4":
        delete_todo()
    elif choice == "5":
        break
    else:
        print("Invalid choice. Try again.")

This app provides a menu of options to manage to-do items using PysonDB. The user can add new to-dos, list all to-dos, mark a to-do completed by its ID, delete a to-do by ID, and quit the program.

PysonDB makes it easy to persist the application data without needing an external database server. The data is loaded into memory when the app starts for efficient querying and automatically saved to disk after each operation.

Recap & Next Steps

In this guide, you learned how to:

  • Install PysonDB
  • Create a new JSON database
  • Insert, query, update, and delete documents
  • Integrate PysonDB into a Python application

PysonDB has more features we didn‘t cover here, including indexing, schema validation, and data encryption. It‘s also cross-platform and can be used in web, desktop, and mobile apps.

I encourage you to explore the PysonDB documentation and experiment with it in your own projects. Its simplicity and performance make it a great fit for many Python use cases.

Some ideas to try next:

  • Build a web-based to-do app with PysonDB and a microframework like Flask
  • Prototype a data analysis tool using PysonDB and Jupyter notebooks
  • Create a desktop app with PysonDB and a GUI toolkit like PyQt

The possibilities are endless! PysonDB is a hidden gem in the Python ecosystem that deserves more attention. I hope this guide inspired you to give it a try.

Further Reading:

Happy coding!

Similar Posts