[英]FastAPI/Pydantic in a project with MyPy
我目前正在处理fastAPI教程,并且我的环境设置为black,flake8,bandit和mypy。 教程中的所有内容都可以正常工作,但是我仍然必须输入#:忽略使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")
我可以#类型:忽略,但是随后我在编辑器中丢失了类型提示和验证。 我是否遗漏了明显的内容,还是应该仅禁用Mypy for FastAPI项目?
您可以使用Optional
:
from typing import Optional
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
这告诉mypy
该值应该是该类型,但是None
是可以接受的。
如果您使用的是mypy,它可能会抱怨类型声明,例如:
tax: float = None
出现以下错误:分配中的类型不兼容(表达式的类型为“ None”,变量的类型为“ float”)在这种情况下,您可以使用Optional告诉mypy该值可以为None,例如:
tax: Optional[float] = None
在上面的代码中,请观看此视频,此视频已在此处说明的基本模型中进行了说明
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.