Skip to main content

Common dependencies for Python 3 software development and data management.

Project description

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")

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

commons_library-0.5.1.tar.gz (29.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

commons_library-0.5.1-py3-none-any.whl (29.0 kB view details)

Uploaded Python 3

File details

Details for the file commons_library-0.5.1.tar.gz.

File metadata

  • Download URL: commons_library-0.5.1.tar.gz
  • Upload date:
  • Size: 29.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3

File hashes

Hashes for commons_library-0.5.1.tar.gz
Algorithm Hash digest
SHA256 66c15aeb906cbcf07c471999a4da2e8a5f65876993209db1bc0f4ead826d1ee2
MD5 abdc9c30a7c62a2733b25924407209fa
BLAKE2b-256 297f8ef9c3657c603f87b41f275600d3f3e57411748a52d7cbb566e044e885e1

See more details on using hashes here.

File details

Details for the file commons_library-0.5.1-py3-none-any.whl.

File metadata

File hashes

Hashes for commons_library-0.5.1-py3-none-any.whl
Algorithm Hash digest
SHA256 865f357d058618416730b94a8df480d2e5ccb600ef16ec6cffaa56e087e13ce2
MD5 6c7d61c2cb2bff471228705b4bc74e84
BLAKE2b-256 74cd134bac63ac77f36db95492fd4f59cd5c73c9b2a38a0531f47c9b4f453649

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