Signature: `StaticFiles(directory=None, packages=None, check_dir=True)`
* `directory` - A string or [os.Pathlike][pathlike] denoting a directory path.
-* `packages` - A list of strings of python packages.
+* `packages` - A list of strings or list of tuples of strings of python packages.
* `html` - Run in HTML mode. Automatically loads `index.html` for directories if such file exist.
* `check_dir` - Ensure that the directory exists upon instantiation. Defaults to `True`.
app = Starlette(routes=routes)
```
+By default `StaticFiles` will look for `statics` directory in each package,
+you can change the default directory by specifying a tuple of strings.
+
+```python
+routes=[
+ ...
+ Mount('/static', app=StaticFiles(packages=[('bootstrap4', 'static')]), name="static"),
+]
+```
+
You may prefer to include static files directly inside the "static" directory
rather than using Python packaging to include static files, but it can be useful
for bundling up reusable components.
self,
*,
directory: PathLike = None,
- packages: typing.List[str] = None,
+ packages: typing.List[typing.Union[str, typing.Tuple[str, str]]] = None,
html: bool = False,
check_dir: bool = True,
) -> None:
raise RuntimeError(f"Directory '{directory}' does not exist")
def get_directories(
- self, directory: PathLike = None, packages: typing.List[str] = None
+ self,
+ directory: PathLike = None,
+ packages: typing.List[typing.Union[str, typing.Tuple[str, str]]] = None,
) -> typing.List[PathLike]:
"""
Given `directory` and `packages` arguments, return a list of all the
directories.append(directory)
for package in packages or []:
+ if isinstance(package, tuple):
+ package, statics_dir = package
+ else:
+ statics_dir = "statics"
spec = importlib.util.find_spec(package)
assert spec is not None, f"Package {package!r} could not be found."
- assert (
- spec.origin is not None
- ), f"Directory 'statics' in package {package!r} could not be found."
+ assert spec.origin is not None, f"Package {package!r} could not be found."
package_directory = os.path.normpath(
- os.path.join(spec.origin, "..", "statics")
+ os.path.join(spec.origin, "..", statics_dir)
)
assert os.path.isdir(
package_directory
- ), f"Directory 'statics' in package {package!r} could not be found."
+ ), f"Directory '{statics_dir!r}' in package {package!r} could not be found."
directories.append(package_directory)
return directories
assert response.status_code == 200
assert response.text == "123\n"
+ app = StaticFiles(packages=[("tests", "statics")])
+ client = test_client_factory(app)
+ response = client.get("/example.txt")
+ assert response.status_code == 200
+ assert response.text == "123\n"
+
def test_staticfiles_post(tmpdir, test_client_factory):
path = os.path.join(tmpdir, "example.txt")