8000 GitHub - dj-bolt/django-bolt: The fastest Python web framework, built on Django. Rust (Actix Web) HTTP server + async typed handlers + msgspec, with the full Django ORM, Admin, middleware and auth. 300k+ req/s, no gunicorn/uvicorn. · GitHub
[go: up one dir, main page]

Skip to content

About

The fastest Python web framework, built on Django. Rust (Actix Web) HTTP server + async typed handlers + msgspec, with the full Django ORM, Admin, middleware and auth. 300k+ req/s, no gunicorn/uvicorn.

Topics

Resources

Contributing

Stars

1.8k stars

Watchers

22 watching

Forks

Repository files navigation

Django-Bolt

Django APIs on a Rust server

PyPI Python versions Django versions License Downloads Discord

Documentation · Tutorial · Benchmarks · Comparison · Discord

Django-Bolt is an API framework and an HTTP server for Django. You write typed handlers in Python, in a normal Django project. A Rust server (Actix Web) receives each request, and runs routing, authentication, CORS and rate limits before it calls your handler. Your models, admin, migrations and settings do not change.

import msgspec
from django.contrib.auth.models import User

from django_bolt import BoltAPI

api = BoltAPI()


class UserOut(msgspec.Struct):
    id: int
    username: str


@api.get("/users")
async def list_users(limit: int = 20) -> list[UserOut]:
    return User.objects.order_by("id")[:limit]
python manage.py runbolt --dev
curl "localhost:8000/users?limit=2"
# [{"id":1,"username":"alice"},{"id":2,"username":"bob"}]

runbolt is also the production server. You do not need gunicorn or uvicorn.

Speed

Test Result
JSON route, 8 processes, 100 connections 324,493 req/s
1 KB JSON, 1 process, against Litestar 2.8×
1 KB JSON, 1 process, against FastAPI 5.8×
10 rows from PostgreSQL, 1 process, against Litestar and FastAPI 2.2× and 2.3×

Measured on an AMD Ryzen 5 5600G with bombardier. The Benchmarks page gives all results, their conditions and the commands to reproduce them.

Install

Django-Bolt needs Python 3.12 or later and Django 5.2 or later. See Installation for the full requirements.

pip install django-bolt

Add the app to your settings:

INSTALLED_APPS = [
    # ...
    "django_bolt",
]

Create api.py next to your urls.py, or in any installed app. runbolt finds it when it starts:

from django_bolt import BoltAPI

api = BoltAPI()


@api.get("/hello/{name}")
async def hello(name: str) -> dict:
    return {"message": f"Hello, {name}"}

Start the server:

python manage.py runbolt --dev            # development, reloads on change
python manage.py runbolt --processes 4    # production

Open http://localhost:8000/docs for the OpenAPI docs. Then follow the tutorial. It builds an articles API in four parts.

Examples

Validate a request

Bolt reads each argument from its type hint: path, query, header, cookie, form, file or JSON body. A bad value gets a 422 response, and the handler does not run.

from typing import Annotated

import msgspec

from django_bolt import BoltAPI
from django_bolt.params import Header

api = BoltAPI()


class ArticleIn(msgspec.Struct):
    title: str
    body: str


@api.post("/articles", status_code=201)
async def create_article(
    article: ArticleIn,
    client: Annotated[str, Header(alias="x-client")],
    notify: bool = False,
) -> dict:
    return {"title": article.title, "client": client, "notify": notify}

Protect a route

Rust checks the token and the guards before Python runs.

from django_bolt import BoltAPI
from django_bolt.auth import IsAuthenticated, JWTAuthentication

api = BoltAPI()


@api.get("/me", auth=[JWTAuthentication()], guards=[IsAuthenticated()])
async def me(request) -> dict:
    user = await request.auser()
    return {"username": user.username}

Serve a model with a viewset

from django.contrib.auth.models import User

from django_bolt import BoltAPI, ModelViewSet, PageNumberPagination
from django_bolt.serializers import Serializer

