starlette
БесплатноЗапускает вложенные скриптыНе проверенBuild async web applications and APIs with Starlette 1.0, the lightweight ASGI framework for Python. Use this skill whenever a user wants to create an async…
от simonw★ 804 звезды на GitHubОб этом скилле
Starlette 1.0
Starlette is a lightweight ASGI framework/toolkit for building high-performance async web services in Python.
Version 1.0 was released on March 22, 2026 — the first stable release after nearly eight years of development.
It requires Python 3.10+ and depends only on anyio. It is the foundation for FastAPI and the Python MCP SDK.
Installation
pip install starlette
pip install uvicorn # ASGI server
pip install starlette[full] # all optional deps: httpx, jinja2, python-multipart, itsdangerous, pyyaml
1 · Application
The Starlette class ties together routing, middleware, exception handling, and lifespan.
from contextlib import asynccontextmanager
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.responses import JSONResponse
from starlette.routing import Route
@asynccontextmanager
async def lifespan(app):
print("Starting up")
yield
print("Shutting down")
async def homepage(request):
return JSONResponse({"hello": "world"})
app = Starlette(
debug=True,
routes=[Route("/", homepage)],
middleware=[Middleware(SessionMiddleware, secret_key="secret")],
exception_handlers={},
lifespan=lifespan,
)
Run with: uvicorn main:app --reload
Starlette constructor parameters (1.0)
| Parameter | Description |
|---|---|
debug |
Enable debug tracebacks on errors |
routes |
List of Route, WebSocketRoute, Mount, Host |
middleware |
List of Middleware(cls, **kwargs) |
exception_handlers |
Dict mapping status codes or exception types to handlers |
lifespan |
Async context manager for startup/shutdown |
1.0 Breaking Change:
on_startup,on_shutdown,@app.route(),@app.websocket_route(),@app.middleware(),@app.exception_handler(),on_event(), andadd_event_handler()have all been removed. Uselifespan,routes,middleware, andexception_handlersparameters instead.
Storing and accessing state
# On the app
app.state.ADMIN_EMAIL = "[email protected]"
# In an endpoint, access via request.app
async def dashboard(request):
email = request.app.state.ADMIN_EMAIL
return JSONResponse({"admin": email})
Using Starlette as a pure ASGI toolkit
You can use any Starlette component standalone, without the Starlette class:
from starlette.responses import PlainTextResponse
async def app(scope, receive, send):
assert scope["type"] == "http"
response = PlainTextResponse("Hello, world!")
await response(scope, receive, send)
2 · Routing
Basic routes
from starlette.routing import Route, Mount, WebSocketRoute
from starlette.responses import PlainTextResponse
async def homepage(request):
return PlainTextResponse("Home")
async def user_detail(request):
username = request.path_params["username"]
return PlainTextResponse(f"Hello, {username}")
routes = [
Route("/", homepage),
Route("/users/{username}", user_detail, methods=["GET"]),
]
Path parameter convertors
Built-in convertors: str (default), int, float, uuid, path.
Route("/items/{item_id:int}", get_item)
Route("/files/{file_path:path}", get_file)
Route("/values/{val:float}", get_value)
Route("/objects/{obj_id:uuid}", get_object)
Custom convertors
from datetime import datetime
from starlette.convertors import Convertor, register_url_convertor
class DateTimeConvertor(Convertor):
regex = r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"
def convert(self, value: str) -> datetime:
return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S")
def to_string(self, value: datetime) -> str:
return value.strftime("%Y-%m-%dT%H:%M:%S")
register_url_convertor("datetime", DateTimeConvertor())
# Usage: Route("/history/{date:datetime}", history)
Submounting routes
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles
routes = [
Route("/", homepage),
Mount("/users", routes=[
Route("/", users_list, methods=["GET", "POST"]),
Route("/{username}", user_detail),
]),
Mount("/static", app=StaticFiles(directory="static"), name="static"),
]
Reverse URL lookups
# In an endpoint — produces a full URL
url = request.url_for("user_detail", username="alice")
# With named mounts
routes = [
Mount("/users", name="users", routes=[
Route("/{username}", user_detail, name="user_detail"),
])
]
url = request.url_for("users:user_detail", username="alice")
# Without a request (returns path only)
path = app.url_path_for("user_detail", username="alice")
Host-based routing
from starlette.routing import Host, Router
api = Router(routes=[...])
routes = [
Host("api.example.org", app=api, name="api"),
Host("{subdomain}.example.o
Установить starlette в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл starlette?
Build async web applications and APIs with Starlette 1.0, the lightweight ASGI framework for Python. Use this skill whenever a user wants to create an async Python web app, REST API, WebSocket server, or ASGI application using Starlette. Triggers include mentions of 'Starlette', 'ASGI', async Python web frameworks, or requests to build lightweight async APIs, WebSocket services, streaming responses, or middleware pipelines. Also use when the user is working with FastAPI internals (which is built on Starlette), needs ASGI middleware patterns, or wants a minimal async web server without a full framework. Covers routing, requests/responses, WebSockets, middleware, templates, static files, authentication, lifespan, background tasks, config, testing, schemas, and more.
Как установить скилл starlette?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл starlette запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic