Fast web framework for Python asyncio
npx @tessl/cli install tessl/pypi-blacksheep@1.2.0BlackSheep is a modern, high-performance Python web framework built with asyncio and Cython for optimal speed. It provides comprehensive server-side web application capabilities along with HTTP client functionality, designed for building scalable web services and APIs.
# Package: blacksheep
# Requires Python: 3.8+
# Dependencies: guardpost, rodi, essentials
# Optional dependencies: uvicorn, hypercorn (ASGI servers)from blacksheep import (
# Server Application
Application,
# HTTP Messages
Request, Response, Message,
# Content Types
Content, TextContent, HTMLContent, JSONContent,
FormContent, MultiPartFormData, StreamedContent, FormPart,
# Headers and Cookies
Headers, Header, Cookie, CookieSameSiteMode,
# URL and Routing
URL, Route, Router, RoutesRegistry,
# Request Bindings
FromJSON, FromQuery, FromRoute, FromForm,
FromHeader, FromCookie, FromServices, FromFiles,
FromBytes, FromText,
# Response Helpers
json, text, html, file, redirect,
ok, created, accepted, no_content,
bad_request, unauthorized, forbidden, not_found,
# Authentication & Authorization
auth, allow_anonymous,
# WebSocket Support
WebSocket, WebSocketState, WebSocketError,
# Exceptions
HTTPException, InvalidURL,
# Template Engine
use_templates,
)from blacksheep.client import (
# HTTP Client
ClientSession,
# Client Exceptions
ConnectionTimeout, RequestTimeout,
CircularRedirectError, MaximumRedirectsExceededError,
)from blacksheep import Application, get, json, text
app = Application()
@app.route("/")
async def home():
return text("Hello, BlackSheep!")
@app.route("/api/users/{user_id}")
async def get_user(user_id: int):
return json({"id": user_id, "name": f"User {user_id}"})
@app.route("/api/users", methods=["POST"])
async def create_user(data: FromJSON[dict]):
# data.value contains the parsed JSON
return json({"created": True, "data": data.value})
# Run with: uvicorn main:appimport asyncio
from blacksheep.client import ClientSession
from blacksheep import json as create_json_content
async def main():
async with ClientSession() as client:
# GET request
response = await client.get("https://api.example.com/users")
data = await response.json()
# POST with JSON
json_data = create_json_content({"name": "Alice"})
response = await client.post(
"https://api.example.com/users",
content=json_data
)
print(f"Status: {response.status}")
asyncio.run(main())Key APIs:
app = Application(debug=True)
app.route("/users/{user_id:int}") # Route with typed parameters
app.use_cors() # CORS middleware
app.serve_files("./static") # Static file servingKey APIs:
# Request data binding
async def handler(user: FromJSON[User], id: FromRoute[int]):
pass
# Response creation
return json(data) # JSON response
return file("image.jpg") # File response
return redirect("/home") # Redirect responseKey APIs:
@auth("admin") # Require admin role
async def admin_only():
pass
@allow_anonymous
async def public_endpoint():
pass
# JWT configuration
app.use_authentication().add_jwt_bearer(audiences=["api"])Key APIs:
async with ClientSession() as client:
response = await client.get("https://api.com")
data = await response.json()Key APIs:
@app.ws("/chat/{room}")
async def chat_handler(websocket: WebSocket, room: str):
await websocket.accept()
await websocket.send_text(f"Joined room: {room}")Key APIs:
from blacksheep.testing import TestClient
client = TestClient(app)
response = await client.get("/api/users")
assert response.status == 200BlackSheep follows these design principles:
from blacksheep import ok, created, bad_request, not_found, unauthorized
return ok({"message": "Success"}) # 200
return created({"id": 123}) # 201
return bad_request({"error": "Invalid"}) # 400
return unauthorized() # 401
return not_found() # 404async def endpoint(
id: FromRoute[int], # URL parameter
q: FromQuery[str], # Query parameter
data: FromJSON[MyModel], # JSON body
file: FromFiles, # Uploaded files
token: FromHeader[str], # Header value
session_id: FromCookie[str], # Cookie value
service: FromServices[MyService], # DI service
):
passfrom blacksheep import TextContent, JSONContent, FormContent
return Response(200, content=TextContent("Hello"))
return Response(200, content=JSONContent({"key": "value"}))
return Response(200, content=FormContent({"field": "value"}))For detailed information about each component, see the respective documentation sections linked above.