Skip to main content

Repository Patterns for Python

Project description

Red Bird: Repository Patterns for Python

Generic database implemetation for SQL, MongoDB and in-memory lists


Pypi version build codecov Documentation Status PyPI pyversions

Repository Pattern is a technique in which database layer is separated from the application code. In other words, repository pattern provide generic ways to communicate with the database that are genericnot database specific or even data store specific. Ultimately all data stores are just for retrieving, updating, setting and deleting data.

In practice, repository pattern is an abstraction that provide same syntax regardless of the data store is SQL database, MongoDB database or even just a Python list in RAM.

Pros in repository pattern:

  • More readable code
    • Every database connection follow the same pattern.
  • More maintainable code
    • Database migrations are easy.
    • Unit testing requires no separate database for testing.
  • More rapid development
    • Use Python lists until you get your database set up.

Cons in repository pattern:

  • Poor at optimization
  • Hides the actual operations

Examples

First, we create a simple repo:

from redbird.repos import MemoryRepo
repo = MemoryRepo()

Adding/creating items:

repo.add({"name": "Anna", "nationality": "British"})

Reading items:

repo.filter_by(name="Anna").all()

Updating items:

repo.filter_by(name="Anna").update(nationality="Finnish")

Deleting items:

repo.filter_by(name="Anna").delete()

Creating Repository

In-memory repository:

from redbird.repos import MemoryRepo
repo = MemoryRepo()

SQL repository:

from sqlalchemy import create_engine
from redbird.repos import SQLRepo
repo = SQLRepo(table="mytable", engine=create_engine("sqlite://"))

or using ORM:

from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, String, Integer

Base = declarative_base()
class SQLModel(SQLBase):
    __tablename__ = 'pytest'
    id = Column(String, primary_key=True)
    name = Column(String)
    age = Column(Integer)

repo = SQLRepo(model_orm=SQLModel, engine=create_engine("sqlite://"))

Author

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

redbird-0.2.0.tar.gz (141.3 kB view hashes)

Uploaded Source

Built Distribution

redbird-0.2.0-py3-none-any.whl (45.6 kB view hashes)

Uploaded Python 3

Supported by

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