0

在 FastAPI 项目中,您可以轻松地将数据从 HTML 表单获取到后端。有内置的方法可以从文本输入、文件上传等获取数据。但是,下拉菜单在我的项目中似乎不起作用。FastAPI 开发人员 Tiangolo在被请求后解决了这个问题,制作了一个包含下拉菜单的教程页面。我尝试按照与他相同的步骤进行操作,但无法将下拉菜单中的数据获取到我的后端。

我的代码如下所示:

  • view.py: 包含带有下拉值的枚举,并生成 html 模板。
class dropdownChoices(str, Enum):
    water = "WATER"
    fire = "FIRE"
    electric = "ELECTRIC"
    grass = "GRASS"
    donut = "DONUT"

@router.get('/upload')
def upload(request: Request):
    return templates.TemplateResponse('upload.html', context={'request': request, 'choices': [e.value for e in dropdownChoices]})
  • upload.html:将显示我的表单的模板,包含下拉菜单。
<form action="/upload" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="choices_dropdown">Choose:</label>
        <select id="choices_dropdown" name="dropdown_choices">
            {% for choice in choices %}
            <option value={{choice}}>{{choice}}</option>
            <!-- The choices are correctly displayed in the dropdown menu -->
            {% endfor %}
        </select>
    </div>
    <!-- More form actions including file upload and checkbox. These work. -->
    <div class="form-group">
        <label for="upload_file">Choose Upload File:</label>
        <input type="file" class="form-control-file" name='upload_file' id="upload_file">
        <input class="form-check-input" type="checkbox" name='overwrite_existing' id="flexCheckChecked"> Overwrite existing
    </div>
    <button id="upload" type='submit' class="btn btn-primary">Upload</button>
</form>
  • main.py:处理来自表单的数据。
# Gets data from upload.html
@app.post("/upload")
async def handle_form(request: Request,
                      choice: str = "WATER",
                      upload_file: UploadFile = File(...),
                      overwrite_existing: bool = Form(False)):
    print(choice) #does NOT work: always print default ("WATER")
    print(overwrite_existing) #Works, prints true or false depending on input
    contents = await upload_file.file.read() #Works, file is later read etc
    return templates.TemplateResponse('upload.html', context={'request': request,
                                                              'choices': [e.value for e in view.dropdownChoices]})

我觉得我已经彻底遵循了教程,但我总是得到默认选择。如果我不在我的handle_form()方法中设置默认选项,我将一无所获。我不明白为什么用户从下拉菜单中的选择不像其他人那样被传输。

4

2 回答 2

1

您在表格中的名字是dropdown_choices。您在 FastAPI 端点定义中的名称是choice. 这些必须相同。您还想告诉 FastAPI 这也是一个表单字段(就像您对复选框所做的那样):

choice: str = Form("WATER"), 

您还应该将选项值包装在""

<option value="{{choice}}">

选择框没有什么神奇之处;数据以通常的方式提交——通过GET或通过POST

于 2021-06-18T17:00:06.993 回答
1

您总是会得到默认选择,因为您设置了它,并且它不会以匹配的名称发送。

choice: str = "WATER",

在这里,您说您期望choice的不是枚举而是普通的str,并且您将默认值设置为文字 str "WATER"。但是在您的前端,您将其名称发送为dropdown_choices.

<select id="choices_dropdown" name="dropdown_choices">

此外,通过这样的声明,Fastapi 会期望该值作为查询参数发送,但您的前端将其作为表单数据的一部分作为正文发送。为了让 fastapi 正确地将它放在它所在的位置并正确验证它,您需要同时具有匹配的名称和类型。

async def handle_form(request: Request,
                      dropdown_choices: dropdownChoices = Form(dropdownChoices.water),
                      upload_file: UploadFile = File(...),
                      overwrite_existing: bool = Form(False)):

该值现在使用正确的名称声明,并且应该直接作为枚举进行解析和验证。默认值也被声明为枚举的成员,而不是不相关的 str。

于 2021-06-20T06:45:10.890 回答