'FastAPI serving static files through symlinks

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.



Solution 1:[1]

It is doable, as long as you mount a StaticFiles() instance in 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, for example:

<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 in the pointing folder):

{{ url_for('publicsym', path='static/whatever.tgz')}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1