Rick
Python plumbing library for building microframework-based applications.
Rick provides essential building blocks and utilities for constructing robust, maintainable Python applications without imposing architectural constraints. It's lightweight, modular, and battle-tested.
Documentation
Documentation is available at https://oddbit-project.github.io/rick/
Features
Core Components
- Dependency Injection - Thread-safe service container with singleton and factory patterns
- Service Registry - Thread-safe dynamic class registration and retrieval
- Container Classes - Immutable and mutable data containers for type-safe configuration
Validation & Forms
- 30+ Validators - Email, IP, UUID, hash, string, numeric, and more
- Form Processing - Request validation with nested records and fieldsets
- Custom Validation - Easy-to-define custom validation functions
- Input Filters - Transform and sanitize input data
Serialization
- JSON Serializer - Extended JSON encoding with support for datetime, Decimal, UUID, dataclasses
- MessagePack Serializer - Binary serialization 30-50% smaller and 2-4x faster than JSON
- Type Preservation - Full bidirectional encoding/decoding with custom object support
Configuration Management
- EnvironmentConfig - Load configuration from environment variables with automatic type conversion
- File-Based Config - Support for JSON, TOML, and hybrid configurations
- Validation - Built-in validation functions for configuration correctness
- StrOrFile - Load sensitive values from files for enhanced security
Resource Management
- Redis Cache - Full-featured Redis caching with pickle, JSON, or MessagePack serialization
- Encrypted Cache - CryptRedisCache with Fernet256 encryption for sensitive data
- Stream Processing - MultiPartReader for multipart/form-data with seek support
- Console Output - ANSI colored terminal output with 16 colors and text attributes
Security & Cryptography
- Fernet256 - 256-bit encryption for data protection
- BCrypt - Secure password hashing
- Encrypted Caching - Built-in support for encrypting cached sensitive data
- Hash Utilities - SHA1, SHA256, SHA512 implementations
Additional Features
- Event System - Event manager for dispatching and handling events
- Mixins - Injectable, Runnable, and Translator mixins
- Console Utilities - AnsiColor and ConsoleWriter for beautiful CLI applications
Installation
pip install rick
For TOML configuration support (Python < 3.11):
pip install rick tomli
Quick Start
Dependency Injection
from rick.base import Di
# Create DI container
di = Di()
# Register singleton
config_instance = {'api_url': 'https://api.example.com'}
di.add('config', config_instance)
# Register factory with lazy loading
def create_logger(di_instance):
return {'name': 'app_logger'}
di.add('logger', create_logger)
# Retrieve services
config = di.get('config')
logger = di.get('logger') # Calls create_logger(di)
Form Validation
from rick.form import RequestRecord
class RegistrationForm(RequestRecord):
def __init__(self):
super().__init__()
self.field('username', validators='required|alphanum|minlen:3')
self.field('email', validators='required|email')
self.field('password', validators='required|minlen:8')
self.field('age', validators='required|int|between:18,120')
# Example usage
request_data = {
'username': 'johndoe',
'email': 'john@example.com',
'password': 'securepass123',
'age': 25
}
form = RegistrationForm()
if form.is_valid(request_data):
user_data = form.get_data()
else:
errors = form.get_errors()
Configuration Management
from rick.resource.config import EnvironmentConfig, StrOrFile
class AppConfig(EnvironmentConfig):
DB_HOST = 'localhost'
DB_PORT = 5432
DB_PASSWORD = StrOrFile(None) # Load from file
DEBUG = False
MAX_WORKERS = 4
def validate_database(self, data: dict):
if not data.get('db_host'):
raise ValueError("Database host is required")
# Environment variables override defaults
config = AppConfig().build()
print(f"Database: {config['db_host']}:{config['db_port']}")
print(f"Debug mode: {config['debug']}")
Redis Caching
from rick.resource.redis import RedisCache, CryptRedisCache
from rick.serializer.msgpack import msgpack
# Example data
user_data = {'username': 'john_doe', 'email': 'john@example.com'}
# Standard cache with MessagePack
cache = RedisCache(
host='localhost',
serializer=msgpack.packb,
deserializer=msgpack.unpackb,
prefix='myapp:'
)
cache.set('user:123', user_data, ttl=3600)
user = cache.get('user:123')
# Encrypted cache for sensitive data
secure_cache = CryptRedisCache(
key='0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
host='localhost'
)
secure_cache.set('api_token', {'token': 'secret123'})
token = secure_cache.get('api_token')
Serialization
from rick.serializer.json.json import ExtendedJsonEncoder, CamelCaseJsonEncoder
from rick.serializer.msgpack import msgpack
import json
from datetime import datetime
from decimal import Decimal
# JSON serialization
data = {
'timestamp': datetime.now(),
'amount': Decimal('123.45'),
'status': 'active'
}
# Standard JSON
json_str = json.dumps(data, cls=ExtendedJsonEncoder)
# CamelCase for JavaScript compatibility
json_str = json.dumps(data, cls=CamelCaseJsonEncoder)
# MessagePack - faster and smaller
packed = msgpack.packb(data)
restored = msgpack.unpackb(packed) # Full type preservation
Console Output
from rick.resource.console import ConsoleWriter, AnsiColor
# High-level semantic output
console = ConsoleWriter()
console.header('Application Startup')
console.success('Database connected')
console.warn('Cache disabled')
console.error('Plugin failed to load')
# Low-level color formatting
color = AnsiColor()
print(color.red('Error:', attr='bold') + ' Operation failed')
print(color.green('Success', 'white', ['bold', 'underline']))
Use Cases
Rick is ideal for:
- Custom Frameworks - Build domain-specific frameworks with Rick's components
- Microservices - Lightweight utilities for microservice architecture
- CLI Applications - Console output, configuration, and validation
- Background Workers - Job processing with caching and configuration
- API Servers - Request validation, caching, and serialization
- Data Processing - Validation, transformation, and serialization pipelines
Architecture
Rick follows a modular architecture where each component is independent:
rick/
├── base/ # DI, Registry, Containers
├── form/ # Forms and RequestRecord
├── validator/ # 30+ validation rules
├── filter/ # Input filters
├── serializer/ # JSON and MessagePack
├── resource/ # External resources
│ ├── config/ # Configuration loaders
│ ├── redis/ # Redis caching
│ ├── console/ # Console output
│ └── stream/ # Stream processing
├── crypto/ # Encryption utilities
├── event/ # Event system
├── mixin/ # Reusable mixins
└── util/ # General utilities
Python Version Support
- Python 3.10
- Python 3.11
- Python 3.12
- Python 3.13
- Python 3.14
Development
Requirements
- Python 3.10+
- Redis (for cache features)
- Docker (for running tests with testcontainers)
Setting Up Development Environment
# Clone the repository
git clone https://github.com/oddbit-project/rick.git
cd rick
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install with development dependencies
pip install -e .
pip install -r requirements-dev.txt
# Run tests
pytest
# Run tests with coverage
pytest --cov=rick --cov-report=html
# Run linting
flake8 rick/ tests/
Running Tests with Tox
Test across multiple Python versions:
# Run all tests
tox
# Run specific Python version
tox -e py310
tox -e py311
tox -e py312
tox -e py313
tox -e py314
# Run linting only
tox -e flake
Related Projects
- RickDb - Database abstraction layer for Rick
- Flask - Recommended web framework for HTTP functionality
Contributing
Contributions are welcome! Rick is maintained by the OddBit organization.
Guidelines
- Fork the repository
- Create a feature branch
- Write tests for new functionality
- Ensure all tests pass
- Submit a pull request
Security
For security concerns, please review our security policy or contact the maintainers directly.
Security Features
- Encrypted caching with Fernet256
- BCrypt password hashing
- Secure configuration loading from files
- Input validation and sanitization
- Regular security audits with pip-audit
License
Rick is licensed under the BSD 3-Clause License. See the LICENSE file for details.
Changelog
See CHANGELOG.md for version history and release notes.
Support
- Issues: GitHub Issues
- Repository: GitHub
- PyPI: https://pypi.org/project/rick/
- Documentation: https://oddbit-project.github.io/rick/
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file rick-0.8.6.tar.gz.
File metadata
- Download URL: rick-0.8.6.tar.gz
- Upload date:
- Size: 92.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a89d2b5204e3f92ceed1f9f62e26edb737b5a1105616e0f383a419950be0d719
|
|
| MD5 |
109d3a71ca2d3bcada81a75a43afbb25
|
|
| BLAKE2b-256 |
9788c8811b09db82e3d16cd8046950c04addaa517215f2456d2229082311d5a5
|
Provenance
The following attestation bundles were made for rick-0.8.6.tar.gz:
Publisher:
publish.yml on oddbit-project/rick
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
rick-0.8.6.tar.gz -
Subject digest:
a89d2b5204e3f92ceed1f9f62e26edb737b5a1105616e0f383a419950be0d719 - Sigstore transparency entry: 2338187779
- Sigstore integration time:
-
Permalink:
oddbit-project/rick@133b6bb0c3057a5a08c7e6f7fd0e26a5ff0859cb -
Branch / Tag:
refs/tags/v0.8.6 - Owner: https://github.com/oddbit-project
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@133b6bb0c3057a5a08c7e6f7fd0e26a5ff0859cb -
Trigger Event:
release
-
Statement type: