Skip to main content

Pancake - Decorator-driven Python web framework with IoC, MyBatis ORM, and AI workflow

Project description

Pancake Framework

A decorator-driven Python framework with Spring-inspired IoC, MyBatis-style ORM, and AI workflow integration.

Python License PyPI CI

中文文档

Features

  • Dough IoC System — Spring-inspired Bean container with full lifecycle (on_initon_starton_stopon_destroy)
  • Decorator-Driven@Singleton, @Prototype, @Lazy, @DependsOn, @Import, @inject
  • Async First — All lifecycle methods support async def, DoughFactory handles sync/async transparently
  • Zero Import — All decorators and services auto-injected into builtins
  • Base ClassesConfiguration (bean factory), Service, Struct (dataclass + Dough), Function
  • MyBatis Plus ORM — Async ORM with CRUD, @Select/@Insert, dynamic SQL, chain queries
  • AI Module — Unified LLM client (OpenAI/DeepSeek/Gemini/Ollama), memory, RAG
  • Redis Cache@cached with anti-penetration/avalanche/breakdown protection
  • Message Queue — Event-driven with SimpleBroker and RedisBroker
  • Plugin System — XML-based plugin management, auto pip install, pancake plugin CLI

Quick Start

pip install pancake_framework
pancake create myapp && cd myapp
pancake run

Server starts at http://127.0.0.1:8080. Health check at /health.

Dough IoC System

The core of Pancake is the Dough system — a Spring-inspired IoC container.

Bean Lifecycle

__init__()  →  on_init()  →  on_start()  →  [running]  →  on_stop()  →  on_destroy()
   构造        @PostConstruct    就绪                        停止         @PreDestroy

Scopes

Scope Decorator Description
Singleton @Singleton One instance per factory (default)
Prototype @Prototype New instance every resolve
Lazy @Lazy Created on first access

Example

from pancake import Service, DoughFactory, DependsOn, inject, Singleton

@Singleton
@DependsOn("DatabaseService")
class UserService(Service):
    async def on_init(self):
        self.db = DoughFactory.get().resolve("DatabaseService")

    async def find_user(self, user_id: int):
        return await self.db.query(user_id)

class AppConfig(Configuration):
    def my_cache(self):
        return RedisCache()

    @noMaker
    def helper(self):
        return "not a bean"

Decorators

Decorator Target Description
@DoughDecorator Class Mark class as Bean
@Singleton Class Singleton scope
@Prototype Class Prototype scope
@Lazy Class Lazy initialization
@DependsOn("A", "B") Class Declare dependencies
@Import(ExternalCls) Class Auto-register external classes
@Maker Method Mark method return as Bean
@noMaker Method Exclude method from auto-registration
@inject Function Auto-inject dependencies from factory
@Config Class Inject fields from settings

Documentation

Module Description
CLI Command-line tools
MyBatis ORM Mappers, CRUD, chain queries, dynamic SQL
AI LLM client, memory, RAG
Redis Cache, data structures, distributed locks
Config YAML/XML/env configuration
Plugins Plugin system and built-in plugins
Messaging Event-driven message queue
Remote HTTP and gRPC remote calls

Optional Dependencies

pip install pancake_framework[ai]          # AI module
pip install pancake_framework[langgraph]   # LangGraph workflow
pip install pancake_framework[redis]       # Redis cache & messaging
pip install pancake_framework[grpc]        # gRPC remote calls
pip install pancake_framework[cui]         # Click CLI commands
pip install pancake_framework[gui]         # Flet GUI
pip install pancake_framework[all]         # All optional deps

Architecture

pancake/
├── dough.py           # Dough base class, Scope enum, DoughMeta metaclass
├── registry.py        # Global class & decorator registry
├── decorators.py      # @Singleton, @Prototype, @Lazy, @inject, etc.
├── settings.py        # Centralized configuration management
├── run.py             # Startup pipeline
├── base/              # Configuration, Function, Service, Struct
├── factory/           # DoughFactory — Bean lifecycle management
├── builder/           # Build pipeline, plugin loader, source loader
├── cli/               # CLI commands (create/run/plugin/config)
├── ovenware/          # Broker (message queue)
├── resource/          # YAML/JSON/XML config loaders
└── tool/              # Utilities

TODO

Core / IoC

  • Database migration support
  • Configuration hot-reload
  • Pagination Page object abstraction
  • OpenTelemetry / metrics integration
  • Graceful shutdown with signal handling
  • WebSocket support
  • Rate limiting middleware
  • API documentation auto-generation
  • More database dialects (SQLite/PG/MySQL type mapping)
  • Connection pool health check and auto-reconnect
  • JWT authentication support
  • Scheduled tasks (cron-like)
  • CLI interactive code (REPL)
  • Bean lifecycle callbacks — on_init(@PostConstruct), on_destroy(@PreDestroy)
  • Lazy initialization — @Lazy for deferred bean creation
  • Dependency resolution — @DependsOn topological sort, @Import auto-register
  • Async lifecycle — all lifecycle methods support async def
  • Zero import — all decorators/services auto-injected into builtins
  • Circular dependency detection — topological sort with cycle reporting
  • Integration tests — 42 tests covering multi-layer deps, diamond, edge cases
  • Auto-configuration — auto-detect dependencies and configure defaults
  • Profiles — environment-specific config (dev / test / prod)
  • Conditional beans — @ConditionalOnProperty, @ConditionalOnClass
  • Event system — @EventListener, application events (ContextRefreshed, etc.)
  • Property binding — auto-map YAML/ENV to dataclass (@ConfigurationProperties)

