Performance: File download responses
This affects page load speed and user experience by controlling how files are sent from the server to the browser and how quickly the browser can start downloading and rendering the file.
Jump into concepts and practice - no test required
from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() @app.get('/download') async def download_file(): def iterfile(): with open('large_file.zip', 'rb') as f: yield from f return StreamingResponse(iterfile(), media_type='application/zip')
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get('/download') async def download_file(): return FileResponse('large_file.zip')
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| FileResponse for large files | Minimal (no DOM changes) | 0 | 0 | [!] OK but can block server |
| StreamingResponse for large files | Minimal (no DOM changes) | 0 | 0 | [OK] Best for performance |
FileResponse in FastAPI?FileResponse is designed to send files from the server to the client, enabling downloads.FileResponse.FileResponse in a FastAPI app?FileResponse is located in the fastapi.responses module and imported using Python's standard import syntax./download?
from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get('/download')
async def download_file():
return FileResponse('files/report.pdf', media_type='application/pdf', filename='report.pdf')from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get('/getfile')
def get_file():
return FileResponse(path='myfile.txt', media_type='text/plain', filename=myfile.txt)filename=myfile.txt without quotes, so Python treats it as a variable, causing a NameError.data.csv stored in static/files/. The file path may not exist sometimes. Which is the best way to handle this safely?FileResponse risks server errors or confusing client errors.FileNotFoundError and returning a 404 response is best practice for user-friendly error handling.