Repository navigation
v0.1.0-beta.7 🚀
Pre-releaseCore Architecture Overhaul, Testing Subsystem & Unified Security
Welcome to v0.1.0-beta.7 of the ZCore Framework! 🚀
This is one of the most substantial and transformative releases in ZCore's history. Guided by our foundational philosophy of Engineered Simplicity (KISS) and Clean Architecture, v0.1.0-beta.7 eliminates generic boilerplate across data layers, introduces a complete asynchronous testing framework with transaction rollback guarantees, unifies request-scoped context state and security primitives, and introduces event-driven subscriber mechanics.
🚀 Core Features & Architectural Advancements
1. 🧪 Comprehensive Async Testing Infrastructure (zcore.testing)
Writing integration and unit tests for database-backed FastAPI services is now effortless and boilerplate-free:
ZTestFixtureEngine: Modular async fixtures includingContainerSandbox(snapshots and restores IoC state),DatabaseRollback(wraps tests in isolated savepoint transactions),UserContext(injects user identities and security scopes), andAppLifespan(manages FastAPI lifecycle hooks).ZTestClient: An asynchronous test client extendinghttpx.AsyncClientthat coordinates test sandboxes with zero manual mock setups.BaseZTest: An abstract class providing clean, class-based test suites using an intuitiveasync with self.run(use_db=True)context manager.- CLI Test Generator: Run
zc startapp <domain> --testto scaffold ready-to-run test files automatically.
2. 🌐 Centralized Request Context & Scopes (ZContext & ctx)
Replaced fragmented context functions with a unified, high-performance, contextvar-isolated ZContext class:
- Global
ctxSingleton: Access context variables anywhere in the request lifecycle via strongly-typed properties (ctx.user_id,ctx.restricted_fields,ctx.action). ctx.scope()Context Manager: Create isolated, temporary context overrides for background tasks, cron jobs, or test sandboxing.- Action-Aware Routing: Route operations (
create,view,update,delete) are automatically detected and injected intoZContext, driving action-scoped field pruning inZchema.
3. 🧹 Streamlined Data Layer Generics & Dynamic Hook Propagation
We eliminated the verbose schema generic clutter from data access layers:
- Single Generic Parameter:
BaseRepository[Model]andBaseService[Model]now only require the database model type. - Dynamic Criterion & Query Filters: Repository
get(),exist(), andget_list()now accept arbitrary positional SQLAlchemy binary expressions (*criterion) and keyword arguments (**filters) consolidated via_apply_filters. - Dynamic Pre-Hook Data Injection: Service
pre_createandpre_updatelifecycle hooks can now return a dictionary (Optional[dict[str, Any]]) that automatically merges context-derived data (e.g.,user_idfromctx) directly into repository database flushes.
4. 🔐 Consolidated Security & Generic Authentication (BaseAuth)
- Unified
SecurityClass: Merged scattered hashing and JWT logic into a centralizedSecuritycoordinator supporting Argon2id password hashing, PyJWT token encoding/decoding, and cryptographic token generation. - Template Method
BaseAuth: A generic authentication dependency that extracts and validates tokens, integrates withBaseCachefor user-lookup caching, and automatically binds the resolved user toZContext. - Dynamic Scope Resolution:
HasScopespermission dependencies now evaluate scopes dynamically fromZContext(ctx.get("scopes")) with automatic type coercion for lists, tuples, and sets.
5. ⚡ Modern Constructor Auto-Wiring (Inject[T])
- Converted
Injectinto a subscriptable type marker (Inject[T]), which seamlessly maps toAnnotated[T, Depends(Injector(T))]. - Allows clean, idiomatic constructor type-hinting in services and routes without importing or declaring raw FastAPI
Depends()chains.
6. 📡 Event-Driven Architecture (@on_event) & SQL Diagnostics
@on_eventDecorator: Mark service methods as event subscribers with automatic container-backed resolution viaEventDispatcher.register_listeners().- SQL Execution Telemetry: Built-in connection interceptors log SQL execution durations in milliseconds and filter out Postgres system catalog query noise.
- Static Route Protection: Added
_sort_routes()to ensure parameterized paths (e.g.,/{id:uuid}) never shadow sibling static endpoints like/search.
🛠️ CLI & Subsystem Enhancements
zc genenv: Introspects registered PydanticSettingsclasses and scaffolds a clean.env.examplefile automatically.SettingsSimplification: RenamedZCoreCoreSettingstoSettingsand replacedENVIRONMENTstrings with booleanDEBUGflags.ZCoreJSONResponse: Replaces standard JSON responses to safely serialize complex types (UUIDs, ISO datetimes, Decimals).- Standalone Documentation Portal: Decoupled documentation from the core repository into the official standalone repository Baseryn/zcore-docs.
⚠️ Breaking Changes & Migration Guide
1. Repository and Service Generic Declarations
You no longer need to pass schema types to BaseRepository or BaseService.
Old:
class TaskRepo(BaseRepository[Task, TaskCreate, TaskUpdate]):
...
class TaskService(BaseService[Task, TaskCreate, TaskUpdate]):
...New:
class TaskRepo(BaseRepository[Task]):
...
class TaskService(BaseService[Task]):
...2. Base Settings & Debug Configuration
The settings class name has been simplified, and ENVIRONMENT is now DEBUG.
Old:
from zcore import ZCoreCoreSettings
class AppSettings(ZCoreCoreSettings):
ENVIRONMENT: str = "development"New:
from zcore import Settings
class AppSettings(Settings):
DEBUG: bool = True3. Dependency Injection Syntax
Update route handlers and constructors to use Inject[T] type annotations.
Old:
@router.post("/tasks")
async def create_task(service: TaskService = Inject(TaskService)):
...New:
from zcore import Inject
@router.post("/tasks")
async def create_task(service: Inject[TaskService]):
...4. Consolidated Security Utilities
Imports from zcore.security.hashing and zcore.security.jwt are merged under Security.
Old:
from zcore.security.hashing import hash_password, verify_password
from zcore.security.jwt import create_access_tokenNew:
from zcore import Security
hashed = Security.hash_password(raw_password)
token = Security.create_jwt({"sub": str(user_id)})🛠 How to Install / Upgrade
To install or upgrade to the latest beta:
pip install --upgrade fastapi-zcore-framework📖 Interactive Documentation: https://baseryn.github.io/zcore-docs/