FastAPI 等效于 Flask 的 request.form,用于不可知的表单 [英] FastAPI equivalent of Flask's request.form, for agnostic forms

查看:45
本文介绍了FastAPI 等效于 Flask 的 request.form,用于不可知的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从 Flask 迁移到 FastAPI,我想知道是否有类似于 Flask 的东西:

I try to migrate from Flask to FastAPI, and I was wondering if there is something similar to Flask's:

payload = request.form.to_dict(flat=False)
payload = {key:payload[key][0] for key in payload}

用于 FastAPI.

for FastAPI.

到目前为止,我只发现了一些技巧,您是否仍然需要将表单的所有参数一一实现给函数:

Until now I've found only some hacks, were you still had to implement one-by-one all the form's arguments to a function:

from pydantic import BaseModel
class FormData(BaseModel):
    alfa: str=Form(...)
    vita: str=Form(...)
async def Home(request: Request, form_data:FormData)

这个例子的可读性当然比标准的表单处理要好:

This example is of course better in readability than the standard form handling:

async def Home(username: str = Form(...), something_else: str = Form(...)):

但由于所有表单字段的必要声明,它仍然非常受限.

But still it's quite restricting, due to the necessary declaration of all form fields.

还有其他更不可知论者吗?优雅的方法?

Is there any other more agnostic & elegant approach?

提前致谢 &如果这是我无法通过谷歌搜索找到的微不足道的问题,我深表歉意:)

Thanks in advance & I apologize if this a trivial question I've failed to find through googling :)

推荐答案

你可以获得底层的starlette request 并使用它的 request.form() 方法.它需要 python-multipart 才能工作:

You can get the underlying starlette request and use its request.form() method. It requires python-multipart to work:

from fastapi import FastAPI, Request

app = FastAPI()

@app.post("/example")
async def example(request: Request):
    form_data = await request.form()
    return form_data

调用示例:

C:\>curl -X POST "http://localhost:8000/example" -d "hello=there&another=value"
{"hello":"there","another":"value"}

这篇关于FastAPI 等效于 Flask 的 request.form,用于不可知的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