我正在创建一个FastAPI Python应用程序,用户上传要处理的文件。我不希望文件超过X大小(以字节为单位)。
如何在POST请求将文件存储在内存中之前限制文件上载大小?
我正在使用uivcorn进行测试,但我希望使用(GCP)部署这段代码。我不确定这是否可以在python代码端或服务器配置端完成。
代码片段:
from fastapi import (
FastAPI,
Path,
File,
UploadFile,
)
app = FastAPI()
@app.post("/")
async def root(file: UploadFile = File(...)):
text = await file.read()
text = text.decode("utf-8")
return len(text)发布于 2022-05-22 19:01:02
我找到了一个python库,它通过FastAPI中间件来处理这个问题。如果上传文件太大,它将引发413 HTTP错误;“错误:请求实体太大”
from starlette_validation_uploadfile import ValidateUploadFileMiddleware
from fastapi import (
FastAPI,
Path,
File,
UploadFile,
)
app = FastAPI()
#add this after FastAPI app is declared
app.add_middleware(
ValidateUploadFileMiddleware,
app_path="/",
max_size=1048576, #1Mbyte
file_type=["text/plain"]
)
@app.post("/")
async def root(file: UploadFile = File(...)):
#...do something with the file
return {"status: upload successful"}发布于 2022-05-23 11:20:32
它通常由web服务器(如nginx或Apache )控制,但如果您想在服务器端进行控制,可以使用以下代码:
from fastapi import (
FastAPI,
Path,
File,
UploadFile,
)
app = FastAPI()
@app.post("/")
async def root(file: UploadFile = File(...)):
if len(await file.read()) >= 8388608:
return {"Your file is more than 8MB"}https://stackoverflow.com/questions/72338900
复制相似问题