api = BoltAPI()


class UserSerializer(Serializer):
    id: int
    username: str
    email: str


@api.viewset("/users")
class UserViewSet(ModelViewSet):
    queryset = User.objects.order_by("id")
    serializer_class = UserSerializer
    pagination_class = PageNumberPagination

Stream events and use WebSocket

import asyncio
from collections.abc import AsyncIterator

from django_bolt import BoltAPI
from django_bolt.responses import EventSourceResponse
from django_bolt.websocket import WebSocket

api = BoltAPI()


@api.get("/ticks", response_class=EventSourceResponse)
async def ticks() -> AsyncIterator[dict]:
    for tick in range(3):
        yield {"tick": tick}
        await asyncio.sleep(1)


@api.websocket("/ws/echo")
async def echo(websocket: WebSocket):
    await websocket.accept()
    async for message in websocket.iter_text():
        await websocket.send_text(message)

Limit and allow callers

from django_bolt import BoltAPI
from django_bolt.middleware import cors, rate_limit

api = BoltAPI()


@api.get("/public")
@cors(origins=["https://example.com"])
@rate_limit(rps=100, burst=200)
async def public() -> dict:
    return {"ok": True}

Serve tools to LLM clients

Install the MCP add-on with pip install "django-bolt[mcp]".

from bolt_mcp import MCP

from django_bolt import BoltAPI

api = BoltAPI()
mcp = MCP("articles")


@mcp.tool
async def add(a: int, b: int) -> dict:
    return {"sum": a + b}


api.mount_mcp(mcp)

What you get

Area Features
Requests Typed path, query, header, cookie, form, file and body parameters
Responses JSON, HTML, redirects, files, streaming, server-sent events
Serializers msgspec structs, field sets, computed fields, model integration
Django ORM Return a QuerySet from an async handler, or use the async ORM
Authentication JWT, API key and session auth, checked in Rust
Permissions IsAuthenticated, AllowAny, and claim checks with Requires(...)
CORS, rate limits, compression Applied in Rust
Middleware Bolt middleware, and Django middleware when you turn it on
Class-based views APIView, ViewSet, ModelViewSet, @action
Pagination Page number, limit and offset, cursor
Dependencies Depends()
WebSocket Handlers with the same auth, guards and CORS as HTTP routes
OpenAPI Swagger UI, ReDoc, Scalar, RapiDoc and Stoplight Elements at /docs
Static and media files Served by Rust, no WhiteNoise
Testing A test client that runs the same Rust pipeline as the server
Deployment Many processes on one port, worker recycling, graceful stop
MCP servers Tools, resources and prompts over MCP Streamable HTTP

When not to use Django-Bolt

  • You need a stable API. Django-Bolt is at version 0.x. A minor release can change an API. Read the changelog before you upgrade.
  • Your host needs a WSGI or ASGI application. Bolt routes run only in runbolt.
  • You depend on Django REST Framework packages or on Pydantic. Bolt has its own serializers and validates with msgspec.

The comparison gives the full list of trade-offs next to Django Ninja, DRF, FastAPI and Litestar.

Contribute

CONTRIBUTING.md explains the setup (Rust toolchain, uv, just), the tests and the pull request rules.

git clone https://github.com/dj-bolt/django-bolt.git
cd django-bolt
uv sync
just build
just test-py

Get help

Sponsors

Become a sponsor to support the development of Django-Bolt. Your logo will show here, with a link to your website.

Backers

Acknowledgments

Django-Bolt uses ideas and code from these projects:

License

MIT.

About

The fastest Python web framework, built on Django. Rust (Actix Web) HTTP server + async typed handlers + msgspec, with the full Django ORM, Admin, middleware and auth. 300k+ req/s, no gunicorn/uvicorn.

Topics

Resources

Contributing

Stars

1.8k stars

Watchers

22 watching

Forks

Releases

Sponsor this project

Contributors

Languages

0