与 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中文网其他相关文章!