Starlette ASGI Framework

repository·main·Indexed 11 days ago

https://github.com/encode/starlette

A lightweight, high-performance ASGI framework and toolkit for building asynchronous web services in Python. It supports asyncio and trio backends and provides modular components for routing, middleware, authentication, and background tasks.

Tokens
52.3K
Snippets
169
Records
238
Agent score
95%

What's inside Starlette

  1. Use Shiny for reactive Python web applications

    main
    Shiny leverages Starlette and asyncio to allow developers to create web applications using reactive programming. It automates state management and determines the best execution path at runtime to minimize re-rendering, making it suitable for everything from simple dashboards to full-featured web apps.
  2. Use FastAPI for high-performance web APIs

    main
    FastAPI is a high-performance web API framework built on top of Starlette. It uses Pydantic for data handling and is based on the OpenAPI specification (version 3.0.0+ with JSON Schema). It is designed for being easy to learn and fast to code, providing type declarations for route parameters.
  3. Use Flama for machine learning API deployment

    main
    Flama is a data-science oriented framework designed to rapidly build and deploy modern, robust machine learning (ML) APIs. It allows data scientists to turn ML models into asynchronous, auto-documented APIs quickly. It supports GraphQL, REST, and ML APIs and includes an intuitive CLI for automatic deployment of ML models.
  4. Use Greppo for geospatial dashboards

    main
    Greppo is a Python framework specifically for building geospatial dashboards and web applications. It provides a toolkit to integrate data, algorithms, visualizations, and UI interactivity. It includes APIs for updating backend variables, recomputing logic, and reflecting changes in the frontend via a data mutation hook.
  5. Pattern: Send eager responses from ASGI middleware

    main

    Middleware can intercept a request and return a response immediately without calling the underlying application. This is useful for redirects or authentication enforcement. You can use Starlette's RedirectResponse or other response classes and call them as ASGI applications by passing the scope, receive, and send arguments.

    from starlette.datastructures import URL
    from starlette.responses import RedirectResponse
    
    class RedirectsMiddleware:
        def __init__(self, app, path_mapping: dict):
            self.app = app
            self.path_mapping = path_mapping
    
        async def __call__(self, scope, receive, send):
            if scope["type"] != "http":
                await self.app(scope, receive, send)
                return
    
            url = URL(scope=scope)
    
            if url.path in self.path_mapping:
                url = url.replace(path=self.path_mapping[url.path])
                response = RedirectResponse(url, status_code=301)
                await response(scope, receive, send)
                return
    
            await self.app(scope, receive, send)
  6. Difference between handled exceptions and errors

    main

    Starlette distinguishes between handled exceptions and errors:

    1. Handled Exceptions: These are expected cases (like a 404) that are coerced into HTTP responses via the ExceptionMiddleware. By default, HTTPException is used for these.
    2. Errors: These are unexpected exceptions occurring within the application. They bubble up through the middleware stack. To handle these, you can register a handler for the Exception class or the 500 status code.

    Middleware Stack Order:

    • ServerErrorMiddleware (Returns 500 for server errors)
    • Installed middleware
    • ExceptionMiddleware (Deals with handled exceptions)
    • Router
    • Endpoints

    Note on BackgroundTasks: If an exception is raised within a BackgroundTask, the error handler will be called, but the response has already been sent to the client, so the handler's return value will be discarded.