Skip to main content

from commons.database import DatabaseAdapter

commons-lib

This is a common library for dependencies that might be useful on Python Development.

It offers:

  • A thread-safe Database Adapter + File-Based Data Migration executor powered by SQLModel ORM (sqlalchemy) and Pydantic;
  • Local Key-Value Cache database, powered by SQLite;
  • Better logging configuration via commons.logging;
  • Dynamic runtime import (commons.runtime);
  • Local/HTTP Remote Resource representation powered by httpx;
  • Currency support (commons.currencies):
    • Currencies in ISO-4217 format powered by pycountry;
    • Brazilian Pix support;
    • Bitcoin (BTC) and Monero (XMR) support;
    • Live currencies quotation from Wise and cryptocompare.com;
    • Payment QRCode generation for cryptocurrencies and Pix;
  • Support for i18n via Babel (commons.locale):
    • Wraps common features and format methods from Babel;
    • Automatically compile .po files;
    • Extracts translatable strings from source-code;
  • Notification System (powered by apprise):
    • SMTP tool for sending messages (to be replaced);
  • Media support:
    • Media/MIME Types (commons.media.mimetypes);
    • Document Processor;
    • Image Processor (commons.media.images);
    • Audio Processor;
    • Video Processor;
    • Subtitle Processor;

⚠️ This is under active development and might not be ready for production environments.

Testing

coverage run -m unittest && coverage html -d tests/coverage/html

Build

uv build && twine upload dist/*

Usage

This section describe how to use this library.

Database

Database Adapters

To make the life easier when handling with multiple databases, there is a Database Adapter class available at commons.database.DatabaseAdapter.

This class is a Pydantic Model that wraps the logic behind sqlalchemy to allow async connection handling to several database drivers. By default, it creates an adapter for a SQLite In-Memory Database.

To allow asynchronous operations, the adapter is thread-safe.

Creating an Adapter
from commons.database import DatabaseAdapter

DatabaseAdapter()
# 'sqlite:///:memory:?cache=shared'
DatabaseAdapter(scheme="sqlite", database="sqlite.db")
# 'sqlite:///sqlite.db'
DatabaseAdapter(scheme="postgresql", username="postgres", password="1234", host="db.domain.tld", port=5432, database="mydb")
# 'postgresql://postgres:1234@db.domain.tld:5432/mydb'
DatabaseAdapter(scheme="redis", username="username", password="pwd", host="db.domain.tld", port=6379, database="0")
# 'redis://username:pwd@db.domain.tld:6379/0'
Connecting to a database
from commons.database import DatabaseAdapter
with DatabaseAdapter().session() as session:
    # your code
    session.close()

Generic Repository Class

To implement a database repository, you can follow the generic approach described below:

from commons.database import DatabaseAdapter
from typing import Optional
from sqlalchemy import Session

class GenericDatabaseRepository:
    database: DatabaseAdapter
    session: Optional[Session] = None

    def __init__(self, database: DatabaseAdapter = DatabaseAdapter()):
        self.database = database

    def __enter__(self):
        self.session = self.database.session()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.session.close()
        self.session = None
        
    # your repository methods

# Usage
with GenericDatabaseRepository() as db:
    # your code  
    ...

This allows easy handling of the database sessions and data persistence. An example of this approach is the commons.database.Cache class, described on the next section.

Cache Databases

To make a smart use of the SQL power, a Cache class is available at commons.database.Cache, allowing quick storage of binary data in key-value scheme.

By default, the class uses a default database adapter that makes use of an In-Memory SQLite database, but a commons.database.DatabaseAdapter can be specified in the constructor. Be aware that, now, the class is implemented using SQL, so, NoSQL databases are not supported.

Below, an example on how to use it:

from commons.database import Cache, CacheEntry

with Cache() as cache:
    # set an entry
    entry: CacheEntry = cache.set("key", b"value", max_age=3600)

    # Get entry data
    data: bytes = entry.data
    
    # Check if entry is expired
    if entry.expired:
      print("Cache is expired.")
    else:
      print("Cache is not expired.")
    
    # Invalidate an entry
    cache.invalidate("key")

    # Get an entry from a key
    stored_entry: CacheEntry | None = cache.get("key")

Metadata

Release files for commons-library 0.5.3

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

Source distribution (sdist)

Source distribution for commons-library 0.5.3
File Size Uploaded
commons_library-0.5.3.tar.gz 30.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for commons-library 0.5.3
File Interpreter ABI Platform
commons_library-0.5.3-py3-none-any.whl Python 3 none any Details

Total release size: 59.8 kB

Release files / commons_library-0.5.3.tar.gz

Download URL commons_library-0.5.3.tar.gz
Size 30.1 kB
Tags Source
SHA-256 checksum
How to use checksums
eaa837fe4b2adfc7d2b07313619f0f80a1485c5e321e9f5a96761154192f3997
BLAKE2b-256 checksum
How to use checksums
530887269ba89c4904f45ef4786c56bb46c61ffddd0241c3dda827a5f692a70a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.3

Release files / commons_library-0.5.3-py3-none-any.whl

Download URL commons_library-0.5.3-py3-none-any.whl
Size 29.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
efb7965c2b4475ee0c5574794ce85c898f20841c23698eea5fa7e75f193ea83b
BLAKE2b-256 checksum
How to use checksums
ea6d98cb7cae8a1c13ff1bb9d0b0165d189b1751e39eac6d5e32356b8fb4e4c3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.3

Release history Release notifications | RSS feed

This release

0.5.3 This release

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.5.0

2 release files

0.4.9

2 release files

0.4.8

2 release files

0.4.7

2 release files

0.4.6

2 release files

0.4.5

2 release files

0.4.4

2 release files

0.4.3

2 release files

0.4.2

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

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