Skip to main content

Add your description here

Project description

Flash DB

Flash DB is a lightweight async Django ORM alternative built on top of SQLAlchemy. While it is part of the Flash Web Framework, it can be used standalone with frameworks like FastAPI.

Features

  • Asynchronous from the ground up: Built for asyncio.
  • Django-like API: Model.objects manager, lazy QuerySets, and familiar method names.
  • SQLAlchemy's power: Leverage the full power of SQLAlchemy's expression language when needed.
  • Transaction Management: Manages database transactions as a context manager or decorator, with nested savepoint support.
  • Type-safe: Fully type-annotated for a better development experience with tools like MyPy.
  • Simple setup: Easy to integrate with FastAPI and other async frameworks.

Installation

pip install flash_db

Quickstart

1. Initialize the Database

First, initialize the database connection. For a FastAPI application, you should use the lifespan context manager.

# main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from flash_db import init_db, close_db

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Initialize the database
    init_db("sqlite+aiosqlite:///db.sqlite3")
    yield
    # Close the database
    await close_db()

app = FastAPI(lifespan=lifespan)

2. Define Your Models

Create your models by inheriting from flash_db.Model.

# models.py
from sqlalchemy.orm import Mapped, mapped_column
from flash_db import Model, TimestampMixin

class User(Model, TimestampMixin):
    __tablename__ = "users"

    name: Mapped[str]
    email: Mapped[str] = mapped_column(unique=True)

3. Create Records

Use the objects.create() method on the model manager. Operations require an explicit commit.

# usage.py
from flash_db import get_db, atomic
from .models import User

async def create_user():
    async for db in get_db():
        # Option 1: Explicit commit
        user = await User.objects.create(db, name="John Doe", email="john.doe@example.com")
        await db.commit()
        print(f"Created user: {user.name}")

        # Option 2: Atomic block (commits automatically on exit)
        async with atomic(db):
            await User.objects.create(db, name="Jane Doe", email="jane@example.com")

4. Query Data

Use the objects manager to query the database.

Get all records:

async def list_users():
    async for db in get_db():
        users = await User.objects.all().fetch(db)
        for user in users:
            print(user.name)

Filter records:

async def find_user():
    async for db in get_db():
        user = await User.objects.filter(User.email == "john.doe@example.com").first(db)
        if user:
            print(f"Found user: {user.name}")

Get a single record:

async def get_user():
    async for db in get_db():
        try:
            user = await User.objects.get(db, User.name == "John Doe")
            print(f"Got user: {user.name}")
        except User.DoesNotExist:
            print("User not found.")
        except User.MultipleObjectsReturned:
            print("Multiple users found.")

5. Update Records

Update records using the update method.

async def update_user_email():
    async for db in get_db():
        await User.objects.filter(User.name == "John Doe").update(db, email="new.email@example.com")
        await db.commit()

6. Delete Records

Delete records using the delete method.

async def delete_user():
    async for db in get_db():
        await User.objects.filter(User.name == "John Doe").delete(db)
        await db.commit()

Async and Session Management

Flash DB is fully asynchronous, and it requires you to manage the database session explicitly. The get_db function provides an async generator that yields an AsyncSession object. You should use this session for all your database operations.

This explicit approach ensures that the session is correctly handled and closed, which is crucial in an async environment.

Roadmap

Our goal for flash_db is to build a lightweight, yet powerful, async ORM that feels intuitive to Django developers.

  • Transaction Management: Atomic transactions via decorator or context manager.
  • get_or_create() / update_or_create(): Streamline create/update patterns.
  • Model Validation Hooks: clean() methods for data validation.
  • Advanced Querying: exclude(), distinct(), only(), defer(), and more.
  • Complex Lookups: Q Objects and F Expressions (Beta), Prefetching.
  • Performance: bulk_create, bulk_update (Beta).
  • Signals: pre_save, post_save, pre_delete, post_delete.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flash_db-0.3.2a1.tar.gz (51.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flash_db-0.3.2a1-py3-none-any.whl (30.7 kB view details)

Uploaded Python 3

File details

Details for the file flash_db-0.3.2a1.tar.gz.

File metadata

  • Download URL: flash_db-0.3.2a1.tar.gz
  • Upload date:
  • Size: 51.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.14

File hashes

Hashes for flash_db-0.3.2a1.tar.gz
Algorithm Hash digest
SHA256 ad176a75147012a91b5dd33176e57e5e55d58ea9851bc931df2beba7964fee44
MD5 7d5871e0af5d6fe06137e5370ce47d10
BLAKE2b-256 02e9e21fd57faf4ef0468950f81482e60d4a4b4cb96ad43e906e3f4983b4bfc0

See more details on using hashes here.

File details

Details for the file flash_db-0.3.2a1-py3-none-any.whl.

File metadata

  • Download URL: flash_db-0.3.2a1-py3-none-any.whl
  • Upload date:
  • Size: 30.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.14

File hashes

Hashes for flash_db-0.3.2a1-py3-none-any.whl
Algorithm Hash digest
SHA256 b1286db57e6b49172b6f95771851dfac77c8f9f3a6e1a03bc67e2afae247e50e
MD5 0a11dfbae9a99e3028a565d627ffad54
BLAKE2b-256 7864c49810f00a2a8b3f0ca44760c7eb86ab61914a8c2c291a38858bbf763109

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page