首页 >后端开发 >Python教程 >如何解决FastAPI上传空文件问题?

如何解决FastAPI上传空文件问题?

DDD
DDD原创
2024-12-20 14:48:10791浏览

How to Solve Empty File Upload Issues in FastAPI?

如何使用FastAPI上传文件?

问题:
当使用FastAPI上传文件时根据官方文档,file2store变量仍然存在空。

原因:

  • 确保安装了 python-multipart。
  • 使用 def 端点时,可以使用 .file属性来访问实际的 Python 文件并同步调用其方法。
  • 使用 async def 端点时,请考虑异步文件操作。
  • 如果文件对于内存来说太大,请相应地调整块大小。

解决方案:

app. py:

from fastapi import File, UploadFile

@app.post("/create_file")
def create_file(file: UploadFile = File(...)):
    try:
        contents = file.file.read()
        # store contents to the database
    except Exception:
        return {"message": "Error uploading file"}
    finally:
        file.file.close()
    return {"message": f"Successfully uploaded {file.filename}"}

替代对于异步端点:

@app.post("/create_file")
async def create_file(file: UploadFile = File(...)):
    try:
        contents = await file.read()
        # store contents to the database
    except Exception:
        return {"message": "Error uploading file"}
    finally:
        await file.close()
    return {"message": f"Successfully uploaded {file.filename}"}

上传多个文件:

from fastapi import File, UploadFile
from typing import List

@app.post("/upload")
def upload(files: List[UploadFile] = File(...)):
    for file in files:
        try:
            contents = file.file.read()
            # store contents to the database
        except Exception:
            return {"message": "Error uploading file(s)"}
        finally:
            file.file.close()
    return {"message": f"Successfully uploaded {[file.filename for file in files]}"}

来自 Python 脚本的请求:

requests.post(url="SERVER_URL/create_file", files={"file": (f.name, f, "multipart/form-data")})

以上是如何解决FastAPI上传空文件问题?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn