Classes
StaticFiles
4
▼
Middleware that serves static files from a directory.
Files are served for paths matching the conf…
StaticFiles
4
▼
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",
))
Methods
Internal Methods 4 ▼
__init__
5
▼
__init__
5
▼
def __init__(self, directory: str | Path, prefix: str = '/static', *, index: str = 'index.html', not_found_page: str | None = None, cache_control: str = 'public, max-age=3600') -> None
Parameters
| Name | Type | Description |
|---|---|---|
directory |
— |
|
prefix |
— |
Default:'/static'
|
index |
— |
Default:'index.html'
|
not_found_page |
— |
Default:None
|
cache_control |
— |
Default:'public, max-age=3600'
|
__call__
2
AnyResponse
▼
Serve a static file or fall through.
async
__call__
2
AnyResponse
▼
async def __call__(self, request: Request, next: Next) -> AnyResponse
Parameters
| Name | Type | Description |
|---|---|---|
request |
— |
|
next |
— |
Returns
AnyResponse
_serve_file
2
Response
▼
Read a file and build a response.
_serve_file
2
Response
▼
def _serve_file(self, file_path: Path, *, status: int = 200) -> Response
Parameters
| Name | Type | Description |
|---|---|---|
file_path |
— |
|
status |
— |
Default:200
|
Returns
Response
_handle_not_found
2
AnyResponse
▼
Fall through to the inner handler; serve custom 404 if it also fails.
This let…
async
_handle_not_found
2
AnyResponse
▼
async def _handle_not_found(self, next: Next, request: Request) -> AnyResponse
Fall through to the inner handler; serve custom 404 if it also fails.
This lets application routes (e.g. SSE endpoints) take priority
over the custom 404 page. Whennot_found_pageis set, the
router'sNotFoundexception is caught and the custom page
is served instead.
Parameters
| Name | Type | Description |
|---|---|---|
next |
— |
|
request |
— |
Returns
AnyResponse