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.2.tar.gz (40.8 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.2-py3-none-any.whl (53.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pancake_framework-0.2.2.tar.gz
  • Upload date:
  • Size: 40.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for pancake_framework-0.2.2.tar.gz
Algorithm Hash digest
SHA256 0140c6be9e8b0f0ffa82b4597dc33bea3556de5eb6b60df6517d03365a8df739
MD5 a5331850c34481c44d9992e34ccce176
BLAKE2b-256 8b97ca591bec53bc920bc4761746c463df8ca0ff37d1f9d51d5b80ce1402e7ab

See more details on using hashes here.

Provenance

The following attestation bundles were made for pancake_framework-0.2.2.tar.gz:

Publisher: publish.yml on PancakeFramework/PancakeFramework

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

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

File metadata

File hashes

Hashes for pancake_framework-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 e50673f388bd095f71e34a3c2bc0ff14d1b51316ee650f5ce30b8ccb414753c7
MD5 b9c340c437d1c2de844bbf11ee59db1d
BLAKE2b-256 b17f64da10fe2298e9a84b952232bf55e106904854ae89234fe1df67ddd0d9e5

See more details on using hashes here.

Provenance

The following attestation bundles were made for pancake_framework-0.2.2-py3-none-any.whl:

Publisher: publish.yml on PancakeFramework/PancakeFramework

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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