Static files

While in production you will want to serve static files through more efficient solutions (NGINX, CDN), Expanse provides a simple way to serve them during development.

Serving static files directly from your application is only possible if your application is in debug mode. In production, it will should be disabled.

By default, static files should be stored in the static directory at the root of you application and will be served through URLs prefixed by /static.

Both of these are configurable if needed.

Generating static files URL

A route with the name static is automatically created and is accessible via a Router instance. Retrieving the URL associated with this route is done with the route() method.

from expanse.routing.router import Router


def index(router: Router) -> str:
    return router.route("static", path="foo/bar.txt")

For convenience, in your view templates, you have access to the static function.

<a href="{{ static('foo/bar.txt') }}">My file</a>

Configuring paths

The paths where the application will look for static files can be configured

export STATIC_PATHS=static,static2

Relative paths will be resolved relative to the root of your application.

If you need to configure paths more programmatically, you can do so by using the add_path method of a Static instance. In a typical application, this would be done in the AppServiceProvider service provider:

from expanse.support.service_provider import ServiceProvider
from expanse.static.static import Static


class AppServiceProvider(ServiceProvider):
    def register(self) -> None:
        self._app.after_resolving(Static, self._add_static_paths)

    def _add_static_paths(self, static: Static) -> None:
        static.add_path(self._app.base_path / "custom_static")

Configuring the URL prefix

The default prefix for static files URL is /static but this can easily be changed:

export STATIC_PREFIX=/assets