python - 使用 MyPy 的项目中的 FastAPI/Pydantic
问题描述
我目前正在学习 fastAPI 教程,我的环境设置为 black、flake8、bandit 和 mypy。本教程中的所有内容都运行良好,但我一直不得不 # type: ignore things 让 mypy 合作。
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post("/items/")
async def create_items(item: Item) -> Item:
return item
Mypy 然后错误:
❯ mypy main.py [14:34:08]
main.py:9: error: Incompatible types in assignment (expression has type "None", variable has type "str")
main.py:11: error: Incompatible types in assignment (expression has type "None", variable has type "float")
我可以 # type: ignore ,但是我在编辑器中丢失了类型提示和验证。我是否遗漏了一些明显的东西,还是应该为 FastAPI 项目禁用 mypy?
解决方案
您可以使用Optional
:
from typing import Optional
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
这mypy
表明该值应该属于该类型,但None
可以接受。
推荐阅读
- mysql - 如何在具有多个 WHERE 条件的单个 SQL 查询中获取多个 COUNT?
- excel - Excel VBA - 需要获取可变大小的行
- c - C中的学生单链表,无法从另一个函数中创建的节点访问所有字段
- python - Python:将消息编码为 base64 以解决“!” 和行长问题
- excel-formula - 不保留条件格式
- python - Flask-Sockets keepalive
- css - 使用调整大小的屏幕查看页面时,屏幕右侧显示黑色背景
- r - 具有 2 个键(不是层次结构)的 tsibble,以一年中的一周为索引
- amazon-web-services - 用户数据未在私有 VPC 子网中的 EC2 实例上运行
- java - 如何在java中读取文本文件中的列数