sqlachemy
https://www.sqlalchemy.org/
面向数据库的ORM工具,其仅仅做ORM工作,不做校验工作。
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.
It provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.
pydantic
https://pydantic-docs.helpmanual.io/
此工具面向输入的数据,对其进行校验,但并不对接数据库。
Documentation for version: v1.9.1
Data validation and settings management using python type annotations.
pydantic enforces type hints at runtime, and provides user friendly errors when data is invalid.
Define how data should be in pure, canonical python; validate it with pydantic.
问题引入
对于一个标准的项目,需要处理这两类问题,需要这两个工具同时使用,
由此会定义两个 数据类型
例如:
https://github.com/fanqingsong/DogeAPI
https://github.com/fanqingsong/DogeAPI/blob/main/models/models.py
#!/usr/bin/python3 from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from database.configuration import Base class Blog(Base): """ Blog class Args: Base (sqlalchemy.ext.declarative.api.Base): Base class """ __tablename__ = "blogs" id = Column(Integer, primary_key=True, index=True) title = Column(String) body = Column(String) user_id = Column(Integer, ForeignKey("users.id")) creator = relationship("User", back_populates="blogs") class User(Base): """ User class Args: Base (sqlalchemy.ext.declarative.api.Base): Base class """ __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) name = Column(String) email = Column(String) password = Column(String) blogs = relationship("Blog", back_populates="creator")
同时
https://github.com/fanqingsong/DogeAPI/blob/main/schema/schemas.py
#!/usr/bin/python3 from typing import List, Optional from pydantic import BaseModel class BlogBase(BaseModel): title: str body: str class Blog(BlogBase): class Config: orm_mode = True class User(BaseModel): name: str email: str password: str class ShowUser(BaseModel): name: str email: str blogs: List[Blog] = [] class Config: orm_mode = True class ShowBlog(BaseModel): title: str body: str creator: ShowUser class Config: orm_mode = True class Login(BaseModel): username: str password: str class Token(BaseModel): access_token: str token_type: str class TokenData(BaseModel): username: Optional[str] = None
sqlmodel — 问题解决办法
https://sqlmodel.tiangolo.com/#sqlalchemy-and-pydantic
fastapi的作者注意到了这个问题,于是发明了此ORM工具。
SQLModel is a library for interacting with SQL databases from Python code, with Python objects. It is designed to be intuitive, easy to use, highly compatible, and robust.
SQLModel is based on Python type annotations, and powered by Pydantic and SQLAlchemy.
The key features are:
- Intuitive to write: Great editor support. Completion everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.
- Easy to use: It has sensible defaults and does a lot of work underneath to simplify the code you write.
- Compatible: It is designed to be compatible with FastAPI, Pydantic, and SQLAlchemy.
- Extensible: You have all the power of SQLAlchemy and Pydantic underneath.
- Short: Minimize code duplication. A single type annotation does a lot of work. No need to duplicate models in SQLAlchemy and Pydantic.
数据类型定义一次, 即可做ORM,也可做pydantic模式
https://sqlmodel.tiangolo.com/tutorial/fastapi/response-model/
from typing import List, Optional from fastapi import FastAPI from sqlmodel import Field, Session, SQLModel, create_engine, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.post("/heroes/", response_model=Hero) def create_hero(hero: Hero): with Session(engine) as session: session.add(hero) session.commit() session.refresh(hero) return hero @app.get("/heroes/", response_model=List[Hero]) def read_heroes(): with Session(engine) as session: heroes = session.exec(select(Hero)).all() return heroes
实例
https://github.com/fanqingsong/fastapi-alembic-sqlmodel-async
原创文章,作者:dweifng,如若转载,请注明出处:https://blog.ytso.com/273933.html