How to add custom headers when using app.mount (Specifically, cache-control headers) #7618
-
I am using app.mount similar to the following example: app.mount("/app", StaticFiles(directory="html", html="index.html"), name="static") How would I go about adding custom response headers when mounting static files in this fashion? Specifically, I would like to add cache-control response headers for this mount. Thank you. |
Beta Was this translation helpful? Give feedback.
Replies: 8 comments
-
Look inside the |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help here @dmig-alarstudios ! 👏 🙇 If that solves the original problem, then you can close this issue @pushshift ✔️ |
Beta Was this translation helpful? Give feedback.
-
Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues. |
Beta Was this translation helpful? Give feedback.
-
I have the same question, if i really want to server static file from app.mount and just change response header how can i do it |
Beta Was this translation helpful? Give feedback.
-
Same here, I would like to use |
Beta Was this translation helpful? Give feedback.
-
Same, did anyone figure out how to do this? |
Beta Was this translation helpful? Give feedback.
-
from starlette.responses import Response
from starlette.types import Scope
from starlette.staticfiles import StaticFiles
class CacheControlledStaticFiles(StaticFiles):
async def get_response(self, path: str, scope: Scope) -> Response:
response = await super().get_response(path, scope)
response.headers["Cache-Control"] = "public, max-age=31536000"
return response This should work. |
Beta Was this translation helpful? Give feedback.
-
If you want to set cache control to only images for example, add this: if path.endswith('.png') or path.endswith('.jpg'):
response.headers["Cache-Control"] = "public, max-age=31536000" |
Beta Was this translation helpful? Give feedback.
This should work.