FastAPI学习笔记(一)-13.请求表单

一、请求为表单时的写法

使用了from fastapi import Form

Form是对表单的每个字段做验证

FastAPI学习笔记(一)-13.请求表单
 1 '''
 2 @author:invoker
 3 @project:fastapi202108
 4 @file: chapter043.py
 5 @contact:invoker2021@126.com
 6 @descript:
 7 @Date:2021/8/6 17:53
 8 @version: Python 3.7.8
 9 '''
10 
11 """Form Data 表单数据处理"""
12 
13 from fastapi import APIRouter, Form
14 
15 # Form类来自python-multipart包
16 app043 = APIRouter()
17 
18 
19 @app043.post("/login")
20 async def login(username: str = Form(...,title="用户名称",max_length=20,min_length=8),
21                 password: str = Form(...,title="用户密码",min_length=8,max_length=20)):  # 定义表单
22     return {"username": username,"password":password}
View Code

接口:http://127.0.0.1:8000/chapter043/login

 表单:

返回:

{ "username": "invoker12354", "password": "1231415124" }

 

二、使用BaseModel并不能发送表单,仍然发送的是json

FastAPI学习笔记(一)-13.请求表单
 1 '''
 2 @author:invoker
 3 @project:fastapi202108
 4 @file: chapter043.py
 5 @contact:invoker2021@126.com
 6 @descript:
 7 @Date:2021/8/6 17:53
 8 @version: Python 3.7.8
 9 '''
10 
11 """Form Data 表单数据处理"""
12 
13 from fastapi import APIRouter, Form
14 from pydantic import BaseModel,Field
15 
16 # Form类来自python-multipart包
17 app043 = APIRouter()
18 # curl -X 'POST' \
19 #   'http://127.0.0.1:8000/chapter043/login' \
20 #   -H 'accept: application/json' \
21 #   -H 'Content-Type: application/x-www-form-urlencoded' \
22 #   -d 'username=invoker12345&password=1234545644'
23 
24 class LoginModel(BaseModel):
25     loginName:str=Form(...,title='登录用户名称',min_length=5,max_length=20)
26     password:str = Form(...,title='登录密码',min_length=5,max_length=20)
27 
28 # /login接口使用的是表单类型
29 @app043.post("/login")
30 async def login(username: str = Form(...,title="用户名称",max_length=20,min_length=8),
31                 password: str = Form(...,title="用户密码",min_length=8,max_length=20)):  # 定义表单
32     return {"username": username,"password":password}
33 
34 
35 # /login2还是使用的json格式:
36 # curl -X 'POST' \
37 #   'http://127.0.0.1:8000/chapter043/login2' \
38 #   -H 'accept: application/json' \
39 #   -H 'Content-Type: application/json' \
40 #   -d '{
41 #   "loginName": "1",
42 #   "password": "2"
43 # }'
44 @app043.post("/login2")
45 async def login2(login:LoginModel):
46     return {"username": login.loginName,"password":login.password}
View Code

 

上一篇:fastapi_cache2的安装


下一篇:FastAPI数据库系列(一) MySQL数据库操作