Performance: File responses
This affects how quickly files are sent from the server to the user, impacting page load speed and user wait time.
from fastapi import FastAPI from fastapi.responses import FileResponse app = FastAPI() @app.get('/download') async def download_file(): return FileResponse('largefile.zip', media_type='application/zip', filename='largefile.zip')
from fastapi import FastAPI from fastapi.responses import Response app = FastAPI() @app.get('/download') async def download_file(): with open('largefile.zip', 'rb') as f: data = f.read() return Response(content=data, media_type='application/zip')
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Reading full file into memory and returning Response | 0 (no DOM) | 0 | 0 | [X] Bad |
| Using FileResponse to stream file | 0 (no DOM) | 0 | 0 | [OK] Good |
FileResponse in FastAPI?FileResponse is designed to send files from the server to the client in FastAPI.FileResponse specifically sends files.FileResponse in FastAPI?FileResponse is imported from fastapi.responses using Python's standard import syntax.from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get('/download')
async def download_file():
return FileResponse('example.pdf', media_type='application/pdf', filename='report.pdf')from fastapi import FastAPI
from fastapi.responses import FileResponse
app = FastAPI()
@app.get('/file')
async def get_file():
return FileResponse(filepath='data.txt', media_type='text/plain')os.path.exists('file.txt') correctly checks if the file exists before sending.HTTPException with 404 status is the proper way to signal file not found in FastAPI.Pass the test and this pattern moves unknown