Skip to main content

Routing extensions for Starlette.

Project description

from examples.dependencies import Variable

Starlette Dispatch

Routing extensions and dependency injection library for Starlette.

PyPI GitHub Libraries.io dependency status for latest release PyPI - Downloads GitHub Release Date

Installation

Install starlette_dispatch using PIP:

pip install starlette_dispatch

Features

  • Route groups. Group routes by common path prefix and common middleware.
  • Route method decorators. Convenient decorators for common HTTP methods.
  • Dependency injection. Route handlers can request dependencies by adding a parameter with the dependency type hint.
  • Backward compatible with Starlette. You can use it with your existing Starlette application.
  • No performance overhead. Dependency injection takes exact the same time as if you would write the handler manually.
  • Fully typed. Starlette Dispatch is fully typed and supports type hints.
  • Async support. Starlette Dispatch supports async handlers and async dependencies.

And the most important -- it does not erase route handler signature. You can compose it with any other decorators.

Quick start

Starlette Dispatch does not require any changes to your existing Starlette application. You can use it with your existing Starlette application.

Here is a simple snippet that demonstrates dependency injection and route group usage:

import typing

from starlette.applications import Starlette
from starlette.authentication import SimpleUser
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Route

from starlette_dispatch import RouteGroup, RequestDependency

admin_middleware = [
    Middleware(AuthenticationMiddleware, backend=...)
]
admin_routes = RouteGroup('/admin', middleware=admin_middleware)

CurrentUser = typing.Annotated[SimpleUser, RequestDependency(lambda r: r.user)]


async def index_view(request: Request, user: CurrentUser) -> JSONResponse:
    """This is your landing page."""
    return JSONResponse({'message': f'Hello, {user}!'})


@admin_routes.get('/')
async def admin_index_view(request: Request) -> JSONResponse:
    """This is your admin landing page."""
    return JSONResponse({'message': 'Hello, admin!'})


app = Starlette(
    routes=[
        Route('/', index_view),  # regular Starlette route
        *admin_routes,
    ]
)

Route groups

A route group is a way to group routes by common path prefix and common middleware. Instead of writing the same prefix for each route, you can define a group and add routes to it using convenient decorators.

Route groups support all common HTTP methods and add some extra helpers like get_or_post.

from starlette.requests import Request
from starlette.responses import JSONResponse

from starlette_dispatch import RouteGroup

group = RouteGroup('/group')


@group.get('/')
def my_view(request: Request) -> JSONResponse:
    return JSONResponse({'message': 'Hello, world!'})


@group.get_or_post('/')
def form_view(request: Request) -> JSONResponse:
    return JSONResponse({'message': 'Hello, world!'})

Multiple routes on a single handler

You can call route decorators multiple times on a single handler. This way you can share the same handler for multiple routes without creating a new handler.

from starlette.requests import Request
from starlette.responses import JSONResponse

from starlette_dispatch import RouteGroup, FromPath

group = RouteGroup('/group')


@group.get('/new')
@group.get('/edit/{id}')
def create_view(request: Request, id: FromPath[int | None]) -> JSONResponse:
    ...

Route injections

Each route handler can request a dependency by adding a parameter with the dependency type hint. The dependency will be properly resolved and injected into the handler on handler call. See more about dependency injection below.

For each injection Starlette Dispatch creates a resolver function. This means, it does not add a noticeable overhead to your application and takes exact the same time as if you would write the handler manually.

import typing
from starlette.requests import Request
from starlette.responses import JSONResponse

from starlette_dispatch import RouteGroup, VariableDependency


class User: ...


user = User()
CurrentUser = typing.Annotated[str, VariableDependency(user)]

group = RouteGroup('/')


@group.get('/')
def index_view(request: Request, user: CurrentUser) -> JSONResponse:
    return JSONResponse({'message': f'Hello, {user}!'})

Route middleware

Each route can have its own middleware.

If route group has middleware, it will be merged with route middleware. Route middleware has a higher priority.

import typing

from starlette.requests import Request
from starlette.responses import JSONResponse

from starlette_dispatch import RouteGroup, VariableDependency


class User: ...


user = User()
CurrentUser = typing.Annotated[str, VariableDependency(user)]

group = RouteGroup('/')


@group.get('/')
def my_view(request: Request, user: CurrentUser) -> JSONResponse:
    return JSONResponse({'message': f'Hello, {user}!'})

Dependency injection

In a nutshell, the dependency is a type, annotated with a value or a factory function that resolves to the value. The factory function is called dependency resolver.

Variable dependency

Variable dependency is a resolver that returns a simple value.

import typing

from starlette_dispatch import RouteGroup, VariableDependency

Value = typing.Annotated[str, VariableDependency('hello')]

group = RouteGroup('/')


@group.get('/')
def my_view(value: Value) -> None:
    assert value == 'hello'

Factory dependency

Factory dependency is a resolver that creates a value on each call. The result can be cached. The factory can have dependencies and can be async.

import typing

from starlette_dispatch import FactoryDependency, RouteGroup


