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.
  • Bulk methods for CreateMixin, ReadMixin, UpdateMixin, DeleteMixin.
  • ReadMixin support paginated data from database.
  • StatementMaker class for create query 'per-one-model'.
  • Decorators Validation for validation and serialize/deserialize arguments, parameters and return data for function and methods.
  • Marshmallow (https://github.com/marshmallow-code/marshmallow) schemas for serialization input data.
  • Marshmallow schemas for deserialization SQLAlchemy result object to dict.
  • Datetime with UTC timezone validation in BaseSchema.

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.3.0.tar.gz (14.1 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.3.0-py3-none-any.whl (11.4 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for db_first-4.3.0.tar.gz
Algorithm Hash digest
SHA256 6a12b88d198a4fc24a18b0bd6ec390e8bf9dd2a27d5c11834c57ca9558d47442
MD5 619e4cf98d79150a453323509c9f6b6d
BLAKE2b-256 4ee535a15fd3e32172e6fb8f98e0e367b377f29a3c06e5a5ec3a16da0f311344

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for db_first-4.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 29c33aaec08c6da2f1ee5835b58b94d763ba3673537b754a834db72bd8a9decf
MD5 fde17402134fd12d022c55556e8a92b5
BLAKE2b-256 4445f2e3a908137feb7d5acc3ff5862c35dd1a53e8238f0980ff059a0021ebd2

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