相关疑难解决方法(0)

如何使用 FastAPI 从 Pydantic 模型中排除可选未设置值?

我有这个模型:

class Text(BaseModel):
    id: str
    text: str = None


class TextsRequest(BaseModel):
    data: list[Text]
    n_processes: Union[int, None]
Run Code Online (Sandbox Code Playgroud)

所以我希望能够接受如下请求:

{"data": ["id": "1", "text": "The text 1"], "n_processes": 8} 
Run Code Online (Sandbox Code Playgroud)

{"data": ["id": "1", "text": "The text 1"]}.
Run Code Online (Sandbox Code Playgroud)

现在在第二种情况下我得到

{'data': [{'id': '1', 'text': 'The text 1'}], 'n_processes': None}
Run Code Online (Sandbox Code Playgroud)

使用此代码:

app = FastAPI()

@app.post("/make_post/", response_model_exclude_none=True)
async def create_graph(request: TextsRequest):
    input_data = jsonable_encoder(request)
Run Code Online (Sandbox Code Playgroud)

n_processes那么这里我该如何排除呢?

python optional-parameters pydantic fastapi

10
推荐指数
2
解决办法
2万
查看次数

使用fastapi上传文件

我根据官方文档使用fastapi上传文件,就像:

@app.post("/create_file/")
async def create_file(file: UploadFile=File(...)):
      file2store = await file.read()
      # some code to store the BytesIO(file2store) to the other database
Run Code Online (Sandbox Code Playgroud)

当我使用 python requests lib 发送请求时:

f = open(".../file.txt", 'rb')
files = {"file": (f.name, f, "multipart/form-data")}
requests.post(url="SERVER_URL/create_file", files=files)
Run Code Online (Sandbox Code Playgroud)

file2store 始终为空。有时(很少见),它可以获取文件字节,但几乎所有时间都是空的,所以我无法在另一个数据库上恢复文件。我还尝试了 'bytes' 而不是 'UploadFile',我得到了相同的结果。我的代码有什么地方不对,还是我使用fastapi上传文件的方式有问题?我google了很长时间,但没有成功。所以我在这里提出问题,希望知道答案的人可以帮助我。谢谢

python file-upload fastapi

8
推荐指数
2
解决办法
2万
查看次数

FastAPI UploadFile 与 Flask 相比慢

我创建了一个端点,如下所示:

@app.post("/report/upload")
def create_upload_files(files: UploadFile = File(...)):
        try:
            with open(files.filename,'wb+') as wf:
                wf.write(file.file.read())
                wf.close()
        except Exception as e:
            return {"error": e.__str__()}
Run Code Online (Sandbox Code Playgroud)

它是用 uvicorn 启动的:

../venv/bin/uvicorn test_upload:app --host=0.0.0.0 --port=5000 --reload
Run Code Online (Sandbox Code Playgroud)

我正在执行一些测试,使用 Python 请求上传大约100 MB的文件,大约需要 128 秒:

../venv/bin/uvicorn test_upload:app --host=0.0.0.0 --port=5000 --reload
Run Code Online (Sandbox Code Playgroud)

我使用 Flask 通过 API 端点测试了相同的上传脚本,大约需要 0.5 秒:

f = open(sys.argv[1],"rb").read()
hex_convert = binascii.hexlify(f)
items = {"files": hex_convert.decode()}
start = time.time()
r = requests.post("http://192.168.0.90:5000/report/upload",files=items)
end = time.time() - start
print(end)
Run Code Online (Sandbox Code Playgroud)

我做错了什么吗?

python upload file-upload starlette fastapi

7
推荐指数
1
解决办法
9998
查看次数