python - 使用 FastAPI 从下拉菜单中获取数据
问题描述
在 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()
方法中设置默认选项,我将一无所获。我不明白为什么用户从下拉菜单中的选择不像其他人那样被传输。
解决方案
您在表格中的名字是dropdown_choices
。您在 FastAPI 端点定义中的名称是choice
. 这些必须相同。您还想告诉 FastAPI 这也是一个表单字段(就像您对复选框所做的那样):
choice: str = Form("WATER"),
您还应该将选项值包装在""
:
<option value="{{choice}}">
选择框没有什么神奇之处;数据以通常的方式提交——通过GET
或通过POST
。
推荐阅读
- javascript - 传单插件未加载
- time-complexity - 总和等于给定数 n 的最小平方数的时间复杂度
- docker - Traefik 未检测到在 network_mode=host (192.168.99.x) 中运行的容器
- html - 全部大写 在 Firefox 的下拉列表中选择选项值
- emacs - 为什么键绑定会导致 Emacs 在启动时执行我的功能?
- date - 表格排序日期不正确
- node.js - 用户与服务器断开连接时无法获取 voiceStateUpdate
- validation - Micronaut 中奇怪的验证错误处理
- typescript - TypeScript 尝试使用 Yarn Workspaces 编译兄弟文件夹的 node_modules
- excel - 刷新多维数据集时 SSAS 驱动程序错误