[FastAPI-03]Form表单

1. 安装依赖

pip install -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com python-multipart

2. 表单程序

.
├── post_test_1.py
└── templates
    ├── index.html
    └── post.html

2.1 post_test_1.py

# _*_ coding: UTF-8 _*_
from fastapi import FastAPI,Form
from starlette.requests import Request
from starlette.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="../templates")

@app.post("/user/")
async def create_upload_files(request: Request,username:str =Form(),password:str = Form()):
    print('username',username)
    print('password',password)
    
    return templates.TemplateResponse('index.html',{'request':request,'username':username,'password':password})


@app.get("/")
async def main(request: Request):
    return templates.TemplateResponse('post.html',{'request':request})



if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app,host='127.0.0.1',port=8000)

2.2 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello FastAPI</h1>
    <h2>{{ username }}</h2>
    <h2>{{ password }}</h2>
</body>
</html>

2.3 post.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width= , initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="container">
        <form action="/user/" enctype="application/x-www-form-urlencoded" method="post">
            <label>username</label>
            <br>
            <input type="username" name="username">
            <br>
            <label>password</label>
            <br>
            <input type="password" name="password">
            <br><br>
            <input type="submit">
        </form>
    </div>
</body>
</html>
posted @   LeoShi2020  阅读(60)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示