Static file serving middleware.
Serves files from a directory for matching URL prefixes. Supports
root-level serving (prefix="/") with automatic index file resolution
and optional custom error pages.
Falls through to the next handler for non-matching paths.
File bodies are streamed from disk bysend_file_response()
(viaFileResponse) rather than read fully into
memory, and carryETag / Last-Modified / Accept-Rangesso clients
can do conditional GETs (304) and range requests (206).
middleware.static
| Name | Type | Default | Description |
|---|---|---|---|
type
|
|
— | |
qualified_name
|
|
— | |
element_type
|
|
— | |
description
|
|
— | |
source_file
|
|
— | |
line_number
|
|
— | |
is_autodoc
|
|
— | |
autodoc_element
|
|
— | |
_autodoc_template
|
|
— | |
_autodoc_url_path
|
|
— | |
_autodoc_page_type
|
|
— | |
title
|
|
— | |
doc_content_hash
|
|
— |
Symbols on this page
StaticFiles
class
Middleware that serves static files from a directory.
Files are served for paths matching the configured prefix. Non-matching paths fall through to the next handler.
Security: resolves symlinks and verifies the final path is within the configured directory to prevent path traversal.
Usage::
# Serve under a prefix
app.add_middleware(StaticFiles(
directory="./static",
prefix="/static",
))
# Root-level serving (static site)
app.add_middleware(StaticFiles(
directory="./public",
prefix="/",
not_found_page="404.html",
cache_control="no-cache",
))
Large files stream from disk in chunks once they reach
stream_thresholdbytes (default 1 MiB), keeping worker RSS bounded;
smaller files are read in a single shot so latency is unchanged.
View source · /home/runner/work/chirp/chirp/site/../src/chirp/middleware/static.py:1