1- # Serving static files
1+ F # Serving static files
22
33This page covers:
44
@@ -28,21 +28,22 @@ When serving files this way, a match-all route ("*") is configured in the
2828application router for ` GET ` and ` HEAD ` , and files are read from the configured
2929folder upon web requests.
3030
31+
3132It is also possible to serve static files from sub-folders:
3233
3334``` python
3435app.serve_files(" app/static" )
3536```
3637
37- Enable file discovery (in such case, requests for directories will generate an
38- HTML response with a list of files) :
38+ To enable file discovery, add the ` discovery=True ` parameter. In such case,
39+ requests for directories will generate an HTML response with a list of files:
3940
4041``` python
4142app.serve_files(" app/static" , discovery = True )
4243```
4344
44- BlackSheep also supports serving static files from multiple folders, and
45- specifying a prefix for the route path :
45+ Serving static files from multiple folders is supported, using a different path
46+ for each folder :
4647
4748``` python
4849app = Application()
@@ -52,6 +53,52 @@ app.serve_files("app/images", root_path="images")
5253app.serve_files(" app/videos" , root_path = " videos" )
5354```
5455
56+ ### Route paths and folder names
57+
58+ By default, when you serve files from a folder, the folder name is ** not**
59+ included in the route at which files are served. For example, if you have a
60+ file ` test.txt ` in your ` static ` directory and you use:
61+
62+ ``` python
63+ app.serve_files(" static" )
64+ ```
65+
66+ the file will be accessible at ` http://localhost/test.txt ` (not
67+ ` http://localhost/static/test.txt ` ).
68+
69+ If you want the files to be accessible under a specific route path (such as
70+ ` /static/ ` ), use the ` root_path ` parameter:
71+
72+ ``` python
73+ app.serve_files(" static" , root_path = " static" )
74+ ```
75+
76+ With this configuration, ` test.txt ` will be accessible at ` http://localhost/static/test.txt ` .
77+
78+ ### Serving single files
79+
80+ If you need to serve single files, it is possible to use the ` file ` function
81+ like in the following example.
82+
83+ ``` python
84+ from blacksheep import Application, get
85+ from blacksheep.server.responses import file , ContentDispositionType
86+
87+
88+ app = Application()
89+
90+
91+ @get (" /favicon.ico" )
92+ def favicon_icon ():
93+ # Note: the file is read asynchronously and served in chunks,
94+ # even though this function itself is synchronous
95+ return file (
96+ " path-to-your/favicon.ico" , # ← local path
97+ " image/vnd.microsoft.icon" ,
98+ content_disposition = ContentDispositionType.INLINE ,
99+ )
100+ ```
101+
55102## File extensions
56103
57104Only files with a configured extension are served to the client. By default,
0 commit comments