Skip to content

API Reference

Use this reference to look up class signatures, parameters, and methods. For examples that connect these APIs in an application, start with serving a site, rendering Markdown pages, or running named SQL queries.

Static Files

StaticFiles

StaticFiles(
    *,
    loader: BaseLoader,
    html: bool = False,
    check_dir: bool = True,
    follow_symlink: bool = False,
    max_age: int | None = 3600,
    template_cache_control: str | None = None,
    global_vars: dict[str, Any] | None = None,
    filters: dict[str, Callable[..., Any]] | None = None,
    extensions: Sequence[type[Extension] | str] = (),
    fragments: Contexts | None = None,
    page_context: Sequence[Route] = (),
    query_runner: QueryRunner | None = None,
)

A raw ASGI app that serves files from a Jinja2 loader's directories.

Files ending in .jinja or .j2 are rendered as templates, markdown is rendered to HTML, and everything else is served as-is with ETag/Last-Modified support; see the module docstring for the full template surface. Owns the resources it renders through — the Jinja Environment, the MarkdownIt instance, and the optional QueryRunner — all constructed once in init.

The runner is held privately: templates can run a declared query through fetch() but cannot reach the runner itself. When no runner is configured, fetch() yields empty results rather than failing, so a site with no database still serves.

Two folders under a served directory are discovered rather than declared: shortcodes/ contributes its template files as Jinja tags, and fragments/ contributes its region templates as htmx regions. Those regions are self.fragments, which this app serves under its own /fragment/<name> and an HTMXResponse anywhere in the app finds to cascade. The fragments argument names the context functions of the regions that want one; a region with none renders from its template alone.

Wire the serving app from a loader and its rendering resources.

loader supplies the search directories files are served from. html enables directory index and 404.html resolution. check_dir makes the first request verify the directories exist (raising rather than 404ing); follow_symlink permits symlinked paths to resolve outside the realpath of the served directory. max_age and template_cache_control set the Cache-Control headers for static files and rendered templates respectively (see the module docstring). global_vars and filters are merged into the Jinja environment. query_runner executes template queries; when None, fetch() returns empty results.

extensions are your own Jinja extensions (a class or an import path), registered alongside the ones this class always wires: the {% sql %} tag, the {% markdown %} tag, the shortcode tags, and the region tags.

page_context gives a page variables of its own: each Route names a URL and an async function that returns the variables the page at that URL renders with. See starlette_templates.context.

Every region template under a served directory's fragments/ becomes a region and a Jinja tag of its own name, whether or not fragments is given, and the app needs no other wiring for the cascade. fragments supplies the context functions of the regions that want one: a module holding them, a mapping of name to function, a function on its own, or any mix of those in a sequence. See starlette_templates.htmx.

Raises:

  • ValueError

    for any discovery problem in a shortcodes/ or fragments/ folder — a shortcode file whose name cannot become a tag, a region template that declares no triggers, a region two sources both supply a function for, or a name two directories both claim. Also when a page_context entry carries no context function to call.

  • TypeError

    if a fragments source is neither a module, a mapping, nor a function.

QueryRunner

Executes a named query and returns its rows for binding into a template.

StaticFiles depends on this protocol, not a concrete engine (§4): the app supplies an implementation, and tests supply a fake. The single method is awaited inline by the template's fetch() call, so the rows are available where fetch() is used.

Methods:

  • run

    Execute query, binding its :name placeholders from params, return the rows.

run async

run(query: Query, params: Mapping[str, Any]) -> list[Row]

Execute query, binding its :name placeholders from params, return the rows.

params carries the values for any named placeholders in the SQL (the runner is responsible for binding them out-of-band, never interpolating).

run() is awaited inside the request's cancellation scope, so when the client disconnects the CancelledError propagates here through the await — a runner that holds an engine-side query open should cancel it off that, the same way any async call below a cancelled scope unwinds. StaticFiles passes no separate cancellation handle: it is a raw ASGI app and has none to give.

Raises:

Query dataclass

Query(name: str, database: str | None, sql: str)

A named SQL query declared in a template, awaiting execution.

Declared by a {% sql name [from database] %} tag or an sql-info fenced code block; collected into a QuerySet and run only when a template calls fetch() on it. database is None when the declaration named no database. sql is the raw query text with its :name placeholders left unbound — the runner binds them out-of-band, never by interpolation.

Attributes:

name instance-attribute

name: str

database instance-attribute

database: str | None

sql instance-attribute

sql: str

QuerySet dataclass

QuerySet(queries: list[Query] = list())

The named queries declared in one template render, keyed by name.

Populated as {% sql %} tags and sql-fenced blocks are encountered, then read back by fetch() when a query runs. Exposed to templates as queries, where a query is reached by name as an attribute (queries.stations) or via get(). A name may appear more than once across databases; get() and by_database() disambiguate by database.

Methods:

Attributes:

queries class-attribute instance-attribute

queries: list[Query] = field(default_factory=list)

get

get(name: str, database: str | None = None) -> Query | None

by_database

by_database(database: str) -> list[Query]

QueryExecutionError

QueryExecutionError(query: Query, message: str)

Raised when a QueryRunner fails to execute a template's query.

Carries the offending query so the render boundary can report which named query failed without the runner's engine-specific exception leaking through.

Attributes:

query instance-attribute

query = query

jsonify

jsonify(data: Any, indent: int | None = None) -> Markup

Convert data to a Markup-safe JSON string for embedding in HTML templates.

Uses Pydantic's serialization to handle complex types like datetime, Decimal, and BaseModel instances.

markdown_extension

markdown_extension(
    md: MarkdownIt,
) -> type[MarkdownExtension]

Build a MarkdownExtension subclass whose {% markdown %} tag renders through md.

MarkdownExtension

Jinja2 extension for {% markdown %}...{% endmarkdown %} blocks.

The body is Jinja first and markdown second. It renders like any other template body — variables, filters, shortcodes, region tags — and the result is converted to HTML. Under autoescape a variable is escaped before the conversion, so a value cannot inject markup or markdown of its own.

The template's own indentation comes off the body first (the common prefix of its lines), so a block indented to line up with the HTML around it is not read as an indented code block.

An sql fence inside the block declares into the same QuerySet the page uses, the way one in an included markdown file does, and produces no output.

Do not register this base class directly — it has no renderer. Use :func:markdown_extension to build a subclass bound to a MarkdownIt.

Markdown Pages

MarkdownPage dataclass

MarkdownPage(body: str, page: dict[str, Any] = dict())

A markdown source split into the variables it declares and the body that renders.

page is the frontmatter as written, reached in a template as page.title. It is empty for a file that opens with no fence. body is everything below the closing fence, and is the whole source when there is no frontmatter, so rendering body never loses content.

Attributes:

  • body (str) –
  • page (dict[str, Any]) –
  • layout (str | None) –

    The template named by the layout key, or None for a page that wraps itself.

body instance-attribute

body: str

page class-attribute instance-attribute

page: dict[str, Any] = field(default_factory=dict)

layout property

layout: str | None

The template named by the layout key, or None for a page that wraps itself.

split_frontmatter

split_frontmatter(
    source: str, name: str = "<markdown>"
) -> MarkdownPage

Split source into its frontmatter variables and the markdown below them.

The fence has to be the first line, so only a file written to carry frontmatter is read as carrying it. name names the file in any error raised.

Raises:

  • ValueError

    if the file opens a frontmatter block and never closes it, or if load_frontmatter rejects the block.

load_frontmatter

load_frontmatter(block: str, name: str) -> dict[str, Any]

Read a frontmatter block as the mapping of variables it declares.

name names the file in any error raised, since the block itself carries nothing to identify it by.

