官方文档地址:https://fastapi.tiangolo.com/zh/tutorial/request-forms/

接收的不是 JSON,而是表单字段时,要使用 Form

要使用表单,需预先安装 python-multipart:pip install python-multipart

# 从 fastapi 导入 Form
from fastapi import FastAPI, Form app = FastAPI() @app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)): # 定义 Form 参数
return {"username": username}

OAuth2 规范的 "密码流" 模式规定要通过表单字段发送 username 和 password。该规范要求字段必须命名为 username 和 password,并通过表单字段发送,不能用 JSON。

声明表单体要显式使用 Form ,否则,FastAPI 会把该参数当作查询参数或请求体(JSON)参数。

HTML 表单(<form></form>)向服务器发送数据通常使用「特殊」的编码。FastAPI 要确保从正确的位置读取数据,而不是读取 JSON。

表单数据的「媒体类型」编码一般为 application/x-www-form-urlencoded。但包含文件的表单编码为 multipart/form-data

可在一个路径操作中声明多个 Form 参数,但不能同时声明要接收 JSON 的 Body 字段。因为此时请求体的编码是 application/x-www-form-urlencoded,不是 application/json

代码示例

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

main.py

# -*- coding: UTF-8 -*-

from fastapi import FastAPI, Form, Request
from fastapi.templating import Jinja2Templates app = FastAPI()
templates = Jinja2Templates(directory="templates") @app.post("/user/")
async def form_text(request: Request, username: str = Form(...), password: str = Form(...)):
print('username', username)
print('password', password) # return {'text_1':text_1 , 'text_2': text_2}
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)

templates/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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<!-- <link rel="icon" href="../../favicon.ico"> --> <title>Signin Template for Bootstrap</title> <!-- Bootstrap core CSS -->
<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> --> <!-- Custom styles for this template -->
<!-- <link href="../static/css/signin.css" rel="stylesheet"> --> </head> <body> <div class="container"> <h1>HELLO..{{ username }}</h1>
<h1>HELLO..{{ password }}</h1>
</div> <!-- /container --> </body>
</html>

templates/post.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body> <div class="container">
<form action="/user/" enctype="application/x-www-form-urlencoded" method="post">
<label>username</label>
<br>
<input name="username" type="username">
<br>
<label>password</label>
<br>
<input name="password" type="password">
<br><br>
<input type="submit">
</form> </div> </body>
</html>

Form表单数据的更多相关文章

  1. 解析form表单数据

    //解析form表单数据 function parseFormData(params) { var args = new Object(); for(var key in params){ if(!p ...

  2. easyui不提交window中的form表单数据

    <form id="ff" method="post">, <div id="win" class="easyu ...

  3. Django框架获取各种form表单数据

    Django中获取text,password 名字:<input type="text" name="name"><br><br& ...

  4. 3..jquery的ajax获取form表单数据

    jq是对dom进行的再次封装.是一个js库,极大简化了js使用 jquery库在js文件中,包含了所有jquery函数,引用:<script src="jquery-1.11.1.mi ...

  5. html基础:jquery的ajax获取form表单数据

    jq是对dom进行的再次封装.是一个js库,极大简化了js使用 jquery库在js文件中,包含了所有jquery函数,引用:<script src="jquery-1.11.1.mi ...

  6. element-ui中关闭对话框清空验证,清除form表单数据

    对于elementUI中对话框,点击对话框和关闭按钮 怎么清空验证,清空form表单,避免二次点击还会有 验证错误的提示.今天终于自己查资料解决了,分享给大家 1.首先在你的对话框 取消按钮 加一个c ...

  7. Select下拉列表选择自动提交form表单数据

    HTML代码: <form action='__CONTROLLER__/index' method="get" id="myform"> < ...

  8. formset批量处理form表单数据

    Formset(表单集)是多个表单的集合.Formset在Web开发中应用很普遍,它可以让用户在同一个页面上提交多张表单,一键添加多个数据 class StudentStudyRecordModel( ...

  9. JS获取form表单数据

    以下代码可放在一个js文件中,以便通用: //获取指定表单中指定标签对象 function getElements(formId, label) { var form = document.getEl ...

随机推荐

  1. MySQL--数据过滤(AND、OR、IN、NOT操作符)

    MySQL允许给出多个WHERE子句.这些子句可以两种方式使用:以AND子句的方式或OR子句的方式使用. 1.组合WHERE子句 1.1 AND操作符 SELECT prod_id,prod_pric ...

  2. 从编译器对指令集的要求看API设计原则

    摘要:最近看<计算机体系结构:量化研究方法(第五版)>,发现指令集设计中的一些原则,对API设计也同样适用,给大家分享一下. 本文中的所有内容来自工作和学习过程中的心得整理,如需转载请注明 ...

  3. 计算机二级Python(第一阶段)

    介绍   本篇文章主要针对于计算机二级考试的崽崽,当然想了解Python和学习Python的崽崽也是可以看本篇文章的:毕竟,手机和电脑都可以运行Python:本篇我文章虽然是笔记,但是也纯靠手打,希望 ...

  4. Bika LIMS 开源LIMS集—— SENAITE的使用(分析/测试、方法)

    分析/测试项目分类(Test Category) 定义检测项目的分类,例如理化检测.微生物检测,或者按样品的维度定义,例如食品检测.水质检测等. 分析方法(Test Method) 定义实验室分析方法 ...

  5. YII学习总结6(模板替换和“拼合”)

    controller\helloController.php<?php namespace app\controllers; use yii\web\Controller; class hell ...

  6. Mac os:将Homebrew的下载源换成国内镜像增加下载速度(阿里云镜像)

    原文转载自「刘悦的技术博客」https://v3u.cn/a_id_135 可能所有的mac os系统爱好者都遇到过下面这种倒霉情况,在网络环境不太好的时候,你满怀期待的敲下 brew install ...

  7. CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) A-E

    比赛链接 A 题解 知识点:思维,模拟. 发现 \(b\) 串第一个字符是 \(1\) 则只能使用 max , \(0\) 则只能使用 min ,随后只需要模拟到 \(a\) 串剩余 \(m\) 个字 ...

  8. 针对单个球体的World类

    好了,终于到了可以看到图片的环节了.之前的类,你一定要实现好了.所有关于World类的报错,现在我们一个一个解决来了. 先看看World类的声明: #pragma once #ifndef __WOR ...

  9. 论文解读(NWR)《Graph Auto-Encoder via Neighborhood Wasserstein Reconstruction》

    论文信息 论文标题:Graph Auto-Encoder via Neighborhood Wasserstein Reconstruction论文作者:Shaked Brody, Uri Alon, ...

  10. ModelBox开发体验:使用YOLOv3做口罩检测

    摘要:本案例将在ModelBox中使用YOLO v3模型,实现一个简单的口罩检测应用 本文分享自华为云社区<ModelBox开发体验Day05开发案例-使用YOLOv3做口罩检测>,作者: ...