def make_dependency():
    return 'hello'


async def async_dependency():
    return 'hello'


Value = typing.Annotated[str, FactoryDependency(make_dependency)]
AsyncValue = typing.Annotated[str, FactoryDependency(async_dependency)]
CachedValue = typing.Annotated[str, FactoryDependency(make_dependency, cached=True)]

group = RouteGroup('/')


@group.get('/')
def my_view(value: Value, async_value: AsyncValue, cached_value: CachedValue) -> None:
    assert value == 'hello'
    assert async_value == 'hello'
    assert cached_value == 'hello'

Factory function dependencies

The factory function itself can have dependencies. They are defined in the same way as regular dependencies.

import typing

from starlette_dispatch import FactoryDependency, RouteGroup


def parent_dependency():
    return 'hello'


ParentValue = typing.Annotated[str, FactoryDependency(parent_dependency)]


def make_dependency(parent: ParentValue):
    return parent + ' world'


Value = typing.Annotated[str, FactoryDependency(make_dependency)]

group = RouteGroup('/')


@group.get('/')
def my_view(value: Value) -> None:
    assert value == 'hello world'

Predefined dependencies

There are several predefined dependencies: starlette.requests.Request, starlette_dispatch.injections.DependencySpec.

Request is a Starlette request object and DependencySpec is a special object that contains meta information about the dependency. DependencySpec object is very useful in complex cases.

from starlette.requests import Request

from starlette_dispatch import DependencySpec


def make_dependency(request: Request, spec: DependencySpec):
    assert request  # Starlette request object
    assert spec.param_name  # name of the parameter
    assert spec.param_type  # type of the parameter
    assert spec.optional  # is the parameter optional
    assert spec.default  # default value of the parameter
    assert spec.annotation  # type annotation of the parameter

Request resolver

If your dependency available in the request object, instead of creating a factory function, you can use a RequestDependency resolver. It takes a function that accepts Request and DependencySpec (optionally) objects.

import typing
from starlette_dispatch import RequestDependency

# example dependency that resolves to a value from query parameter
Value = typing.Annotated[str, RequestDependency(lambda request, spec,: request.query_params['value'])]
NoSpecValue = typing.Annotated[str, RequestDependency(lambda request: request.query_params['value'])]

Custom resolver

You are not limited to predefined resolvers. You can create your own resolver by subclassing DependencyResolver and implementing the resolve method.

from starlette.requests import Request

from starlette_dispatch import DependencyResolver, DependencySpec


class MyResolver(DependencyResolver):
    async def resolve(self, request: Request, spec: DependencySpec):
        """Use request and spec objects to create a value."""
        return None

Contrib and support

Simple dependency definition

Instead of using resolver classes, you can use these shortcuts to define dependencies.

import typing

SimpleValueDependency = typing.Annotated[str, 'simple_value']
LambdaDependency = typing.Annotated[str, lambda: 'some value']
RequestOnlyLambdaDependency = typing.Annotated[str, lambda request: request.query_params['value']]
RequestAndSpecLambdaDependency = typing.Annotated[str, lambda request, spec: ...]

FromPath - inject path parameter as a dependency

from starlette_dispatch import FromPath, RouteGroup

group = RouteGroup('/')


@group.get('/{value}')
def my_view(value: FromPath[str]) -> None:
    assert value is not None

If path value does not exist in Request.path_parameters then it will fail with error. However, you can mark dependency as optional and then it will be None if path value does not exist.

from starlette_dispatch import FromPath, RouteGroup

group = RouteGroup('/')


def my_view(value: FromPath[str] | None) -> None:
    assert value is None

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

starlette_dispatch-0.24.0.tar.gz (10.8 kB view details)

Uploaded Source

Built Distribution

starlette_dispatch-0.24.0-py3-none-any.whl (9.8 kB view details)

Uploaded Python 3

File details

Details for the file starlette_dispatch-0.24.0.tar.gz.

File metadata

  • Download URL: starlette_dispatch-0.24.0.tar.gz
  • Upload date:
  • Size: 10.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.12.7 Linux/6.5.0-1025-azure

File hashes

Hashes for starlette_dispatch-0.24.0.tar.gz
Algorithm Hash digest
SHA256 85fc5254f5190a51472849d291247f97d3929e80d0342c509ea60595de807ad0
MD5 427b2fcbd61cc1d33c01f286d99e68b1
BLAKE2b-256 ce980b62390cde403cce912f0c2e2770229c44535ddebf37a57a22feed6a0d3e

See more details on using hashes here.

File details

Details for the file starlette_dispatch-0.24.0-py3-none-any.whl.

File metadata

File hashes

Hashes for starlette_dispatch-0.24.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2a3ad5cee2dbf32becac8e0d55f6663120c9d86447108be58e5d358304d6ca63
MD5 3cc9e9b139229d4d6e907a150e7c8570
BLAKE2b-256 0d5e17244430b8e373537dafc939865040579a660ee51520bf48bb5afe8d5085

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page