Skip to content

Static Files

Starlette also includes an StaticFiles class for serving files in a given directory:

static file

Signed by: StaticFiles(directory=None, packages=None, html=False, check_dir=True, follow_symlink=False)

  • directory - String representing directory path or os.PathLike.
  • packages - A Python package string list or string tuple list.
  • html-runs in HTML mode. If such a file exists,index.html is automatically loaded for the directory.
  • check_dir-Ensure that the directory exists at instantiation. Default is True.
  • follow_symlink-A Boolean indicating whether symbolic links for files and directories should be followed. Default is False.

You can combine this ASGI application with Starlette's routing to provide comprehensive static file services.

from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles


routes = [
    ...
    Mount('/static', app=StaticFiles(directory='static'), name="static"),
]

app = Starlette(routes=routes)

For unmatched requests, static files will respond with "404 not found" or "405 method not allowed." In HTML mode, if an 404.html file exists, it will be displayed as a 404 response.

packages Option can be used to contain "static" directories within Python packages. Python's "bootstrap4" package is an example of this.

from starlette.applications import Starlette
from starlette.routing import Mount
from starlette.staticfiles import StaticFiles


routes=[
    ...
    Mount('/static', app=StaticFiles(directory='static', packages=['bootstrap4']), name="static"),
]

app = Starlette(routes=routes)

By default,StaticFiles looks for the statics directory in each package, and you can change the default directory by specifying a string tuple.

routes=[
    ...
    Mount('/static', app=StaticFiles(packages=[('bootstrap4', 'static')]), name="static"),
]

You may prefer to include static files directly in the "static" directory rather than using Python packaging to include static files, but this may be useful for bundling reusable components.