與 Flask 相比,FastAPI UploadFile 效能問題
由於檔案處理的差異,FastAPI 的 UploadFile 處理可能比 Flask 慢。 Flask 使用同步檔案寫入,而 FastAPI 的 UploadFile 方法是異步的,並使用預設大小為 1 MB 的緩衝區。
改進的性能解決方案
要提高性能,請實現與 aiofiles非同步寫入檔案庫:
<code class="python">from fastapi import File, UploadFile import aiofiles @app.post("/upload") async def upload_async(file: UploadFile = File(...)): try: contents = await file.read() async with aiofiles.open(file.filename, 'wb') as f: await f.write(contents) except Exception: return {"message": "There was an error uploading the file"} finally: await file.close() return {"message": f"Successfully uploaded {file.filename}"}</code>
附加說明
流解決方案
為了獲得更好的性能,請考慮將請求正文作為流訪問,而不存儲內存或臨時目錄中的整個主體:
<code class="python">from fastapi import Request import aiofiles @app.post("/upload") async def upload_stream(request: Request): try: filename = request.headers['filename'] async with aiofiles.open(filename, 'wb') as f: async for chunk in request.stream(): await f.write(chunk) except Exception: return {"message": "There was an error uploading the file"} return {"message": f"Successfully uploaded {filename}"}</code>
以上是為什麼 FastAPI 的 UploadFile 處理速度比 Flask 慢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!