Raises:

  • ValueError

    if the block is not valid YAML, if it holds anything but a mapping, or if its layout is not the name of a template.

Page Context

ContextRoutes

ContextRoutes(routes: Sequence[Route] = ())

The context functions of a site's pages, keyed by the path each one answers.

Built once at wiring time by StaticFiles, from its page_context argument, and read-only from the first request onward, so every concurrent request shares one instance without a lock.

Hold the routes, after checking each one carries a context function.

Raises:

  • ValueError

    if a route has no endpoint to call — a Mount or a WebSocketRoute rather than a Route. Wiring fails here rather than at the render of whatever page the route was meant for.

Methods:

  • variables

    Return the variables every route matching this request supplies.

Attributes:

routes instance-attribute

routes = tuple(routes)

variables async

variables(request: Request) -> dict[str, Any]

Return the variables every route matching this request supplies.

Fills in request.path_params from each match before that route's function runs, so a function reads the parameters of its own path. Merges in declaration order, so a later route wins a name an earlier route also set.

Raises:

  • TypeError

    if a matching route's context function is not async.

context_of async

context_of(
    route: Route, request: Request
) -> Mapping[str, Any]

Await the context function of route and return the variables it supplies.

Raises:

  • TypeError

    if the function is not async. A synchronous one returns the mapping rather than an awaitable, which would otherwise fail deep in the render with nothing to say which route was at fault.

Shortcodes

shortcode_extension

shortcode_extension(
    folder: str | Path,
    suffixes: str | Sequence[str] = SHORTCODE_SUFFIXES,
) -> type[ShortcodeExtension]

Build a ShortcodeExtension subclass whose tags mirror the files in folder.

Raises:

  • ValueError

    for any discovery problem — see :func:discover_shortcode_templates.

discover_shortcode_templates

discover_shortcode_templates(
    folder: Path,
    suffixes: str | Sequence[str] = SHORTCODE_SUFFIXES,
) -> dict[str, Path]

Map normalized tag name -> template path for every template file in folder.

Raises:

  • ValueError

    if the folder does not exist, contains no matching files, a file name normalizes to something that is not a usable tag (empty, not an identifier, a reserved Jinja tag), two file names normalize to the same tag (including two spellings of one name, such as note.html beside note.jinja), or a tag shadows another tag's end tag.

normalize_shortcode_name

normalize_shortcode_name(name: str) -> str

Normalize a template file name to a tag name, the way slugify does but with underscores.

Compatibility-decomposes unicode and drops what has no ASCII equivalent, lowercases, replaces every run of non-alphanumeric characters with a single underscore, and strips leading/trailing underscores. Returns "" when nothing survives; the result is not guaranteed to be a valid identifier (e.g. it may start with a digit) — callers must check.

HTMX Fragments

HTMXResponse

HTMXResponse(
    content: str = "",
    trigger: str | Sequence[str] = (),
    status_code: int = 200,
    fragments: FragmentRegistry | None = None,
)

An HTML response that says what happened, and carries the cascade it implies.

content is the handler's own answer, what goes into the element that made the request. trigger names what happened. Every region those triggers make stale is rendered and appended to this response as an out-of-band swap, so one click updates every part of the page that displays what changed:

return HTMXResponse("Added.", trigger="cart.changed")

The regions come from the StaticFiles mounted in the app this request reached, found by registry_in. An app that serves a site with regions therefore wires nothing: fragments=store on StaticFiles is the whole setup. Pass fragments to name the registry instead — for a test, or an app whose regions are not reachable from its routes.

The work happens in __call__, which is async, rather than in __init__, which cannot be. Nothing is buffered and no head is rewritten: the body is still this object's own attribute when the regions are appended to it.

A trigger no region wants leaves the response untouched, so a handler can still fire a purely client-side htmx event.

Methods:

  • cascade

    Append the stale regions to this response's body, and correct its head.

cascade async

cascade(
    fragments: FragmentRegistry, request: Request
) -> None

Append the stale regions to this response's body, and correct its head.

Regions are independent by construction, so this costs the slowest render rather than the sum of them.

Raises:

  • ValueError

    if a region renders markup that could not be swapped — no root element, or one whose id is not the region's name.

FragmentRegistry

FragmentRegistry(
    env: Environment,
    template_dir: str = TEMPLATE_DIR,
    path_prefix: str = DEFAULT_PREFIX,
    base_context: Context | None = None,
)

The page's re-renderable regions, keyed by what makes them stale.

Built once at wiring time — by StaticFiles, which discovers the regions and publishes the registry as its fragments attribute — handed to the middleware, and read-only from the first request onward, so every concurrent request shares one instance without a lock. Registering a region after the app starts serving is not supported.

Renders through the Jinja environment it is given, which must have enable_async=True — regions are rendered concurrently and awaited. The one StaticFiles builds is already set up for this.

A fragment's name names its template under template_dir, names its context function when it has one, and must be the id of the element that template returns — that id is what htmx matches against the live DOM, so a mismatch means the swap silently lands nowhere. This is checked at render time and raises rather than failing quietly.

base_context supplies the variables every region renders with whether or not it has a context function of its own — queries is what StaticFiles puts there, which is what lets a region declare and run its own query. It is awaited once per region render, so each region gets its own, and it is applied last: a context function does not overwrite the library's own names.

Methods:

  • add

    Register a re-renderable region of the page.

  • stale

    Return the regions the given triggers make stale, in registration order.

  • discover

    Register every region template found under the served directories.

  • template_path

    Return the loader name of a region template file: fragments/cart_badge.html.jinja.

  • template_for

    Return the template a region renders, whichever suffix its author gave it.

  • render

    Render one registered fragment, with no out-of-band marker on it.

  • url_for

    Return where a fragment answers its own request.

  • name_at

    Return the fragment a path names, or None if it names none.

  • wrap

    Return a fragment's first-paint markup, ready to drop into a page.

Attributes:

env instance-attribute

env = env

template_dir instance-attribute

template_dir = template_dir

path_prefix instance-attribute

path_prefix = path_prefix

base_context instance-attribute

base_context = base_context

by_trigger instance-attribute

by_trigger: dict[str, list[Fragment]] = {}

by_name instance-attribute

by_name: dict[str, Fragment] = {}

add

add(
    context: Context | None = None,
    *triggers: str,
    pull: bool = False,
    name: str | None = None,
    template: str | None = None,
) -> None

Register a re-renderable region of the page.

A context function stays an ordinary function — nothing wraps it — which is how the page's first paint reuses the same function that produces the out-of-band update.

Parameters:

  • context (Context | None, default: None ) –

    the async function returning the template context, or None for a region whose template says all it needs. Its __name__ is the fragment's name, which names both the template and the id of the element that template must return, so name is required without it.

  • *triggers (str, default: () ) –

    the trigger names that make this region stale. A region that displays two things can name both.

  • pull (bool, default: False ) –

    fetch this region separately instead of appending it to the response. Use for a region slow enough that you do not want its latency on the critical path of the click.

  • name (str | None, default: None ) –

    the region's name, when it is not the function's. Discovery passes the template's name, since the template is what renders.

  • template (str | None, default: None ) –

    the template to render, when it is not the one template_for finds. Discovery passes the file it found.

Raises:

  • ValueError

    if the name is already registered, since the name is a DOM id and a duplicate would make the swap ambiguous, or if neither a context function nor a name says what the region is called.

stale

stale(triggers: Sequence[str]) -> list[Fragment]

Return the regions the given triggers make stale, in registration order.

Deduplicated by name: a fragment watching two of the fired triggers appears once, and the order is stable so the same click always produces the same body.

discover

discover(
    directories: Sequence[str], contexts: Contexts = ()
) -> None

Register every region template found under the served directories.

