Skip to main content

CerbeRedis

https://raw.githubusercontent.com/adamlwgriffiths/cerberedis/master/images/cerberedis.png

De/serialise Cerberus data to a Redis database.

Installation

$ pip install cerberedis

Example

A basic example:

from cerberus import Validator, TypeDefinition
from redis import Redis
from cerberedis import CerbeRedis

schema = {
    'name': {'type': 'string', 'required': True},
    'email': {'type': 'string', 'required': True},
}
data = {'name': 'Bob', 'email': 'bob@example.com'}

# connect to our redis server
r = Redis()
db = CerbeRedis(r)

# save the schema under the type name 'User'
# with a document id of 1
model_name, id = 'User', 1
db.save(model_name, schema, id, document)

# print the key the model is stored under

print(db.key(model_name, id))

# reload the document
loaded_document = db.load(model_name, schema, id)

A full featured example, including custom types:

from ipaddress import ip_address, IPv4Address, IPv6Address
from datetime import date, datetime
from cerberus import Validator, TypeDefinition
from redis import Redis
# alternatively use redis_mock (https://github.com/adamlwgriffiths/redis-mock)
# from redis_mock import Redis
from cerberedis import CerbeRedis

# Add custom types to both Cerberus
# https://docs.python-cerberus.org/en/stable/customize.html
Validator.types_mapping.update({
    'ipaddress': TypeDefinition('ipaddress', (IPv4Address, IPv6Address), ()),
    'ipv4address': TypeDefinition('ipv4address', (IPv4Address,), ()),
    'ipv6address': TypeDefinition('ipv6address', (IPv6Address,), ()),
})
# Provide CerbeRedis with information on how to handle these new Cerberus types
CerbeRedis.rules.update({
    # dictionary of: <cerberus type name>: [to redis function, from redis function]
    'ipaddress': [lambda x: str(x), lambda x: ip_address(x.decode('utf-8'))],
    'ipv4address': [lambda x: str(x), lambda x: IPv4Address(x.decode('utf-8'))],
    'ipv6address': [lambda x: str(x), lambda x: IPv6Address(x.decode('utf-8'))],
})

# An example Cerberus schema that uses all the built-in Cerberus types
# and the custom ones we defined above
schema = {
    'boolean': {'type': 'boolean', 'required': True},
    'binary': {'type': 'binary', 'required': True},
    'date': {'type': 'date', 'required': True},
    'datetime': {'type': 'datetime', 'required': True},
    'float': {'type': 'float', 'required': True},
    'integer': {'type': 'integer', 'required': True},
    'number': {'type': 'number', 'required': True},
    'string': {'type': 'string', 'required': True},
    'dict': {'type': 'dict', 'schema': {
        'dict_a': {'type': 'string', 'required': True},
        'dict_b': {'type': 'integer', 'required': True},
    }},
    'list': {'type': 'list', 'schema': {'type': 'integer'}},
    'set': {'type': 'set', 'schema': {'type': 'string'}},
    'ipv4address': {'type': 'ipv4address', 'required': True},
}

data = {
    'boolean': True,
    'binary': b'123',
    'date': date.today(),
    'datetime': datetime.now(),
    'float': 1.23,
    'integer': 456,
    'number': 789.0,
    'string': 'abcdefg',
    'dict': {
        'dict_a': 'dict_a_value',
        'dict_b': 9999,
    },
    'list': [1,2,3,4,5],
    'set': {'a', 'b', 'c'},
    'ipv4address': IPv4Address('127.0.0.1'),
}

# Use cerberus to validate and normalise the data
validator = Validator(schema)
document = validator.normalized(data)
if not document:
    raise ValueError(str(validator.errors))

# connect to our redis server
r = Redis()
db = CerbeRedis(r)
model_name, id = 'TestModel', 1
db.save(model_name, schema, id, document)

# reload the document
loaded_document = db.load(model_name, schema, id)

# verify the data is laid out how we expect
assert document == loaded_document

Supported Types

All existing Cerberus Types:

  • boolean

  • binary

  • date

  • datetime

  • float

  • integer

  • number

  • string

  • dict

  • list

  • set

Limitations

  • Containers cannot be nested. Ie. lists and sets cannot contain lists, sets, or dicts.

Future Work

  • Use a Redis Pipeline for the load function

Changelog

1.0.5

  • Return None rather than empty containers. Permits us to know if the value actually exists.

1.0.4

  • Fix image link

1.0.3

  • Fix handling of None values for non-required fields

1.0.2

  • Expose key function

1.0.1

  • Version bump due to PyPi version pedantry

1.0.0

  • Initial release

BSD 2-Clause License

Copyright (c) 2021, Adam Griffiths All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Metadata

Release files for cerberedis 1.0.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cerberedis 1.0.5
File Size Uploaded Provenance
cerberedis-1.0.5.tar.gz 5.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for cerberedis 1.0.5
File Interpreter ABI Platform
cerberedis-1.0.5-py3-none-any.whl Python 3 none any Details

Total release size: 12.4 kB

Release files / cerberedis-1.0.5.tar.gz

Download URL cerberedis-1.0.5.tar.gz
Size 5.9 kB
Tags Source
SHA-256 checksum
How to use checksums
680ef48565d684cc8eb14291075dbf029020ded2da86429588cb7ba1ac39fb53
BLAKE2b-256 checksum
How to use checksums
709412cc52eb3789c261de2e9950510c47f7df9fe64e99a05dfd9fdb7c970f88
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.6.1 requests/2.25.1 setuptools/51.0.0 requests-toolbelt/0.9.1 tqdm/4.56.0 CPython/3.8.5

Release files / cerberedis-1.0.5-py3-none-any.whl

Download URL cerberedis-1.0.5-py3-none-any.whl
Size 6.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9ceae33afbbaf5d3391edffc4fcb1729f6eba0f9fcc7234cdf819cef15c5cb32
BLAKE2b-256 checksum
How to use checksums
7e0da32cbd32d3e6e667d9313c392688f9d7eb9fccb44ac2f398575a9acc9be7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.3.0 pkginfo/1.6.1 requests/2.25.1 setuptools/51.0.0 requests-toolbelt/0.9.1 tqdm/4.56.0 CPython/3.8.5

Security for cerberedis 1.0.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page