Static Files
Relevant source files
The following files were used as context for generating this wiki page:
The Static Files system in Starlette provides a robust, asynchronous mechanism for serving local files, directories, and package resources over HTTP. It is implemented primarily through the StaticFiles class, which acts as a standalone ASGI application that can be mounted into a larger routing structure.
This system handles essential web features such as HTTP caching (via ETags and Last-Modified headers), directory redirection, "HTML mode" for serving index files, and security measures to prevent path traversal attacks. By utilizing anyio for asynchronous file I/O, it ensures that file operations do not block the main event loop.
Sources: starlette/staticfiles.py:38-43, README.md:21-30
Architecture and Core Logic
The system is centered around the StaticFiles class. When a request is received, the class resolves the requested URL path to a physical file path across one or more registered directories or Python packages.
Request Handling Flow
The following diagram illustrates the internal logic of a StaticFiles instance when processing an incoming ASGI scope:
Sources: starlette/staticfiles.py:82-126
Key Components
| Component | Description |
|---|---|
StaticFiles | The primary ASGI application for serving static content. |
FileResponse | A specialized response class that handles streaming file content and range requests. |
NotModifiedResponse | A 304 HTTP response used when client cache validators (ETag/Last-Modified) match. |
lookup_path | Logic for searching across multiple directories and validating path safety. |
Sources: starlette/staticfiles.py:17-43, starlette/responses.py:440-445
Configuration Options
The StaticFiles constructor accepts several parameters to define how files are located and served.
| Parameter | Type | Default | Description |
|---|---|---|---|
directory | PathLike | None | The root directory to serve files from. |
packages | list | None | A list of Python packages (or tuples of package name and directory) containing static assets. |
html | bool | False | If true, enables HTML mode (serves index.html for directories and 404.html for missing files). |
check_dir | bool | True | Whether to verify the existence of the directory during initialization. |
follow_symlink | bool | False | If true, allows serving files through symbolic links. |
Sources: starlette/staticfiles.py:39-55
Path Resolution and Security
Starlette implements strict security checks to ensure that clients cannot access files outside of the designated static directories using path traversal techniques (e.g., ../../etc/passwd).
Lookup Mechanism
- Normalization: The incoming route path is normalized using
os.path.normpathto remove..and.segments. - Absolute Path Validation: Paths starting with
/or\are rejected immediately to prevent escaping the root. - Common Path Check: The system uses
os.path.commonpathto verify that the resolved full path actually resides within one of the configured base directories. - Async I/O: The actual
os.statcall is offloaded to a thread pool usinganyio.to_thread.run_syncto maintain non-blocking behavior.
Sources: starlette/staticfiles.py:94-106, starlette/staticfiles.py:136-155, tests/test_staticfiles.py:186-200
HTTP Caching and 304 Responses
Efficiency is maintained by supporting standard HTTP caching headers. Before serving a full FileResponse, the system checks the request headers against the file's metadata.
StaticFiles validates the If-None-Match (ETag) and If-Modified-Since (timestamp) headers. If If-None-Match is present, it takes precedence over the timestamp-based validation.
Sources: starlette/staticfiles.py:177-206, tests/test_staticfiles.py:223-234
Serving from Python Packages
Starlette can serve assets directly from installed Python packages. This is useful for distributing web assets within library modules.
# Example: Serving from a package named 'my_package'
# It will look for a directory named 'statics' within the package by default.
app = StaticFiles(packages=["my_package"])
# Example: Specifying a custom directory name within the package
app = StaticFiles(packages=[("my_package", "custom_assets")])
The system uses importlib.util.find_spec to locate the package's physical location on the disk and appends the requested static directory path.
Sources: starlette/staticfiles.py:57-79, tests/test_staticfiles.py:73-83
File Responses and Range Requests
The underlying FileResponse (utilized by StaticFiles) supports advanced streaming features, including Byte Range Requests (HTTP 206). This allows clients to request specific segments of a file, which is critical for video streaming and resuming large downloads.
- Single Range: Returns a
206 Partial Contentwith aContent-Rangeheader. - Multiple Ranges: Returns a
206 Partial Contentwith amultipart/byterangescontent type and a unique boundary. - Head Requests: If the method is
HEAD, only the headers (Content-Length, ETag, etc.) are sent without the body.
Sources: starlette/responses.py:530-560, starlette/responses.py:615-635, tests/test_responses.py:840-860
Conclusion
The Static Files module provides a high-performance, secure bridge between the local filesystem and the web. By integrating deeply with Starlette's response system and leveraging asynchronous task groups, it handles complex scenarios like multipart range requests and package-based asset distribution while maintaining strict path security and efficient caching.