Point it at a folder and each region template in it becomes a region: the file name — minus any of TEMPLATE_SUFFIXES — is the region's name, and the template says what makes it stale. A region that wants variables Python has to produce gets a function of its name from contexts — a module holding them, a mapping of name to function, a function on its own, or any mix of those in a sequence; a region with none renders with empty_context. StaticFiles calls this for you.

Nothing lists the regions — adding one means adding a template, and no line anywhere else.

Raises:

  • ValueError

    if two sources offer a context function of one name, if two templates are the same region under different suffixes, or if a template declares no triggers. A region that can never go stale is not a region, and either ambiguity would make the page's swap ambiguous, so discovery fails loudly rather than skipping.

  • TypeError

    if a source is none of the three kinds a context comes from.

template_path

template_path(filename: str) -> str

Return the loader name of a region template file: fragments/cart_badge.html.jinja.

template_for

template_for(name: str) -> str

Return the template a region renders, whichever suffix its author gave it.

A region template may be spelled any of TEMPLATE_SUFFIXES, so the environment's loader is asked which one exists — once, at registration, rather than on every render. Falls back to the first spelling when the loader has none of them, so the render raises a TemplateNotFound that names what was looked for.

render async

render(name: str, request: Request) -> str

Render one registered fragment, with no out-of-band marker on it.

Raises:

  • KeyError

    if no fragment by that name is registered.

  • TemplateNotFound

    if the fragment has no template of its name.

url_for

url_for(name: str, root_path: str = '') -> str

Return where a fragment answers its own request.

root_path is the prefix the serving app is mounted under, which the page passes from its own request. A site mounted at /shop serves its regions at /shop/fragment/<name>, so that is what a pull region's markup must point at.

name_at

name_at(path: str) -> str | None

Return the fragment a path names, or None if it names none.

Returns None for an unregistered name too, so a path that merely looks like a fragment URL falls through to the app and gets its ordinary 404.

wrap

wrap(name: str, html: str, root_path: str = '') -> Markup

Return a fragment's first-paint markup, ready to drop into a page.

A push fragment is returned untouched. A pull fragment is wrapped in the element that re-fetches it when any of its triggers fires, from where the page's own root_path says regions are served.

HTMXMiddleware

HTMXMiddleware(app: ASGIApp, fragments: FragmentRegistry)

Cascades responses that are not HTMXResponses, for the apps that need it.

Most apps need none of this. An HTMXResponse carries its own cascade and the mounted StaticFiles serves a pull region's own request, so a site with regions wires nothing. Install this to cascade a response of some other class that carries an HX-Trigger header — one another library built, or a header set above the handler.

Doing it here means intercepting the response as ASGI messages: appending to a body means rewriting its Content-Length, so the head is held back and the chunks collected. That is the cost HTMXResponse avoids by appending to a body it still owns, and the reason this is the exception rather than the path.

Install it innermost — before any middleware that rewrites the body, such as GZip — so that layer sees the finished body with the swaps already in it. A response that already cascaded itself is left alone, so the two layers never both append the same regions.

It also answers GET /fragment/<name> for any registered fragment, the way StaticFiles does, so a pull region works in an app that mounts no site. A path under that prefix naming nothing registered falls through to the app and 404s normally.

A context function is handed a request built from the scope. It can read the app, the path, and the headers; it must not read the request body, which the handler has already consumed.

Methods:

  • serve

    Answer a pull fragment's own request, with no out-of-band marker on it.

Attributes:

app instance-attribute

app = app

fragments instance-attribute

fragments = fragments

serve async

serve(
    name: str, scope: Scope, receive: Receive, send: Send
) -> None

Answer a pull fragment's own request, with no out-of-band marker on it.

Fragment dataclass

Fragment(
    name: str,
    context: Context,
    triggers: tuple[str, ...],
    pull: bool,
    template: str,
)

A registered region. Built by FragmentRegistry.add; you never construct one.

Attributes:

name instance-attribute

name: str

context instance-attribute

context: Context

triggers instance-attribute

triggers: tuple[str, ...]

pull instance-attribute

pull: bool

template instance-attribute

template: str

HTML in Python

ht

Factory for HTML elements, used as ht.<tag>(...).

Accessing any attribute (ht.div, ht.button) yields a new Element with that tag, which is then called with children and attributes. Also exposes the renderers render_element and render_document.

ht.div(id="my-div", classes=["container", "content"], style={"color": "red"})
ht.button(type="submit", classes=["btn", "btn-primary"])
ht.h1("Hello World")

Methods:

  • render_element

    Render an element (or string, callable, or get_element object) to HTML.

  • render_document

    Render a full HTML document (doctype, head, body) to a string.

render_element classmethod

render_element(element: ElementChild) -> str

Render an element (or string, callable, or get_element object) to HTML.

The tree is walked iteratively with an explicit stack, so nesting depth is bounded by memory rather than by Python's recursion limit.

Callables are evaluated until a value remains; an object with get_element() is resolved to its Element; None renders to "". An error raised by a child is logged and treated as empty rather than aborting the whole document.

Raises:

  • TypeError

    if the resolved value is not an Element, string, or number.

  • CycleError

    if the element tree contains a cycle.

render_document classmethod

render_document(
    body: Element,
    head: list[Element] | None = None,
    title: str | None = None,
    body_kwargs: dict[str, Any] | None = None,
    head_kwargs: dict[str, Any] | None = None,
    html_kwargs: dict[str, Any] | None = None,
) -> str

Render a full HTML document (doctype, head, body) to a string.

