这是我参与8月更文挑战的第12天,活动详情查看:8月更文挑战
何为 Form 表单
相信你一定听过或者见过 HTMl 的 form 元素,这里所指的 Form 表单就是 FastApi 用来获取 HTML 中 form 元素的对象。
在 FastApi 中使用 Form 表单
假设我们需要开发一个登陆的界面,登陆页面有一个 form 表单,其中包含用户名和密码两个元素,我们需要根据前端页面传回来的 form 表单内容来确定是否登陆成功。
项目结构
代码
from fastapi import FastAPI
# 导入Request上下文对象,用来在前后台之间传递参数
from starlette.requests import Request
# 导入jinja2模板引擎对象,用于后续使用
from starlette.templating import Jinja2Templates
app=FastAPI()
# 实例化一个模板引擎对象,指定模板所在路径
templates=Jinja2Templates(directory='templates')
# 定义主页函数,返回登陆页面
@app.get('/')
async def welcome(request:Request):
return templates.TemplateResponse(name='login.html',context={'request':request})
# 导入Form表单
from fastapi import Form
@app.post('/login/')
# 视图函数接收post请求体中的Form表单元素
async def login(request:Request,username=Form(...),pwd=Form(...)):
# 登陆逻辑演示
if username=='phyger' and pwd =='phyger666':
return templates.TemplateResponse(name='index.html',context={'request':request,'result':'SUCCESS'})
else:
return templates.TemplateResponse(name='index.html',context={'request':request,'result':'FAILED'})
if __name__ == '__main__':
import uvicorn
uvicorn.run(app='main:app',host='127.0.0.1',port=8765,reload=True)
打开首页
输入正确的用户名和密码
输入错误的用户名和密码
分析:我们使用
FastApi的Form对象来接收前端传过来的form表单对象。其中接收前端form表单对象时使用的变量名需要和from表单中的name保持一致。
附:login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<form action="/login/" enctype="application/x-www-form-urlencoded" method="POST">
<table>
<tbody>
<tr><td>用户名:</td><td><input type="text" name="username"></td></tr>
<tr><td>密码:</td><td><input type="password" name="pwd"></td></tr>
</tbody>
</table>
<input type='submit' style="font-size: medium;">
</form>
</body>
</html>
以上,我们简单演示了 FastApi 处理 Form 表单的基本用法。
感谢您的阅读,别忘了关注,点赞,评论,转发四连哟!