]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
Add support for Staticfiles directory in packages (#1350)
authorAmin Alaee <mohammadamin.alaee@gmail.com>
Tue, 7 Dec 2021 09:04:54 +0000 (10:04 +0100)
committerGitHub <noreply@github.com>
Tue, 7 Dec 2021 09:04:54 +0000 (10:04 +0100)
docs/staticfiles.md
starlette/staticfiles.py
tests/test_staticfiles.py

index d8786af4de60bd5ae06ce573fe91e91d34af50c4..3591b4f9f588cb692d499df2a0fa16a22ded0e0b 100644 (file)
@@ -6,7 +6,7 @@ Starlette also includes a `StaticFiles` class for serving files in a given direc
 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`.
 
@@ -48,6 +48,16 @@ routes=[
 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.
index f7057539fa1021d2f984df54ff3175f6e077ac81..76e435310be484143059a6bb83b3ee061363c27a 100644 (file)
@@ -40,7 +40,7 @@ class StaticFiles:
         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:
@@ -53,7 +53,9 @@ class StaticFiles:
             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
@@ -64,17 +66,19 @@ class StaticFiles:
             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
index 8057af68921d08bf31625a52dcf339857396e4f0..bd7e0de0229d0a3ae749f14d03c2202fd95684d0 100644 (file)
@@ -67,6 +67,12 @@ def test_staticfiles_with_package(test_client_factory):
     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")