CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-blacksheep

Fast web framework for Python asyncio

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

BlackSheep - Python Web Framework

BlackSheep 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 Information

# Package: blacksheep
# Requires Python: 3.8+
# Dependencies: guardpost, rodi, essentials
# Optional dependencies: uvicorn, hypercorn (ASGI servers)

Core Imports

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,
)

Client Imports

from blacksheep.client import (
    # HTTP Client
    ClientSession,
    
    # Client Exceptions
    ConnectionTimeout, RequestTimeout,
    CircularRedirectError, MaximumRedirectsExceededError,
)

Basic Usage

Simple Web Application

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:app

HTTP Client Usage

import 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())

Framework Capabilities

🚀 Core Server Functionality

  • Application: Main server application class with lifecycle management
  • Routing: Advanced URL routing with parameter extraction and type conversion
  • Middleware: Request/response processing pipeline with built-in and custom middleware
  • Dependency Injection: Service container with automatic resolution
  • Static Files: Efficient static file serving with caching and security

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 serving

📨 Request/Response Handling

  • HTTP Messages: Request and Response classes with rich functionality
  • Content Types: Support for JSON, HTML, forms, multipart, streaming content
  • Headers: Case-insensitive header handling with manipulation methods
  • URL Parsing: Comprehensive URL manipulation and validation
  • Content Negotiation: Automatic content type detection and parsing

Key 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 response

🔐 Authentication & Authorization

  • JWT Authentication: Bearer token validation with OIDC support
  • Cookie Authentication: Secure cookie-based authentication
  • Authorization Policies: Role-based and policy-based access control
  • Decorators: Simple auth decorators for endpoints
  • Session Management: Secure session handling with encryption

Key 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"])

🌐 HTTP Client

  • ClientSession: Full-featured async HTTP client
  • Connection Pooling: Automatic connection management
  • Redirects: Configurable redirect handling
  • SSL Support: Custom SSL context configuration
  • Timeouts: Connection and request timeout controls
  • Middlewares: Client-side middleware support

Key APIs:

async with ClientSession() as client:
    response = await client.get("https://api.com")
    data = await response.json()

🔌 WebSocket Support

  • WebSocket Handler: Full-duplex communication support
  • State Management: Connection lifecycle tracking
  • JSON Messages: Built-in JSON message serialization
  • Route Integration: WebSocket routes with parameter extraction
  • Error Handling: Comprehensive WebSocket exception handling

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}")

🧪 Testing Utilities

  • TestClient: HTTP client simulation for testing
  • Mock Objects: ASGI mocks for unit testing
  • Integration Testing: Full application testing support
  • Async Testing: Asyncio-compatible test utilities
  • Request Simulation: Complete HTTP request simulation

Key APIs:

from blacksheep.testing import TestClient

client = TestClient(app)
response = await client.get("/api/users")
assert response.status == 200

Additional Features

  • CORS: Cross-Origin Resource Sharing with flexible policies
  • CSRF Protection: Cross-Site Request Forgery mitigation
  • Sessions: Encrypted session management
  • OpenAPI: Automatic API documentation generation
  • Compression: Response compression (gzip)
  • Security Headers: HSTS and security header middleware
  • File Uploads: Multipart form and file upload handling
  • Templating: Template engine integration
  • Error Handling: Comprehensive exception handling system

Framework Architecture

BlackSheep follows these design principles:

  1. Async-First: Built specifically for asyncio with no synchronous compatibility layer
  2. Type Safety: Comprehensive type annotations and runtime type checking
  3. Performance: Cython-optimized core components for maximum speed
  4. Modularity: Clean separation of concerns with optional components
  5. Standards Compliance: Full HTTP/1.1, WebSocket, and ASGI specification support
  6. Developer Experience: Rich debugging, testing, and documentation tools

Quick Reference

Status Code Responses

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()                          # 404

Request Data Binding

async 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
):
    pass

Content Types

from 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.

docs

additional.md

auth.md

client.md

core-server.md

index.md

request-response.md

testing.md

websockets.md

tile.json