2018-08-29 10:17:09 +00:00
|
|
|
|
2018-11-08 09:33:20 +00:00
|
|
|
Starlette also includes a `StaticFiles` class for serving files in a given directory:
|
2018-08-29 10:17:09 +00:00
|
|
|
|
2018-11-08 09:33:20 +00:00
|
|
|
### StaticFiles
|
|
|
|
|
2019-02-26 14:38:05 +00:00
|
|
|
Signature: `StaticFiles(directory=None, packages=None, check_dir=True)`
|
2018-11-08 09:33:20 +00:00
|
|
|
|
2019-02-26 14:38:05 +00:00
|
|
|
* `directory` - A string denoting a directory path.
|
|
|
|
* `packages` - A list of strings of python packages.
|
2019-10-15 12:40:56 +00:00
|
|
|
* `html` - Run in HTML mode. Automatically loads `index.html` for directories if such file exist.
|
2019-02-26 14:38:05 +00:00
|
|
|
* `check_dir` - Ensure that the directory exists upon instantiation. Defaults to `True`.
|
2018-08-29 10:17:09 +00:00
|
|
|
|
2018-10-28 18:04:17 +00:00
|
|
|
You can combine this ASGI application with Starlette's routing to provide
|
2018-08-29 10:17:09 +00:00
|
|
|
comprehensive static file serving.
|
|
|
|
|
|
|
|
```python
|
2019-11-13 12:25:18 +00:00
|
|
|
from starlette.applications import Starlette
|
|
|
|
from starlette.routing import Mount
|
2018-10-28 18:04:17 +00:00
|
|
|
from starlette.staticfiles import StaticFiles
|
2018-08-29 10:17:09 +00:00
|
|
|
|
|
|
|
|
2019-11-13 12:25:18 +00:00
|
|
|
routes = [
|
|
|
|
...
|
2019-02-26 14:38:05 +00:00
|
|
|
Mount('/static', app=StaticFiles(directory='static'), name="static"),
|
2019-11-13 12:25:18 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
app = Starlette(routes=routes)
|
2018-08-29 10:17:09 +00:00
|
|
|
```
|
|
|
|
|
2018-08-30 13:42:39 +00:00
|
|
|
Static files will respond with "404 Not found" or "405 Method not allowed"
|
2019-10-15 12:40:56 +00:00
|
|
|
responses for requests which do not match. In HTML mode if `404.html` file
|
|
|
|
exists it will be shown as 404 response.
|
2019-02-26 14:38:05 +00:00
|
|
|
|
|
|
|
The `packages` option can be used to include "static" directories contained within
|
|
|
|
a python package. The Python "bootstrap4" package is an example of this.
|
|
|
|
|
|
|
|
```python
|
2019-11-13 12:25:18 +00:00
|
|
|
from starlette.applications import Starlette
|
|
|
|
from starlette.routing import Mount
|
2019-02-26 14:38:05 +00:00
|
|
|
from starlette.staticfiles import StaticFiles
|
|
|
|
|
|
|
|
|
2019-11-13 12:25:18 +00:00
|
|
|
routes=[
|
|
|
|
...
|
2019-02-26 14:38:05 +00:00
|
|
|
Mount('/static', app=StaticFiles(directory='static', packages=['bootstrap4']), name="static"),
|
2019-11-13 12:25:18 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
app = Starlette(routes=routes)
|
2019-02-26 14:38:05 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
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.
|