使用 pydantic 进行模式验证
现在轮到您了!使用 pydantic 在 MongoDB 操作中强制执行模式,定义一个 Movie 类,并用它来创建您将要插入的新电影。如果在创建新电影时有拼写错误,pydantic 应该会报错!
本练习是课程的一部分
Python 中的 MongoDB 入门
练习说明
- 进行相应的导入:from
pydanticimportBaseModel,以及 fromtypingimportOptional。 - 完成
Movie类的定义,使genre为字符串列表并完善其余字段。 - 完成
new_movie的定义。它于 2012 年上映,评分为 8.0。 - 将该电影插入到名为
mov的 movies 集合中。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Do the appropriate imports
from ____ import BaseModel
from typing import ____
# Complete definition of Movie class
class Movie(____):
title: str
genre: ____[____]
release_year: int
____: float
won_oscar: ____[bool] = None
# Finish the details
new_movie = ____(
title = "the avengers",
genre = ["action", "adventure", "sci-fi"],
____ = ____,
rating = ____
)
# Insert the movie into the movies collection (mov)
mov.____