Web / REST

  • CORS configuration — global and per-route CORS policy
  • API versioning — /api/v1/users, /api/v2/users
  • Exception handler — @ExceptionHandler, global error response
  • Request logging middleware — auto-log method, path, status, duration
  • Response compression — gzip/brotli middleware
  • File upload — @multipart, multipart/form-data handling
  • Server-Sent Events — @sse_controller for real-time push
  • Request body validation — Pydantic-style @Valid on request models
  • Content negotiation — JSON / XML response based on Accept header
  • Async route handler — auto-detect async vs sync functions
  • Static file serving — built-in static directory mount
  • Request ID — auto-generate and propagate X-Request-Id

Security

  • OAuth2 support — OAuth2 client and resource server
  • API key authentication — @api_key_required header-based auth
  • Password hashing — bcrypt/argon2 integration
  • CSRF protection — token-based CSRF for form submissions
  • Security headers — auto-add HSTS, X-Frame-Options, CSP
  • IP whitelist/blacklist — middleware-based IP filtering
  • Session management — server-side session with Redis/memory store

Data / ORM

  • Transaction propagation — REQUIRED, REQUIRES_NEW, NESTED
  • Soft delete — @SoftDelete, deleted_at column support
  • Auto timestamps — created_at, updated_at auto-fill
  • Optimistic locking — version field for concurrent update safety
  • Multi-datasource — connect to multiple databases simultaneously
  • Database seeding — auto-insert initial data on startup
  • Query logging — SQL statement logging with execution time
  • Raw SQL helper — db.execute_raw(sql) with safety checks
  • Relation mapping — one-to-many, many-to-many lazy/eager loading

AOP / Middleware

  • AOP (Aspect-Oriented Programming) — @Before, @After, @Around pointcuts
  • Retry mechanism — @Retry(max=3, delay=1) for flaky operations
  • Circuit breaker — @CircuitBreaker for fault tolerance
  • Cache abstraction — @Cacheable, @CacheEvict (multi-backend: memory/Redis)
  • Async execution — @Async for non-blocking background tasks
  • Method timer — @Timed for method execution metrics
  • Locking — @DistributedLock for concurrent access control

Observability

  • Structured logging — JSON log output with correlation ID
  • Health indicators — custom health checks (DB, Redis, external API)
  • Distributed tracing — OpenTelemetry trace context propagation
  • Log levels API — runtime log level change via REST endpoint

Plugin System

  • XML-based plugin declaration — <dependencies> in pancake.xml
  • Auto pip install — import-first, pip-fallback on ImportError
  • CLI management — pancake plugin list/add/remove/clear
  • CLI modularization — split monolithic cli.py into cli/ package
  • Plugin marketplace — central registry for discovering plugins
  • Plugin version constraints — <version> tag with semver matching
  • Plugin hooks — on_install, on_uninstall, on_upgrade lifecycle

DevOps / CLI

  • CLI modularization — split into cli/ package (project/config/plugin/misc)
  • Project scaffolding — pancake create with templates (API / Fullstack / Microservice)
  • Code generation — auto-generate Mapper/Controller from table schema
  • DevTools — auto-restart on code change (watchdog)
  • Docker support — auto-generate Dockerfile and docker-compose.yml
  • Config validation — startup validation of required config keys
  • Dry run — pancake check with full dependency and config validation

Performance

  • C extension — convert hot-path modules (sql_parser, wrapper, jwt) to C for speed

Tests

pip install pytest pytest-asyncio
python -m pytest tests/ -v

License

MIT

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

pancake_framework-0.2.3.tar.gz (40.6 kB view details)

Uploaded Source

Built Distribution

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

pancake_framework-0.2.3-py3-none-any.whl (54.7 kB view details)

Uploaded Python 3

File details

Details for the file pancake_framework-0.2.3.tar.gz.

File metadata

  • Download URL: pancake_framework-0.2.3.tar.gz
  • Upload date:
  • Size: 40.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.0 CPython/3.13.5 Windows/11

File hashes

Hashes for pancake_framework-0.2.3.tar.gz
Algorithm Hash digest
SHA256 8ed3d4d66b574ed08207ffd9be934aff71c9e5593c22c0c487d1943b5de49f58
MD5 80955797c11b760afcce218786b2c628
BLAKE2b-256 fda2221f32530782b66a25e84fad5c2fda8248af0a0ac6f0566c785145054c52

See more details on using hashes here.

File details

Details for the file pancake_framework-0.2.3-py3-none-any.whl.

File metadata

  • Download URL: pancake_framework-0.2.3-py3-none-any.whl
  • Upload date:
  • Size: 54.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.0 CPython/3.13.5 Windows/11

File hashes

Hashes for pancake_framework-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 74e965ef9634828bfcc6b38cc6ae115c72514cf8032058d6555362a6266b0ac5
MD5 87682e3995bd8941649c94efc9a02b20
BLAKE2b-256 545007e2c1bd9a7d05837ef4ed196d5647191288d0134cf051ec459206f6681c

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