Skip to main content

CRUD tools for working with database via SQLAlchemy.

Project description

DB-First

CRUD tools for working with database via SQLAlchemy.

Features

  • CreateMixin, ReadMixin, UpdateMixin, DeleteMixin for CRUD operation for database.
  • ReadMixin support paginated data from database.
  • StatementMaker class for create query 'per-one-model'.
  • Marshmallow (https://github.com/marshmallow-code/marshmallow) schemas for serialization input data.
  • Marshmallow schemas for deserialization SQLAlchemy result object to dict.

Installation

Recommended using the latest version of Python. DB-First supports Python 3.9 and newer.

Install and update using pip:

$ pip install -U db_first

Examples

Full example

from db_first import BaseCRUD
from db_first.base_model import ModelMixin
from db_first.decorators import Validation
from db_first.mixins import CreateMixin
from db_first.mixins import DeleteMixin
from db_first.mixins import ReadMixin
from db_first.mixins import UpdateMixin
from marshmallow import fields
from marshmallow import Schema
from sqlalchemy import create_engine
from sqlalchemy import Result
from sqlalchemy.exc import NoResultFound
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import Session

engine = create_engine('sqlite://', echo=True, future=True)
session = Session(engine)
Base = declarative_base()


class Items(ModelMixin, Base):
    __tablename__ = 'items'
    data: Mapped[str] = mapped_column(comment='Data of item.')


Base.metadata.create_all(engine)


class IdSchema(Schema):
    id = fields.UUID()


class SchemaOfCreate(Schema):
    data = fields.String()


class SchemaOfUpdate(IdSchema, SchemaOfCreate):
    """Update item schema."""


class OutputSchema(SchemaOfUpdate):
    created_at = fields.DateTime()


class ItemController(CreateMixin, ReadMixin, UpdateMixin, DeleteMixin, BaseCRUD):
    class Meta:
        session = session
        model = Items
        sortable = ['created_at']

    @Validation.input(SchemaOfCreate)
    @Validation.output(OutputSchema, serialize=True)
    def create(self, **data) -> Result:
        return super().create_object(**data)

    @Validation.input(IdSchema, keys=['id'])
    @Validation.output(OutputSchema, serialize=True)
    def read(self, **data) -> Result:
        return super().read_object(data['id'])

    @Validation.input(SchemaOfUpdate)
    @Validation.output(OutputSchema, serialize=True)
    def update(self, **data) -> Result:
        return super().update_object(**data)

    @Validation.input(IdSchema, keys=['id'])
    def delete(self, **data) -> None:
        super().delete_object(**data)


if __name__ == '__main__':
    item_controller = ItemController()

    new_item = item_controller.create(data='first')
    print('Item as dict:', new_item)

    item = item_controller.read(id=new_item['id'])
    print('Item as dict:', item)

    updated_item = item_controller.update(id=new_item['id'], data='updated_first')
    print('Item as dict:', updated_item)

    item_controller.delete(id=new_item['id'])
    try:
        item = item_controller.read(id=new_item['id'])
    except NoResultFound:
        print('Item deleted:', item)

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

db_first-4.0.0.tar.gz (12.7 kB view details)

Uploaded Source

Built Distribution

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

db_first-4.0.0-py3-none-any.whl (10.5 kB view details)

Uploaded Python 3

File details

Details for the file db_first-4.0.0.tar.gz.

File metadata

  • Download URL: db_first-4.0.0.tar.gz
  • Upload date:
  • Size: 12.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for db_first-4.0.0.tar.gz
Algorithm Hash digest
SHA256 ecc6a867bda9e833fc1323ba40fec5e64a4cd21b7fd618560712c6b659742b97
MD5 d228b184b122fae2bd36de035858f243
BLAKE2b-256 66b69cdb5cad33b36699bc5263386234efef42b2e23dd26f6375cabb8ccd973d

See more details on using hashes here.

File details

Details for the file db_first-4.0.0-py3-none-any.whl.

File metadata

  • Download URL: db_first-4.0.0-py3-none-any.whl
  • Upload date:
  • Size: 10.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.11

File hashes

Hashes for db_first-4.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dd04d9f2b4b92ef0d8ee876b44fb38d0151e78451e6b8cfac554e4585bd22756
MD5 317a8e5136f563cd3b8244fc1bf63211
BLAKE2b-256 112c897155eebbe8e083f81ae42e79ab38c979eac0cb87df3be7a64109e2ceea

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