head is a list of elements appended after the default charset/viewport meta tags. title, when given, adds a . The <code>*_kwargs</code> mappings set attributes on the html/head/body tags.</p> <p><span class="doc-section-title">Raises:</span></p> <ul> <li class="doc-section-item field-body"> <code><span title="TypeError">TypeError</span></code> – <div class="doc-md-description"> <p>if <code>body</code> is not an Element/str/get_element object, or <code>head</code> is not a list.</p> </div> </li> </ul> <div class="highlight"><pre><span></span><code><span class="n">ht</span><span class="o">.</span><span class="n">render_document</span><span class="p">(</span><span class="n">ht</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="s2">"Hello world"</span><span class="p">))</span> <span class="c1"># <!DOCTYPE html><html><head>...</head><body><div>Hello world</div></body></html></span> </code></pre></div> </div> </div> </div> </div> </div> <div class="doc doc-object doc-class"> <h2 id="starlette_templates.hypertext.Element" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-class"></code> <span class="doc doc-object-name doc-class-name">Element</span> </h2> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">Element</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="n"><span title="starlette_templates.hypertext.ElementChild">ElementChild</span></span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">:</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">)</span> </code></pre></div> <div class="doc doc-contents first"> <p>A single HTML element: a tag, an ordered list of children, and attributes.</p> <p>Build with <code>ht.<tag>(...)</code> rather than constructing directly. Children and attributes are added through the <code>+</code>/<code>+=</code> operators, <code>__call__</code>, and the append/extend/insert methods; every mutating method returns self so calls chain. <code>classes</code> is always normalized to a list of strings.</p> <p><span class="doc-section-title">Methods:</span></p> <ul> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" set_attrs (starlette_templates.hypertext.Element.set_attrs)" href="#starlette_templates.hypertext.Element.set_attrs">set_attrs</a></code></b> – <div class="doc-md-description"> <p>Set attributes, overwriting on duplicate keys; <code>classes</code> is merged into the list.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" merge_attrs (starlette_templates.hypertext.Element.merge_attrs)" href="#starlette_templates.hypertext.Element.merge_attrs">merge_attrs</a></code></b> – <div class="doc-md-description"> <p>Merge attributes, combining duplicate keys into a list rather than overwriting.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" has_classes (starlette_templates.hypertext.Element.has_classes)" href="#starlette_templates.hypertext.Element.has_classes">has_classes</a></code></b> – <div class="doc-md-description"> <p>Return True if the element carries every one of the given classes.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" add_classes (starlette_templates.hypertext.Element.add_classes)" href="#starlette_templates.hypertext.Element.add_classes">add_classes</a></code></b> – <div class="doc-md-description"> <p>Add classes to the element, de-duplicated in order.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" remove_classes (starlette_templates.hypertext.Element.remove_classes)" href="#starlette_templates.hypertext.Element.remove_classes">remove_classes</a></code></b> – <div class="doc-md-description"> <p>Remove classes from the element, preserving the order of those that remain.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" append (starlette_templates.hypertext.Element.append)" href="#starlette_templates.hypertext.Element.append">append</a></code></b> – <div class="doc-md-description"> <p>Add children to the element.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" extend (starlette_templates.hypertext.Element.extend)" href="#starlette_templates.hypertext.Element.extend">extend</a></code></b> – <div class="doc-md-description"> <p>Add several children to the element.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" insert (starlette_templates.hypertext.Element.insert)" href="#starlette_templates.hypertext.Element.insert">insert</a></code></b> – <div class="doc-md-description"> <p>Insert children at <code>index</code>, in order, with the usual child coercion.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" to_string (starlette_templates.hypertext.Element.to_string)" href="#starlette_templates.hypertext.Element.to_string">to_string</a></code></b> – <div class="doc-md-description"> <p>Render the element to an HTML string.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" render (starlette_templates.hypertext.Element.render)" href="#starlette_templates.hypertext.Element.render">render</a></code></b> – <div class="doc-md-description"> <p>Render the element to a Markup-wrapped HTML string.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" pipe (starlette_templates.hypertext.Element.pipe)" href="#starlette_templates.hypertext.Element.pipe">pipe</a></code></b> – <div class="doc-md-description"> <p>Apply <code>function(self, *args, **kwargs)</code> and return its result, for chaining.</p> </div> </li> </ul> <p><span class="doc-section-title">Attributes:</span></p> <ul> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" tag instance-attribute (starlette_templates.hypertext.Element.tag)" href="#starlette_templates.hypertext.Element.tag">tag</a></code></b> (<code><span title="str">str</span></code>) – <div class="doc-md-description"> <p>The tag name of the element.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" children instance-attribute (starlette_templates.hypertext.Element.children)" href="#starlette_templates.hypertext.Element.children">children</a></code></b> (<code><span title="list">list</span>[<span title="typing.Any">Any</span>]</code>) – <div class="doc-md-description"> <p>List of child elements.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" attributes instance-attribute (starlette_templates.hypertext.Element.attributes)" href="#starlette_templates.hypertext.Element.attributes">attributes</a></code></b> (<code><span title="dict">dict</span>[<span title="str">str</span>, <span title="typing.Any">Any</span>]</code>) – <div class="doc-md-description"> <p>Dictionary of attributes.</p> </div> </li> </ul> <div class="doc doc-children"> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.hypertext.Element.tag" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">tag</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">tag</span><span class="p">:</span> <span class="n"><span title="str">str</span></span> <span class="o">=</span> <span class="s1">'div'</span> </code></pre></div> <div class="doc doc-contents "> <p>The tag name of the element.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.hypertext.Element.children" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">children</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">children</span><span class="p">:</span> <span class="n"><span title="list">list</span></span><span class="p">[</span><span class="n"><span title="typing.Any">Any</span></span><span class="p">]</span> <span class="o">=</span> <span class="p">[]</span> </code></pre></div> <div class="doc doc-contents "> <p>List of child elements.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.hypertext.Element.attributes" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">attributes</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">attributes</span><span class="p">:</span> <span class="n"><span title="dict">dict</span></span><span class="p">[</span><span class="n"><span title="str">str</span></span><span class="p">,</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span> </code></pre></div> <div class="doc doc-contents "> <p>Dictionary of attributes.</p> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.set_attrs" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">set_attrs</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">set_attrs</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">:</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">)</span> <span class="o">-></span> <span class="n"><span title="typing_extensions.Self">Self</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Set attributes, overwriting on duplicate keys; <code>classes</code> is merged into the list.</p> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.merge_attrs" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">merge_attrs</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">merge_attrs</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">:</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">)</span> <span class="o">-></span> <span class="n"><span title="typing_extensions.Self">Self</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Merge attributes, combining duplicate keys into a list rather than overwriting.</p> <div class="highlight"><pre><span></span><code><span class="n">ht</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="n">classes</span><span class="o">=</span><span class="p">[</span><span class="s2">"container"</span><span class="p">])</span><span class="o">.</span><span class="n">merge_attrs</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s2">"my-div"</span><span class="p">,</span> <span class="n">classes</span><span class="o">=</span><span class="p">[</span><span class="s2">"content"</span><span class="p">])</span> </code></pre></div> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.has_classes" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">has_classes</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">has_classes</span><span class="p">(</span><span class="o">*</span><span class="n">classes</span><span class="p">:</span> <span class="n"><span title="str">str</span></span><span class="p">)</span> <span class="o">-></span> <span class="n"><span title="bool">bool</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Return True if the element carries every one of the given classes.</p> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.add_classes" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">add_classes</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">add_classes</span><span class="p">(</span><span class="o">*</span><span class="n">classes</span><span class="p">:</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">)</span> <span class="o">-></span> <span class="n"><span title="typing_extensions.Self">Self</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Add classes to the element, de-duplicated in order.</p> <p>A single callable replaces the class list wholesale and is resolved at render time, so it can reflect state that changes between renders.</p> <div class="highlight"><pre><span></span><code><span class="n">ht</span><span class="o">.</span><span class="n">div</span><span class="p">()</span><span class="o">.</span><span class="n">add_classes</span><span class="p">(</span><span class="s2">"container"</span><span class="p">,</span> <span class="s2">"row"</span><span class="p">)</span> <span class="n">ht</span><span class="o">.</span><span class="n">div</span><span class="p">()</span><span class="o">.</span><span class="n">add_classes</span><span class="p">(</span><span class="k">lambda</span><span class="p">:</span> <span class="s2">"active"</span> <span class="k">if</span> <span class="n">is_active</span><span class="p">()</span> <span class="k">else</span> <span class="s2">""</span><span class="p">)</span> </code></pre></div> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.remove_classes" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">remove_classes</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">remove_classes</span><span class="p">(</span><span class="o">*</span><span class="n">classes</span><span class="p">:</span> <span class="n"><span title="str">str</span></span><span class="p">)</span> <span class="o">-></span> <span class="n"><span title="typing_extensions.Self">Self</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Remove classes from the element, preserving the order of those that remain.</p> <div class="highlight"><pre><span></span><code><span class="n">ht</span><span class="o">.</span><span class="n">div</span><span class="p">()</span><span class="o">.</span><span class="n">remove_classes</span><span class="p">(</span><span class="s2">"container"</span><span class="p">,</span> <span class="s2">"row"</span><span class="p">)</span> </code></pre></div> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.append" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">append</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">append</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="n"><span title="starlette_templates.hypertext.ElementChild">ElementChild</span></span><span class="p">)</span> <span class="o">-></span> <span class="n"><span title="typing_extensions.Self">Self</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Add children to the element.</p> <div class="highlight"><pre><span></span><code><span class="n">ht</span><span class="o">.</span><span class="n">div</span><span class="p">()</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">"Hello world"</span><span class="p">)</span> </code></pre></div> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.extend" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">extend</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">extend</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="n"><span title="starlette_templates.hypertext.ElementChild">ElementChild</span></span><span class="p">)</span> <span class="o">-></span> <span class="n"><span title="typing_extensions.Self">Self</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Add several children to the element.</p> <div class="highlight"><pre><span></span><code><span class="n">ht</span><span class="o">.</span><span class="n">div</span><span class="p">()</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="s2">"Hello"</span><span class="p">,</span> <span class="s2">"world"</span><span class="p">)</span> </code></pre></div> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.insert" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">insert</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">insert</span><span class="p">(</span><span class="n">index</span><span class="p">:</span> <span class="n"><span title="int">int</span></span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="n"><span title="starlette_templates.hypertext.ElementChild">ElementChild</span></span><span class="p">)</span> <span class="o">-></span> <span class="n"><span title="typing_extensions.Self">Self</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Insert children at <code>index</code>, in order, with the usual child coercion.</p> <div class="highlight"><pre><span></span><code><span class="n">ht</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="s2">"World"</span><span class="p">)</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="s2">"Hello "</span><span class="p">)</span> </code></pre></div> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.to_string" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">to_string</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">to_string</span><span class="p">()</span> <span class="o">-></span> <span class="n"><span title="str">str</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Render the element to an HTML string.</p> <div class="highlight"><pre><span></span><code><span class="n">ht</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="s2">"Hello world"</span><span class="p">)</span><span class="o">.</span><span class="n">to_string</span><span class="p">()</span> <span class="c1"># '<div>Hello world</div>'</span> </code></pre></div> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.render" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">render</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">render</span><span class="p">()</span> <span class="o">-></span> <span class="n"><span title="markupsafe.Markup">Markup</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Render the element to a Markup-wrapped HTML string.</p> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Element.pipe" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">pipe</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">pipe</span><span class="p">(</span> <span class="n">function</span><span class="p">:</span> <span class="n"><span title="typing.Callable">Callable</span></span><span class="p">[</span><span class="o">...</span><span class="p">,</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">],</span> <span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">:</span> <span class="n"><span title="typing.Any">Any</span></span> <span class="p">)</span> <span class="o">-></span> <span class="n"><span title="typing.Any">Any</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Apply <code>function(self, *args, **kwargs)</code> and return its result, for chaining.</p> <div class="highlight"><pre><span></span><code><span class="k">def</span><span class="w"> </span><span class="nf">add_prefix</span><span class="p">(</span><span class="n">element</span><span class="p">,</span> <span class="n">prefix</span><span class="p">):</span> <span class="k">return</span> <span class="n">element</span><span class="o">.</span><span class="n">add_classes</span><span class="p">(</span><span class="sa">f</span><span class="s2">"</span><span class="si">{</span><span class="n">prefix</span><span class="si">}</span><span class="s2">-class"</span><span class="p">)</span> <span class="n">ht</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="s2">"Hello world"</span><span class="p">)</span><span class="o">.</span><span class="n">pipe</span><span class="p">(</span><span class="n">add_prefix</span><span class="p">,</span> <span class="s2">"my-prefix"</span><span class="p">)</span> </code></pre></div> </div> </div> </div> </div> </div> <div class="doc doc-object doc-class"> <h2 id="starlette_templates.hypertext.Document" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-class"></code> <span class="doc doc-object-name doc-class-name">Document</span> </h2> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">Document</span><span class="p">(</span> <span class="o">*</span><span class="n">args</span><span class="p">:</span> <span class="n"><span title="starlette_templates.hypertext.ElementChild">ElementChild</span></span><span class="p">,</span> <span class="n">page_title</span><span class="p">:</span> <span class="n"><span title="str">str</span></span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">headers</span><span class="p">:</span> <span class="n"><span title="typing.Mapping">Mapping</span></span><span class="p">[</span><span class="n"><span title="str">str</span></span><span class="p">,</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">]</span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">status_code</span><span class="p">:</span> <span class="n"><span title="int">int</span></span> <span class="o">=</span> <span class="mi">200</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">:</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">,</span> <span class="p">)</span> </code></pre></div> <div class="doc doc-contents first"> <p>An HTML document that is also an ASGI app, so a handler can return it directly.</p> <p>A subclass of Element: children added to the Document become the body's children, and its attributes become the body's attributes when rendered. Owns pre-built <code>title</code>, <code>head</code>, <code>body</code>, and <code>html</code> elements.</p> <p>Build a document with an optional title and the response metadata for ASGI use.</p> <p><code>page_title</code> sets the <title>; <code>headers</code> and <code>status_code</code> are used when the document is served as an ASGI response.</p> <p><span class="doc-section-title">Methods:</span></p> <ul> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" get_element (starlette_templates.hypertext.Document.get_element)" href="#starlette_templates.hypertext.Document.get_element">get_element</a></code></b> – <div class="doc-md-description"> <p>Assemble and return the document as its <code><html></code> Element.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" to_string (starlette_templates.hypertext.Document.to_string)" href="#starlette_templates.hypertext.Document.to_string">to_string</a></code></b> – <div class="doc-md-description"> <p>Render the document to an HTML string, prefixed with the doctype.</p> </div> </li> </ul> <p><span class="doc-section-title">Attributes:</span></p> <ul> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" page_title instance-attribute (starlette_templates.hypertext.Document.page_title)" href="#starlette_templates.hypertext.Document.page_title">page_title</a></code></b> (<code><span title="str">str</span> | None</code>) – <div class="doc-md-description"> <p>The title of the page.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" headers instance-attribute (starlette_templates.hypertext.Document.headers)" href="#starlette_templates.hypertext.Document.headers">headers</a></code></b> (<code><span title="typing.Mapping">Mapping</span>[<span title="str">str</span>, <span title="typing.Any">Any</span>] | None</code>) – <div class="doc-md-description"> <p>Response headers.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" status_code instance-attribute (starlette_templates.hypertext.Document.status_code)" href="#starlette_templates.hypertext.Document.status_code">status_code</a></code></b> (<code><span title="int">int</span></code>) – <div class="doc-md-description"> <p>Response status code.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" title instance-attribute (starlette_templates.hypertext.Document.title)" href="#starlette_templates.hypertext.Document.title">title</a></code></b> – <div class="doc-md-description"> <p>Document title element.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" head instance-attribute (starlette_templates.hypertext.Document.head)" href="#starlette_templates.hypertext.Document.head">head</a></code></b> (<code><a class="autorefs autorefs-internal" title=" Element (starlette_templates.hypertext.Element)" href="#starlette_templates.hypertext.Element">Element</a></code>) – <div class="doc-md-description"> <p>The head element.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" body instance-attribute (starlette_templates.hypertext.Document.body)" href="#starlette_templates.hypertext.Document.body">body</a></code></b> – <div class="doc-md-description"> <p>The body element.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" html instance-attribute (starlette_templates.hypertext.Document.html)" href="#starlette_templates.hypertext.Document.html">html</a></code></b> – <div class="doc-md-description"> <p>The html element.</p> </div> </li> </ul> <div class="doc doc-children"> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.hypertext.Document.page_title" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">page_title</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">page_title</span><span class="p">:</span> <span class="n"><span title="str">str</span></span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="n"><span title="starlette_templates.hypertext.Document(page_title)">page_title</span></span> </code></pre></div> <div class="doc doc-contents "> <p>The title of the page.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.hypertext.Document.headers" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">headers</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">headers</span><span class="p">:</span> <span class="n"><span title="typing.Mapping">Mapping</span></span><span class="p">[</span><span class="n"><span title="str">str</span></span><span class="p">,</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">]</span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="n"><span title="starlette_templates.hypertext.Document(headers)">headers</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Response headers.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.hypertext.Document.status_code" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">status_code</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">status_code</span><span class="p">:</span> <span class="n"><span title="int">int</span></span> <span class="o">=</span> <span class="n"><span title="starlette_templates.hypertext.Document(status_code)">status_code</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Response status code.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.hypertext.Document.title" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">title</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">title</span> <span class="o">=</span> <span class="n"><span title="starlette_templates.hypertext.ht.title">title</span></span><span class="p">()</span> </code></pre></div> <div class="doc doc-contents "> <p>Document title element.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.hypertext.Document.head" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">head</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">head</span><span class="p">:</span> <span class="n"><a class="autorefs autorefs-internal" title=" Element (starlette_templates.hypertext.Element)" href="#starlette_templates.hypertext.Element">Element</a></span> <span class="o">=</span> <span class="n"><span title="starlette_templates.hypertext.ht.head">head</span></span><span class="p">(</span> <span class="n"><span title="starlette_templates.hypertext.ht.meta">meta</span></span><span class="p">(</span><span class="n"><span title="starlette_templates.hypertext.ht.meta(charset)">charset</span></span><span class="o">=</span><span class="s2">"utf-8"</span><span class="p">),</span> <span class="n"><span title="starlette_templates.hypertext.ht.meta">meta</span></span><span class="p">(</span> <span class="n"><span title="starlette_templates.hypertext.ht.meta(name)">name</span></span><span class="o">=</span><span class="s2">"viewport"</span><span class="p">,</span> <span class="n"><span title="starlette_templates.hypertext.ht.meta(content)">content</span></span><span class="o">=</span><span class="s2">"width=device-width, initial-scale=1"</span><span class="p">,</span> <span class="p">),</span> <span class="n"><span title="starlette_templates.hypertext.ht.meta">meta</span></span><span class="p">(</span><span class="n"><span title="starlette_templates.hypertext.ht.meta(http_equiv)">http_equiv</span></span><span class="o">=</span><span class="s2">"X-UA-Compatible"</span><span class="p">,</span> <span class="n"><span title="starlette_templates.hypertext.ht.meta(content)">content</span></span><span class="o">=</span><span class="s2">"IE=edge"</span><span class="p">),</span> <span class="n"><span title="starlette_templates.hypertext.Document(self).title">title</span></span><span class="p">,</span> <span class="p">)</span> </code></pre></div> <div class="doc doc-contents "> <p>The head element.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.hypertext.Document.body" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">body</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">body</span> <span class="o">=</span> <span class="n"><span title="starlette_templates.hypertext.ht.body">body</span></span><span class="p">()</span> </code></pre></div> <div class="doc doc-contents "> <p>The body element.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.hypertext.Document.html" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">html</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">html</span> <span class="o">=</span> <span class="n"><span title="starlette_templates.hypertext.ht.html">html</span></span><span class="p">(</span><span class="n"><span title="starlette_templates.hypertext.Document(self).head">head</span></span><span class="p">,</span> <span class="n"><span title="starlette_templates.hypertext.Document(self).body">body</span></span><span class="p">)</span> </code></pre></div> <div class="doc doc-contents "> <p>The html element.</p> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Document.get_element" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">get_element</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">get_element</span><span class="p">()</span> <span class="o">-></span> <span class="n"><a class="autorefs autorefs-internal" title=" Element (starlette_templates.hypertext.Element)" href="#starlette_templates.hypertext.Element">Element</a></span> </code></pre></div> <div class="doc doc-contents "> <p>Assemble and return the document as its <code><html></code> Element.</p> <p>Moves the document's own children and attributes onto the body and sets the title, so the returned tree reflects everything added to the Document.</p> </div> </div> <div class="doc doc-object doc-function"> <h3 id="starlette_templates.hypertext.Document.to_string" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-method"></code> <span class="doc doc-object-name doc-function-name">to_string</span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">to_string</span><span class="p">()</span> <span class="o">-></span> <span class="n"><span title="str">str</span></span> </code></pre></div> <div class="doc doc-contents "> <p>Render the document to an HTML string, prefixed with the doctype.</p> </div> </div> </div> </div> </div><h2 id="errors">Errors</h2> <div class="doc doc-object doc-class"> <h2 id="starlette_templates.errors.AppException" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-class"></code> <span class="doc doc-object-name doc-class-name">AppException</span> </h2> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">AppException</span><span class="p">(</span> <span class="n">detail</span><span class="p">:</span> <span class="n"><span title="str">str</span></span><span class="p">,</span> <span class="n">status_code</span><span class="p">:</span> <span class="n"><span title="int">int</span></span> <span class="o">=</span> <span class="mi">400</span><span class="p">,</span> <span class="n">code</span><span class="p">:</span> <span class="n"><a class="autorefs autorefs-internal" title=" ErrorCode (starlette_templates.errors.ErrorCode)" href="#starlette_templates.errors.ErrorCode">ErrorCode</a></span> <span class="o">|</span> <span class="n"><span title="str">str</span></span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">source</span><span class="p">:</span> <span class="n"><a class="autorefs autorefs-internal" title=" ErrorSource (starlette_templates.errors.ErrorSource)" href="#starlette_templates.errors.ErrorSource">ErrorSource</a></span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="n">meta</span><span class="p">:</span> <span class="n"><span title="dict">dict</span></span><span class="p">[</span><span class="n"><span title="str">str</span></span><span class="p">,</span> <span class="n"><span title="typing.Any">Any</span></span><span class="p">]</span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span><span class="p">,</span> <span class="p">)</span> </code></pre></div> <div class="doc doc-contents first"> <p>Base exception for all application errors with JSON:API compliance.</p> <p>This exception provides structured error information that can be rendered as either JSON (for API requests) or HTML (for browser requests).</p> <p><span class="doc-section-title">Parameters:</span></p> <ul> <li class="doc-section-item field-body"> <b><code>detail</code></b> (<code><span title="str">str</span></code>) – <div class="doc-md-description"> <p>Human-readable description of the error</p> </div> </li> <li class="doc-section-item field-body"> <b><code>status_code</code></b> (<code><span title="int">int</span></code>, default: <code>400</code> ) – <div class="doc-md-description"> <p>HTTP status code (default: 400)</p> </div> </li> <li class="doc-section-item field-body"> <b><code>code</code></b> (<code><a class="autorefs autorefs-internal" title=" ErrorCode (starlette_templates.errors.ErrorCode)" href="#starlette_templates.errors.ErrorCode">ErrorCode</a> | <span title="str">str</span> | None</code>, default: <code>None</code> ) – <div class="doc-md-description"> <p>Machine-readable error code</p> </div> </li> <li class="doc-section-item field-body"> <b><code>source</code></b> (<code><a class="autorefs autorefs-internal" title=" ErrorSource (starlette_templates.errors.ErrorSource)" href="#starlette_templates.errors.ErrorSource">ErrorSource</a> | None</code>, default: <code>None</code> ) – <div class="doc-md-description"> <p>Location of the error (JSON pointer, parameter name, etc.)</p> </div> </li> <li class="doc-section-item field-body"> <b><code>meta</code></b> (<code><span title="dict">dict</span>[<span title="str">str</span>, <span title="typing.Any">Any</span>] | None</code>, default: <code>None</code> ) – <div class="doc-md-description"> <p>Additional metadata about the error</p> </div> </li> </ul> <details class="example" open> <summary>Example</summary> <div class="highlight"><pre><span></span><code><span class="k">raise</span> <span class="n">AppException</span><span class="p">(</span> <span class="n">detail</span><span class="o">=</span><span class="s2">"User with email 'john@example.com' already exists"</span><span class="p">,</span> <span class="n">status_code</span><span class="o">=</span><span class="mi">409</span><span class="p">,</span> <span class="n">code</span><span class="o">=</span><span class="n">ErrorCode</span><span class="o">.</span><span class="n">DUPLICATE_RESOURCE</span><span class="p">,</span> <span class="n">source</span><span class="o">=</span><span class="n">ErrorSource</span><span class="p">(</span><span class="n">parameter</span><span class="o">=</span><span class="s2">"email"</span><span class="p">),</span> <span class="n">meta</span><span class="o">=</span><span class="p">{</span><span class="s2">"email"</span><span class="p">:</span> <span class="s2">"john@example.com"</span><span class="p">}</span> <span class="p">)</span> </code></pre></div> </details> <div class="doc doc-children"> </div> </div> </div> <div class="doc doc-object doc-class"> <h2 id="starlette_templates.errors.ErrorCode" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-class"></code> <span class="doc doc-object-name doc-class-name">ErrorCode</span> </h2> <div class="doc doc-contents first"> <p>Error codes for API responses following JSON:API specification.</p> <p><span class="doc-section-title">Attributes:</span></p> <ul> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" INTERNAL_ERROR class-attribute instance-attribute (starlette_templates.errors.ErrorCode.INTERNAL_ERROR)" href="#starlette_templates.errors.ErrorCode.INTERNAL_ERROR">INTERNAL_ERROR</a></code></b> – <div class="doc-md-description"> <p>Internal server error not caused by client request.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" INVALID_REQUEST class-attribute instance-attribute (starlette_templates.errors.ErrorCode.INVALID_REQUEST)" href="#starlette_templates.errors.ErrorCode.INVALID_REQUEST">INVALID_REQUEST</a></code></b> – <div class="doc-md-description"> <p>The request is malformed or contains invalid parameters.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" INVALID_PARAMETER class-attribute instance-attribute (starlette_templates.errors.ErrorCode.INVALID_PARAMETER)" href="#starlette_templates.errors.ErrorCode.INVALID_PARAMETER">INVALID_PARAMETER</a></code></b> – <div class="doc-md-description"> <p>A specific parameter in the request is invalid.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" NOT_FOUND class-attribute instance-attribute (starlette_templates.errors.ErrorCode.NOT_FOUND)" href="#starlette_templates.errors.ErrorCode.NOT_FOUND">NOT_FOUND</a></code></b> – <div class="doc-md-description"> <p>The requested resource could not be found.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" VALIDATION_ERROR class-attribute instance-attribute (starlette_templates.errors.ErrorCode.VALIDATION_ERROR)" href="#starlette_templates.errors.ErrorCode.VALIDATION_ERROR">VALIDATION_ERROR</a></code></b> – <div class="doc-md-description"> <p>The request data failed validation checks.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" UNAUTHORIZED class-attribute instance-attribute (starlette_templates.errors.ErrorCode.UNAUTHORIZED)" href="#starlette_templates.errors.ErrorCode.UNAUTHORIZED">UNAUTHORIZED</a></code></b> – <div class="doc-md-description"> <p>Authentication is required and has failed or not been provided.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" FORBIDDEN class-attribute instance-attribute (starlette_templates.errors.ErrorCode.FORBIDDEN)" href="#starlette_templates.errors.ErrorCode.FORBIDDEN">FORBIDDEN</a></code></b> – <div class="doc-md-description"> <p>Access to the requested resource is forbidden.</p> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" METHOD_NOT_ALLOWED class-attribute instance-attribute (starlette_templates.errors.ErrorCode.METHOD_NOT_ALLOWED)" href="#starlette_templates.errors.ErrorCode.METHOD_NOT_ALLOWED">METHOD_NOT_ALLOWED</a></code></b> – <div class="doc-md-description"> <p>The HTTP method used is not allowed for the requested resource.</p> </div> </li> </ul> <div class="doc doc-children"> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorCode.INTERNAL_ERROR" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">INTERNAL_ERROR</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">INTERNAL_ERROR</span> <span class="o">=</span> <span class="s1">'internal_error'</span> </code></pre></div> <div class="doc doc-contents "> <p>Internal server error not caused by client request.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorCode.INVALID_REQUEST" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">INVALID_REQUEST</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">INVALID_REQUEST</span> <span class="o">=</span> <span class="s1">'invalid_request'</span> </code></pre></div> <div class="doc doc-contents "> <p>The request is malformed or contains invalid parameters.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorCode.INVALID_PARAMETER" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">INVALID_PARAMETER</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">INVALID_PARAMETER</span> <span class="o">=</span> <span class="s1">'invalid_parameter'</span> </code></pre></div> <div class="doc doc-contents "> <p>A specific parameter in the request is invalid.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorCode.NOT_FOUND" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">NOT_FOUND</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">NOT_FOUND</span> <span class="o">=</span> <span class="s1">'not_found'</span> </code></pre></div> <div class="doc doc-contents "> <p>The requested resource could not be found.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorCode.VALIDATION_ERROR" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">VALIDATION_ERROR</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">VALIDATION_ERROR</span> <span class="o">=</span> <span class="s1">'validation_error'</span> </code></pre></div> <div class="doc doc-contents "> <p>The request data failed validation checks.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorCode.UNAUTHORIZED" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">UNAUTHORIZED</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">UNAUTHORIZED</span> <span class="o">=</span> <span class="s1">'unauthorized'</span> </code></pre></div> <div class="doc doc-contents "> <p>Authentication is required and has failed or not been provided.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorCode.FORBIDDEN" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">FORBIDDEN</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">FORBIDDEN</span> <span class="o">=</span> <span class="s1">'forbidden'</span> </code></pre></div> <div class="doc doc-contents "> <p>Access to the requested resource is forbidden.</p> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorCode.METHOD_NOT_ALLOWED" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">METHOD_NOT_ALLOWED</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">METHOD_NOT_ALLOWED</span> <span class="o">=</span> <span class="s1">'method_not_allowed'</span> </code></pre></div> <div class="doc doc-contents "> <p>The HTTP method used is not allowed for the requested resource.</p> </div> </div> </div> </div> </div> <div class="doc doc-object doc-class"> <h2 id="starlette_templates.errors.ErrorSource" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-class"></code> <span class="doc doc-object-name doc-class-name">ErrorSource</span> </h2> <div class="doc doc-contents first"> <p>JSON:API error source object indicating where the error originated.</p> <p><span class="doc-section-title">Attributes:</span></p> <ul> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" pointer class-attribute instance-attribute (starlette_templates.errors.ErrorSource.pointer)" href="#starlette_templates.errors.ErrorSource.pointer">pointer</a></code></b> (<code><span title="str">str</span> | None</code>) – <div class="doc-md-description"> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" parameter class-attribute instance-attribute (starlette_templates.errors.ErrorSource.parameter)" href="#starlette_templates.errors.ErrorSource.parameter">parameter</a></code></b> (<code><span title="str">str</span> | None</code>) – <div class="doc-md-description"> </div> </li> <li class="doc-section-item field-body"> <b><code><a class="autorefs autorefs-internal" title=" header class-attribute instance-attribute (starlette_templates.errors.ErrorSource.header)" href="#starlette_templates.errors.ErrorSource.header">header</a></code></b> (<code><span title="str">str</span> | None</code>) – <div class="doc-md-description"> </div> </li> </ul> <div class="doc doc-children"> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorSource.pointer" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">pointer</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">pointer</span><span class="p">:</span> <span class="n"><span title="str">str</span></span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span> </code></pre></div> <div class="doc doc-contents "> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorSource.parameter" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">parameter</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">parameter</span><span class="p">:</span> <span class="n"><span title="str">str</span></span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span> </code></pre></div> <div class="doc doc-contents "> </div> </div> <div class="doc doc-object doc-attribute"> <h3 id="starlette_templates.errors.ErrorSource.header" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-attribute"></code> <span class="doc doc-object-name doc-attribute-name">header</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-class-attribute"><code>class-attribute</code></small> <small class="doc doc-label doc-label-instance-attribute"><code>instance-attribute</code></small> </span> </h3> <div class="doc-signature highlight"><pre><span></span><code><span class="n">header</span><span class="p">:</span> <span class="n"><span title="str">str</span></span> <span class="o">|</span> <span class="kc">None</span> <span class="o">=</span> <span class="kc">None</span> </code></pre></div> <div class="doc doc-contents "> </div> </div> </div> </div> </div> <div class="doc doc-object doc-function"> <h2 id="starlette_templates.errors.exception_handler" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-function"></code> <span class="doc doc-object-name doc-function-name">exception_handler</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-async"><code>async</code></small> </span> </h2> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">exception_handler</span><span class="p">(</span> <span class="n">request</span><span class="p">:</span> <span class="n"><span title="starlette.requests.Request">Request</span></span><span class="p">,</span> <span class="n">exc</span><span class="p">:</span> <span class="n"><span title="Exception">Exception</span></span><span class="p">,</span> <span class="n">jinja_env</span><span class="p">:</span> <span class="n"><span title="jinja2.Environment">Environment</span></span><span class="p">,</span> <span class="n">debug</span><span class="p">:</span> <span class="n"><span title="bool">bool</span></span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span> <span class="p">)</span> <span class="o">-></span> <span class="n"><span title="starlette.responses.Response">Response</span></span> </code></pre></div> <div class="doc doc-contents first"> <p>Handle uncaught exceptions with JSON or HTML response.</p> <p>Provides special handling for: - ValidationError: Detailed validation error messages - AppException: Custom application errors with structured data - General exceptions: Generic 500 error</p> <p>Returns JSON:API format for API requests, HTML for browsers.</p> <p><span class="doc-section-title">Parameters:</span></p> <ul> <li class="doc-section-item field-body"> <b><code>request</code></b> (<code><span title="starlette.requests.Request">Request</span></code>) – <div class="doc-md-description"> <p>The request that caused the error</p> </div> </li> <li class="doc-section-item field-body"> <b><code>exc</code></b> (<code><span title="Exception">Exception</span></code>) – <div class="doc-md-description"> <p>Exception that was raised</p> </div> </li> <li class="doc-section-item field-body"> <b><code>jinja_env</code></b> (<code><span title="jinja2.Environment">Environment</span></code>) – <div class="doc-md-description"> <p>Jinja2 environment for rendering templates</p> </div> </li> <li class="doc-section-item field-body"> <b><code>debug</code></b> (<code><span title="bool">bool</span></code>, default: <code>False</code> ) – <div class="doc-md-description"> <p>Whether to include debug information</p> </div> </li> </ul> <p><span class="doc-section-title">Returns:</span></p> <ul> <li class="doc-section-item field-body"> <code><span title="starlette.responses.Response">Response</span></code> – <div class="doc-md-description"> <p>Response with error details</p> </div> </li> </ul> </div> </div> <div class="doc doc-object doc-function"> <h2 id="starlette_templates.errors.httpexception_handler" class="doc doc-heading"> <code class="doc-symbol doc-symbol-heading doc-symbol-function"></code> <span class="doc doc-object-name doc-function-name">httpexception_handler</span> <span class="doc doc-labels"> <small class="doc doc-label doc-label-async"><code>async</code></small> </span> </h2> <div class="doc-signature highlight"><pre><span></span><code><span class="nf">httpexception_handler</span><span class="p">(</span> <span class="n">request</span><span class="p">:</span> <span class="n"><span title="starlette.requests.Request">Request</span></span><span class="p">,</span> <span class="n">exc</span><span class="p">:</span> <span class="n"><span title="starlette.exceptions.HTTPException">HTTPException</span></span><span class="p">,</span> <span class="n">jinja_env</span><span class="p">:</span> <span class="n"><span title="jinja2.Environment">Environment</span></span><span class="p">,</span> <span class="n">debug</span><span class="p">:</span> <span class="n"><span title="bool">bool</span></span> <span class="o">=</span> <span class="kc">False</span><span class="p">,</span> <span class="p">)</span> <span class="o">-></span> <span class="n"><span title="starlette.responses.Response">Response</span></span> </code></pre></div> <div class="doc doc-contents first"> <p>Handle HTTP exceptions (404, 500, etc.) with JSON or HTML response.</p> <p>Returns JSON:API error format for API requests, HTML error page for browsers.</p> <p><span class="doc-section-title">Parameters:</span></p> <ul> <li class="doc-section-item field-body"> <b><code>request</code></b> (<code><span title="starlette.requests.Request">Request</span></code>) – <div class="doc-md-description"> <p>The request that caused the error</p> </div> </li> <li class="doc-section-item field-body"> <b><code>exc</code></b> (<code><span title="starlette.exceptions.HTTPException">HTTPException</span></code>) – <div class="doc-md-description"> <p>HTTPException that was raised</p> </div> </li> <li class="doc-section-item field-body"> <b><code>jinja_env</code></b> (<code><span title="jinja2.Environment">Environment</span></code>) – <div class="doc-md-description"> <p>Jinja2 environment for rendering templates</p> </div> </li> <li class="doc-section-item field-body"> <b><code>debug</code></b> (<code><span title="bool">bool</span></code>, default: <code>False</code> ) – <div class="doc-md-description"> <p>Whether to include debug information</p> </div> </li> </ul> <p><span class="doc-section-title">Returns:</span></p> <ul> <li class="doc-section-item field-body"> <code><span title="starlette.responses.Response">Response</span></code> – <div class="doc-md-description"> <p>Response with error details</p> </div> </li> </ul> </div> </div> </article> </div> <script>var tabs=__md_get("__tabs");if(Array.isArray(tabs))e:for(var set of document.querySelectorAll(".tabbed-set")){var labels=set.querySelector(".tabbed-labels");for(var tab of tabs)for(var label of labels.getElementsByTagName("label"))if(label.innerText.trim()===tab){var input=document.getElementById(label.htmlFor);input.checked=!0;continue e}}</script> <script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script> </div> <button type="button" class="md-top md-icon" data-md-component="top" hidden> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8z"/></svg> Back to top </button> </main> <footer class="md-footer"> <nav class="md-footer__inner md-grid" aria-label="Footer" > <a href="../errors/" class="md-footer__link md-footer__link--prev" aria-label="Previous: Error Handling"> <div class="md-footer__button md-icon"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11z"/></svg> </div> <div class="md-footer__title"> <span class="md-footer__direction"> Previous </span> <div class="md-ellipsis"> Error Handling </div> </div> </a> </nav> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-copyright"> <div class="md-copyright__highlight"> MIT License </div> </div> </div> </div> </footer> </div> <div class="md-dialog" data-md-component="dialog"> <div class="md-dialog__inner md-typeset"></div> </div> <div class="md-progress" data-md-component="progress" role="progressbar"></div> <script id="__config" type="application/json">{"annotate": null, "base": "..", "features": ["navigation.sections", "navigation.path", "navigation.instant", "navigation.instant.prefetch", "navigation.instant.progress", "navigation.indexes", "navigation.tracking", "content.code.annotate", "toc.follow", "navigation.footer", "navigation.top", "content.code.copy", "content.tabs.link"], "search": "../assets/javascripts/workers/search.2c215733.min.js", "tags": null, "translations": {"clipboard.copied": "Copied to clipboard", "clipboard.copy": "Copy to clipboard", "search.result.more.one": "1 more on this page", "search.result.more.other": "# more on this page", "search.result.none": "No matching documents", "search.result.one": "1 matching document", "search.result.other": "# matching documents", "search.result.placeholder": "Type to start searching", "search.result.term.missing": "Missing", "select.version": "Select version"}, "version": null}</script> <script src="../assets/javascripts/bundle.79ae519e.min.js"></script> </body> </html>