I have mounted the static directory in my FastAPI app using the following code:
JavaScript
x
7
1
from fastapi.staticfiles import StaticFiles
2
3
app = FastAPI(
4
title="Title of the Application",
5
description="Over all description of the application")
6
app.mount("/public", StaticFiles(directory='public'), name='public')
7
If I have a symlink pointing to a path outside the app folder, e.g.
JavaScript
1
4
1
/home/xyz/app/main.py
2
/home/xyz/app/index.html
3
/home/xyz/app/public/data -> /home/xyz/static/whatever.tgz
4
The FastAPI application can recognize the URL xyz.com/public/index.html
, but it can’t recognize xyz.com/public/data
.
Is this doable? Unfortunately, I cannot use FileResponse
due to the blob
size being too large. I want to return the file with a simple link somehow.
Advertisement
Answer
It is doable, as long as you mount a StaticFiles
instance on that specific path as well. For example:
JavaScript
1
3
1
app.mount("/public", StaticFiles(directory="public"), name="public")
2
app.mount("/publicsym", StaticFiles(directory="public/data"), name="publicsym")
3
Then in your Jinja2 template you can requesst the files as below:
JavaScript
1
3
1
<link href="{{ url_for('public', path='/styles.css') }}" rel="stylesheet">
2
<img src="{{ url_for('publicsym', path='/image.png')}}" width="50%">
3
or, as per your given example (if there is a "static"
directory including a “whatever.tgz” file):
JavaScript
1
2
1
{{ url_for('publicsym', path='static/whatever.tgz')}}
2