CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-sanic

A modern Python web server and web framework designed for high performance and speed using async/await syntax.

Pending
Overview
Eval results
Files

blueprints.mddocs/

Blueprint System

Blueprints provide a modular way to organize Sanic applications by grouping related routes, middleware, and functionality into reusable components. They enable clean separation of concerns and support nested blueprint structures for complex applications.

Capabilities

Blueprint Creation

Create blueprint instances with customizable configuration and organizational features.

class Blueprint:
    def __init__(
        self,
        name: str,
        url_prefix: str = None,
        host: str = None,
        version: int = None,
        strict_slashes: bool = None,
        version_prefix: str = "/v",
        ctx: Any = None,
    ):
        """
        Create a new blueprint.
        
        Parameters:
        - name: Blueprint name
        - url_prefix: URL prefix for all routes
        - host: Host restriction for blueprint
        - version: API version number
        - strict_slashes: Strict slash handling
        - version_prefix: Version URL prefix
        - ctx: Blueprint context object
        """

Blueprint Routing

Define routes within blueprints using the same decorators as the main application.

def route(
    self,
    uri: str,
    methods: list = None,
    host: str = None,
    strict_slashes: bool = None,
    stream: bool = False,
    version: int = None,
    name: str = None,
    **kwargs
):
    """
    Blueprint route decorator.
    
    Parameters:
    - uri: Route path
    - methods: HTTP methods
    - host: Host restriction
    - strict_slashes: Slash handling
    - stream: Enable streaming
    - version: Route version
    - name: Route name
    """

def get(self, uri: str, **kwargs):
    """GET method decorator."""

def post(self, uri: str, **kwargs):
    """POST method decorator."""

def put(self, uri: str, **kwargs):
    """PUT method decorator."""

def delete(self, uri: str, **kwargs):
    """DELETE method decorator."""

def patch(self, uri: str, **kwargs):
    """PATCH method decorator."""

def head(self, uri: str, **kwargs):
    """HEAD method decorator."""

def options(self, uri: str, **kwargs):
    """OPTIONS method decorator."""

def add_route(
    self,
    handler,
    uri: str,
    methods: list = None,
    **kwargs
):
    """
    Add route programmatically.
    
    Parameters:
    - handler: Route handler function
    - uri: Route path
    - methods: HTTP methods
    """

Blueprint WebSocket Support

Define WebSocket endpoints within blueprints.

def websocket(self, uri: str, **kwargs):
    """
    WebSocket decorator for blueprints.
    
    Parameters:
    - uri: WebSocket path
    - **kwargs: WebSocket options
    """

def add_websocket_route(self, handler, uri: str, **kwargs):
    """
    Add WebSocket route programmatically.
    
    Parameters:
    - handler: WebSocket handler
    - uri: WebSocket path
    """

Blueprint Static Files

Serve static files through blueprints with blueprint-specific configuration.

def static(
    self,
    uri: str,
    file_or_directory: str,
    **kwargs
):
    """
    Serve static files from blueprint.
    
    Parameters:
    - uri: Static file URL path
    - file_or_directory: File or directory path
    - **kwargs: Static file options
    """

Blueprint Middleware

Apply middleware specifically to blueprint routes.

def middleware(self, middleware_or_request: str):
    """
    Blueprint middleware decorator.
    
    Parameters:
    - middleware_or_request: Middleware type ('request' or 'response')
    """

Blueprint Event Listeners

Register event listeners that execute during blueprint lifecycle events.

def listener(self, event: str):
    """
    Blueprint event listener decorator.
    
    Parameters:
    - event: Event name
    """

Blueprint Exception Handlers

Define exception handlers specific to blueprint routes.

def exception(self, *exceptions):
    """
    Blueprint exception handler decorator.
    
    Parameters:
    - *exceptions: Exception classes to handle
    """

Blueprint Groups

Group multiple blueprints together for bulk operations and shared configuration.

class BlueprintGroup:
    def __init__(
        self,
        url_prefix: str = None,
        version: int = None,
        strict_slashes: bool = None,
        version_prefix: str = "/v",
    ):
        """
        Create blueprint group.
        
        Parameters:
        - url_prefix: Shared URL prefix
        - version: Shared version
        - strict_slashes: Shared slash handling
        - version_prefix: Shared version prefix
        """
    
    def append(self, blueprint: Blueprint):
        """
        Add blueprint to group.
        
        Parameters:
        - blueprint: Blueprint to add
        """
    
    def extend(self, blueprints: list):
        """
        Add multiple blueprints to group.
        
        Parameters:
        - blueprints: List of blueprints
        """
    
    def insert(self, index: int, blueprint: Blueprint):
        """
        Insert blueprint at specific position.
        
        Parameters:
        - index: Insert position
        - blueprint: Blueprint to insert
        """
    
    def remove(self, blueprint: Blueprint):
        """
        Remove blueprint from group.
        
        Parameters:
        - blueprint: Blueprint to remove
        """
    
    def middleware(self, middleware_or_request: str):
        """
        Apply middleware to all blueprints in group.
        
        Parameters:
        - middleware_or_request: Middleware type
        """
    
    def exception(self, *exceptions):
        """
        Apply exception handler to all blueprints in group.
        
        Parameters:
        - *exceptions: Exception classes
        """

Usage Examples

Basic Blueprint

from sanic import Blueprint
from sanic.response import json

# Create blueprint
api_v1 = Blueprint("api_v1", url_prefix="/api/v1")

@api_v1.route("/users")
async def get_users(request):
    users = await fetch_users()
    return json({"users": users})

@api_v1.route("/users", methods=["POST"])
async def create_user(request):
    user_data = request.json
    user = await create_user(user_data)
    return json({"user": user}, status=201)

# Register blueprint with app
app.blueprint(api_v1)

Blueprint with Middleware

from sanic import Blueprint
from sanic.response import json

admin_bp = Blueprint("admin", url_prefix="/admin")

@admin_bp.middleware("request")
async def check_admin_auth(request):
    """Ensure user has admin privileges."""
    if not await is_admin(request):
        return json({"error": "Admin access required"}, status=403)

@admin_bp.route("/dashboard")
async def admin_dashboard(request):
    return json({"message": "Admin dashboard"})

app.blueprint(admin_bp)

Blueprint Groups

from sanic import Blueprint, Sanic
from sanic.blueprints import BlueprintGroup

# Create individual blueprints
users_bp = Blueprint("users", url_prefix="/users")
orders_bp = Blueprint("orders", url_prefix="/orders")
products_bp = Blueprint("products", url_prefix="/products")

# Group blueprints with shared configuration
api_group = BlueprintGroup(url_prefix="/api/v1")
api_group.append(users_bp)
api_group.append(orders_bp)
api_group.append(products_bp)

# Register entire group
app.blueprint(api_group)

Nested Blueprints

# Main API blueprint
api = Blueprint("api", url_prefix="/api")

# Sub-blueprints for different versions
v1 = Blueprint("v1", url_prefix="/v1")
v2 = Blueprint("v2", url_prefix="/v2")

@v1.route("/users")
async def v1_users(request):
    return json({"version": "1.0", "users": []})

@v2.route("/users")
async def v2_users(request):
    return json({"version": "2.0", "users": [], "metadata": {}})

# Create group and register
api_versions = BlueprintGroup()
api_versions.append(v1)
api_versions.append(v2)

app.blueprint(api_versions)

Install with Tessl CLI

npx tessl i tessl/pypi-sanic

docs

blueprints.md

configuration.md

core-application.md

exceptions.md

index.md

middleware-signals.md

request-response.md

server-deployment.md

websockets.md

tile.json