Skip to main content

Use your pydantic models as an ORM, storing data in Redis.

Project description

pydantic-aioredis

Pydantic-aioredis is designed to provide an efficient way of integrating Redis databases with Python-based applications. Built on top of Pydantic, pydantic-aioredis allows you to define data models and validate input data before it is stored in Redis. Data is validated before storing and after retrieval from Redis. The library also provides an easy-to-use API for querying, updating, and deleting data stored in Redis.

Inspired by pydantic-redis by Martin Ahindura

Latest Commit GitHub release (latest by date)
GitHub Workflow Status Test and Lint (branch) Contributors
Package version

Main Dependencies

Getting Started

Examples

Examples are in the examples/ directory of this repo.

Installation

Install the package

pip install pydantic-aioredis

Quick Usage

Import the Store, the RedisConfig and the Model classes and use accordingly

import asyncio
from datetime import date
from pydantic_aioredis import RedisConfig, Model, Store

# Create models as you would create pydantic models i.e. using typings
class Book(Model):
    _primary_key_field: str = 'title'
    title: str
    author: str
    published_on: date
    in_stock: bool = True

# Do note that there is no concept of relationships here
class Library(Model):
    # the _primary_key_field is mandatory
    _primary_key_field: str = 'name'
    name: str
    address: str

# Create the store and register your models
store = Store(name='some_name', redis_config=RedisConfig(db=5, host='localhost', port=6379), life_span_in_seconds=3600)
store.register_model(Book)
store.register_model(Library)

# Sample books. You can create as many as you wish anywhere in the code
books = [
    Book(title="Oliver Twist", author='Charles Dickens', published_on=date(year=1215, month=4, day=4),
        in_stock=False),
    Book(title="Great Expectations", author='Charles Dickens', published_on=date(year=1220, month=4, day=4)),
    Book(title="Jane Eyre", author='Charles Dickens', published_on=date(year=1225, month=6, day=4), in_stock=False),
    Book(title="Wuthering Heights", author='Jane Austen', published_on=date(year=1600, month=4, day=4)),
]
# Some library objects
libraries = [
    Library(name="The Grand Library", address="Kinogozi, Hoima, Uganda"),
    Library(name="Christian Library", address="Buhimba, Hoima, Uganda")
]

async def work_with_orm():
  # Insert them into redis
  await Book.insert(books)
  await Library.insert(libraries)

  # Select all books to view them. A list of Model instances will be returned
  all_books = await Book.select()
  print(all_books) # Will print [Book(title="Oliver Twist", author="Charles Dickens", published_on=date(year=1215, month=4, day=4), in_stock=False), Book(...]

  # Or select some of the books
  some_books = await Book.select(ids=["Oliver Twist", "Jane Eyre"])
  print(some_books) # Will return only those two books

  # Or select some of the columns. THIS RETURNS DICTIONARIES not MODEL Instances
  # The Dictionaries have values in string form so you might need to do some extra work
  books_with_few_fields = await Book.select(columns=["author", "in_stock"])
  print(books_with_few_fields) # Will print [{"author": "'Charles Dickens", "in_stock": "True"},...]


  this_book = Book(title="Moby Dick", author='Herman Melvill', published_on=date(year=1851, month=10, day=17))
  await Book.insert(this_book)
  # oops, there was a typo. Fix it
  # Update is an async context manager and will update redis with all changes in one operations
  async with this_book.update():
    this_book.author = "Herman Melville"
    this_book.published_on=date(year=1851, month=10, day=18)
  this_book_from_redis = await Book.select(ids=["Moby Dick"])
  assert this_book_from_redis[0].author == "Herman Melville"
  assert this_book_from_redis[0].published_on == date(year=1851, month=10, day=18)

  # Delete any number of items
  await Library.delete(ids=["The Grand Library"])

# Now run these updates
loop = asyncio.get_event_loop()
loop.run_until_complete(work_with_orm())

Custom Fields in Model

Field Name Required Default Description
_primary_key_field Yes None The field of your model that is the primary key
_redis_prefix No None If set, will be added to the beginning of the keys we store in redis
_redis_separator No : Defaults to :, used to separate prefix, table_name, and primary_key
_table_name No cls.name Defaults to the model's name, can set a custom name in redis
_auto_save No False Defaults to false. If true, will save to redis on instantiation
_auto_sync No False Defaults to false. If true, will save to redis on attr update

License

Licensed under the MIT License

Contributing

Contributions are very welcome. To learn more, see the Contributor Guide

Contributors

Thanks go to these wonderful people (emoji key):

Andrew
Andrew

💻 📖
Martin Ahindura
Martin Ahindura

💻 🤔
david-wahlstedt
david-wahlstedt

⚠️ 📖 👀
Daniel Wallace
Daniel Wallace

⚠️
Paco Nathan
Paco Nathan

💡
Andreas Brodersen
Andreas Brodersen

📖
kraczak
kraczak

📖
CharlieJiangXXX
CharlieJiangXXX

💻

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

pydantic_aioredis-1.4.0.tar.gz (17.4 kB view details)

Uploaded Source

Built Distribution

pydantic_aioredis-1.4.0-py3-none-any.whl (17.4 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_aioredis-1.4.0.tar.gz.

File metadata

  • Download URL: pydantic_aioredis-1.4.0.tar.gz
  • Upload date:
  • Size: 17.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.0.0 CPython/3.12.3

File hashes

Hashes for pydantic_aioredis-1.4.0.tar.gz
Algorithm Hash digest
SHA256 bca6d1e908b75e9ac9535cac051ceaf386d4128559ae66e94c49cf4d19e96057
MD5 889ee224ac9e3b20387136ca56a3a51b
BLAKE2b-256 b8b489463b3f2eac5fb66a2921866fcf6eb9c98b5bcdf939d957a10270fe1be2

See more details on using hashes here.

File details

Details for the file pydantic_aioredis-1.4.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_aioredis-1.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4f45597eda6c5e217714c0f0bf16260e1baba0bd14be89c63cdefa4031078114
MD5 e764c822961f936776fc8278a26d8163
BLAKE2b-256 5c7448ea1b35147fd180fd42987ad97955211e1e70572abdb36de6e18487ac8d

See more details on using hashes here.

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