Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add staticfiles packages with directory #1350

Merged
merged 5 commits into from
Dec 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion docs/staticfiles.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down Expand Up @@ -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.
Expand Down
18 changes: 11 additions & 7 deletions starlette/staticfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __init__(
self,
*,
directory: PathLike = None,
packages: typing.List[str] = None,
packages: typing.List[typing.Union[str, typing.Tuple[str, str]]] = None,
aminalaee marked this conversation as resolved.
Show resolved Hide resolved
html: bool = False,
check_dir: bool = True,
) -> None:
Expand All @@ -53,7 +53,9 @@ def __init__(
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
Expand All @@ -64,17 +66,19 @@ def get_directories(
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."
aminalaee marked this conversation as resolved.
Show resolved Hide resolved
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
Expand Down
6 changes: 6 additions & 0 deletions tests/test_staticfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down