I have mounted the static directory in my FastAPI app using the following code:
from fastapi.staticfiles import StaticFiles app = FastAPI( title="Title of the Application", description="Over all description of the application") app.mount("/public", StaticFiles(directory='public'), name='public')
If I have a symlink pointing to a path outside the app folder, e.g.
/home/xyz/app/main.py /home/xyz/app/index.html /home/xyz/app/public/data -> /home/xyz/static/whatever.tgz
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:
app.mount("/public", StaticFiles(directory="public"), name="public") app.mount("/publicsym", StaticFiles(directory="public/data"), name="publicsym")
Then in your Jinja2 template you can requesst the files as below:
<link href="{{ url_for('public', path='/styles.css') }}" rel="stylesheet"> <img src="{{ url_for('publicsym', path='/image.png')}}" width="50%">
or, as per your given example (if there is a "static"
directory including a “whatever.tgz” file):
{{ url_for('publicsym', path='static/whatever.tgz')}}