强制执行架构

Python 中的 MongoDB 入门

Filip Schouwenaars

Machine Learning Researcher

从灵活到受验证的架构

  • MongoDB 允许在无固定架构下存储数据
  • 适合快速原型和演进数据模型
mov.insert_one({
    "title": "knives out",
    "genre": ["comedy", "crime", "drama"],
    "year": 2019, # oops
    "rating": 7.9,
})

mov.find_one({ "title": "knives out", "release_year": 2019 })
  • 当架构已明确时,应配置验证
Python 中的 MongoDB 入门

用 pydantic 强制执行架构

  • 数据验证库
  • 定义期望的字段及其类型
  • 每个文档的蓝图
from pydantic import BaseModel
from typing import Optional

class Movie(BaseModel):
    title: str
    genre: list[str]
    release_year: int
    rating: float
    won_oscar: Optional[bool] = None
Python 中的 MongoDB 入门

使用类型化数据模型插入

# 之前
new_movie = {
  "title": "knives out",
  "genre": ["comedy", "crime", "drama"],
  "year": 2019, # oops
  "rating": 7.9,
}
# 无输出
  • 无数据格式检查
# 现在
new_movie = Movie(
  title = "knives out",
  genre = ["comedy", "crime", "drama"],
  year = 2019, # oops
  rating = 7.9,
)
pydantic.error_wrappers.ValidationError:
1 validation error for Movie
release_year: field required
  • 在写入集合前就能捕获拼写错误和缺失字段!
Python 中的 MongoDB 入门

修复我们的错误

from pydantic import BaseModel
from typing import Optional

class Movie(BaseModel):
    title: str
    genre: list[str]
    release_year: int
    rating: float
    won_oscar: Optional[bool] = None 
# 字段与取值均正确
new_movie = Movie(
  title = "knives out",
  genre = ["comedy", "crime", "drama"],
  release_year = 2019,
  rating = 7.9,
)

mov.insert_one(dict(new_movie))
InsertOneResult(...)
Python 中的 MongoDB 入门

MongoDB 内置的架构验证

client.film.create_collection(
  "movies_v2",
  validator={
    "$jsonSchema": {
      "required": ["title", "genre", "release_year", "rating"],
      "properties": {
        "title": { "bsonType": "string" },
        "genre": { 
          "bsonType": "array",
          "items": { "bsonType": "string" }
        },
        "release_year": { "bsonType": "int" },
        "rating": { "bsonType": "double" },
        "won_oscar": { "bsonType": "bool" }
      }
    }
  }
)
Python 中的 MongoDB 入门

测试 MongoDB 的内置架构验证

client.film.movies_v2.insert_one({
  "title": "knives out",
  "genre": ["comedy", "crime", "drama"],
  "year": 2019, # oops
  "rating": 7.9,
})
pymongo.errors.WriteError: Document failed validation, [...]
'missingProperties': ['release_year'], 'errmsg': 'Document failed validation'}
  • 数据库级的架构验证
  • 对所有访问 MongoDB 的应用生效
Python 中的 MongoDB 入门

小结

  • 应用端验证:pydantic.BaseModel
  • 数据库端验证:MongoDB 内置架构验证
  • 防止错误
  • 强制结构一致
Python 中的 MongoDB 入门

Passons à la pratique !

Python 中的 MongoDB 入门

Preparing Video For Download...