Skip to main content

A lightweight routing framework for Python Workers

Project description

Kinglet Logo

Kinglet

Lightning-fast Python web framework for Cloudflare Workers

CI Quality Gate Status codecov PyPI version Python 3.12 License: MIT

Quick Start

Install: pip install kinglet or add dependencies = ["kinglet"] to pyproject.toml

from kinglet import Kinglet, CorsMiddleware, cache_aside_d1

app = Kinglet(root_path="/api")

# Flexible middleware (v1.4.2+)
app.add_middleware(CorsMiddleware(allow_origin="*"))

@app.post("/auth/login")
async def login(request):
    data = await request.json()
    return {"token": "jwt-token", "user": data["email"]}

@app.get("/api/data")
@cache_aside_d1(cache_type="api_data", ttl=1800)  # D1 caching (v1.5.0+)
async def get_data(request):
    return {"data": "cached_in_prod_fresh_in_dev"}

Why Kinglet?

Feature Kinglet FastAPI Flask
Bundle Size 272KB 7.8MB 1.9MB
Testing No server needed TestServer required Test client required
Workers Ready ✅ Built-in ❌ Complex setup ❌ Not compatible

Key Features

Core: Decorator routing, typed parameters, flexible middleware, auto error handling, serverless testing Cloudflare: D1/R2/KV helpers, D1-backed caching, environment-aware policies, CDN-aware URLs Database: Micro-ORM for D1 with migrations, field validation, bulk operations (v1.6.0+) Security: JWT validation, TOTP/2FA, geo-restrictions, fine-grained auth decorators Developer: Full type hints, debug mode, request validation, zero-dependency testing OpenAPI: Auto-generated Swagger/ReDoc docs from routes and models (v1.8.0+)

Examples

Typed Parameters & Auth:

@app.get("/users/{user_id}")
async def get_user(request):
    user_id = request.path_param_int("user_id")  # Validates or returns 400
    token = request.bearer_token()               # Extract JWT
    limit = request.query_int("limit", 10)       # Query params with defaults
    return {"user": user_id, "token": token}

Flexible Middleware & Caching:

# Configure middleware with parameters
cors = CorsMiddleware(allow_origin="*", allow_methods="GET,POST")
app.add_middleware(cors)

# D1-backed caching (v1.5.0+) - faster and cheaper for <1MB responses
@app.get("/api/data")
@cache_aside_d1(cache_type="api_data", ttl=1800)  # D1 primary, R2 fallback
async def get_data(request):
    return {"data": "expensive_query_result"}

# R2-backed caching for larger responses
@app.get("/api/large")
@cache_aside(cache_type="large_data", ttl=3600)  # Environment-aware
async def get_large_data(request):
    return {"data": "large_expensive_query_result"}

D1 Micro-ORM (v1.6.0+):

from kinglet import Model, StringField, IntegerField

class Game(Model):
    title = StringField(max_length=200)
    score = IntegerField(default=0)

# Simple CRUD with field validation
game = await Game.objects.create(db, title="Pac-Man", score=100)
top_games = await Game.objects.filter(db, score__gte=90).order_by("-score").all()

Security & Access Control:

@app.get("/admin/debug")
@require_dev()                    # 404 in production (blackhole)
@geo_restrict(allowed=["US"])     # HTTP 451 for other countries
async def debug_endpoint(request):
    return {"debug": "sensitive data"}

Testing (No Server):

def test_api():
    client = TestClient(app)
    status, headers, body = client.request("GET", "/users/123")
    assert status == 200

OpenAPI/Swagger Documentation (v1.8.0+):

from kinglet import SchemaGenerator, Response

@app.get("/openapi.json")
async def openapi_spec(request):
    generator = SchemaGenerator(app, title="My API", version="1.0.0")
    return Response(generator.generate_spec())

@app.get("/docs")
async def swagger_ui(request):
    generator = SchemaGenerator(app, title="My API")
    return Response(generator.serve_swagger_ui(), content_type="text/html")

# Auto-generates docs from validators and models
# Visit /docs for interactive Swagger UI

Documentation


Built for Cloudflare Workers Python community. Need help?

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

kinglet-1.8.3.tar.gz (209.4 kB view details)

Uploaded Source

Built Distribution

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

kinglet-1.8.3-py3-none-any.whl (99.8 kB view details)

Uploaded Python 3

File details

Details for the file kinglet-1.8.3.tar.gz.

File metadata

  • Download URL: kinglet-1.8.3.tar.gz
  • Upload date:
  • Size: 209.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for kinglet-1.8.3.tar.gz
Algorithm Hash digest
SHA256 220d9e151e9cfc353c8869570bb3fc0d85c1c8eb4d89dca850ee763307058224
MD5 69b5486146345d196b72d29a57fa4ae2
BLAKE2b-256 8e8e793ac81b0e315faf74880035b410f15c5b22718bb09adb96161305b46a28

See more details on using hashes here.

File details

Details for the file kinglet-1.8.3-py3-none-any.whl.

File metadata

  • Download URL: kinglet-1.8.3-py3-none-any.whl
  • Upload date:
  • Size: 99.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for kinglet-1.8.3-py3-none-any.whl
Algorithm Hash digest
SHA256 3b03ca4f68c2ebb6a822651471739a4dcfff12e7ec6ca290a5ceb48c84772c10
MD5 05155f72ff1534c36807cf8cf7822b60
BLAKE2b-256 3e6392741a75bbc3ee93ea65129cdf07d7c4a97b31e839f3b109b897bdab4d30

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