2 比 1 更容易理解,可以先看2(單文件級別)
1、FastAPI 框架 操作Mysql數(shù)據(jù)庫(項目多文件級別)
FastAPI 可以使用任何您想要的關(guān)系型數(shù)據(jù)庫。
在這里,讓我們看一個使用著SQLAlchemy的示例。
您可以很容易地將SQLAlchemy支持任何數(shù)據(jù)庫,像:
- PostgreSQL
- MySQL
- SQLite
- Oracle
- Microsoft SQL Server,等等其它數(shù)據(jù)庫
在此示例中,我們將使用SQLite,因為它使用單個文件并且 在Python中具有集成支持。因此,您可以復(fù)制此示例并按原樣來運行它。
稍后,對于您的產(chǎn)品級別的應(yīng)用程序,您可能會要使用像PostgreSQL這樣的數(shù)據(jù)庫服務(wù)器。
1.0 創(chuàng)建mysql數(shù)據(jù)庫
-
創(chuàng)建test數(shù)據(jù)庫,數(shù)據(jù)庫創(chuàng)建users表和items表
-
users表
- items表
1.1 測試項目文件結(jié)構(gòu)
對于這些示例,假設(shè)您有一個名為的目錄my_super_project,其中包含一個名為的子目錄sql_app,其結(jié)構(gòu)如下:
.
└── sql_app
├── __init__.py
├── crud.py
├── database.py
├── main.py
├── models.py
└── schemas.py
該文件__init__.py只是一個空文件,但它告訴 Python 其中sql_app的所有模塊(Python 文件)都是一個包。
1.2 數(shù)據(jù)庫配置 database.py
# 1、導(dǎo)入 SQLAlchemy 部件
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 連接mysql數(shù)據(jù)庫需要導(dǎo)入pymysql模塊
import pymysql
pymysql.install_as_MySQLdb()
# 2、為 SQLAlchemy 定義數(shù)據(jù)庫 URL地址
# 配置數(shù)據(jù)庫地址:數(shù)據(jù)庫類型+數(shù)據(jù)庫驅(qū)動名稱://用戶名:密碼@機器地址:端口號/數(shù)據(jù)庫名
SQLALCHEMY_DATABASE_URL = "mysql://test:123456@127.0.0.1:3306/test"
# 3、創(chuàng)建 SQLAlchemy 引擎
engine = create_engine(SQLALCHEMY_DATABASE_URL, encoding='utf-8')
# 4、創(chuàng)建數(shù)據(jù)庫會話
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# 5、創(chuàng)建一個Base類declarative_base
# 稍后我們將用這個類繼承,來創(chuàng)建每個數(shù)據(jù)庫模型或類(ORM 模型)
Base = declarative_base()
1.3 創(chuàng)建數(shù)據(jù)庫模型 models.py
用Base類來創(chuàng)建 SQLAlchemy 模型
我們將使用我們之前創(chuàng)建的Base類來創(chuàng)建 SQLAlchemy 模型。
SQLAlchemy 使用的“模型”這個術(shù)語 來指代與數(shù)據(jù)庫交互的這些類和實例。
而 Pydantic 也使用“模型”這個術(shù)語 來指代不同的東西,即數(shù)據(jù)驗證、轉(zhuǎn)換以及文檔類和實例。
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
# 1、從database.py導(dǎo)入Base類
from .database import Base
# User繼承Base類
class User(Base):
# 表名
__tablename__ = "users"
# 2、創(chuàng)建模型屬性/列,使用Column來表示 SQLAlchemy 中的默認值。
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
is_active = Column(Boolean, default=True)
# 3、創(chuàng)建關(guān)系
# 當訪問 user 中的屬性items時,如 中my_user.items,它將有一個ItemSQLAlchemy 模型列表(來自items表),這些模型具有指向users表中此記錄的外鍵
# 當您訪問my_user.items時,SQLAlchemy 實際上會從items表中的獲取一批記錄并在此處填充進去。
# 同樣,當訪問 Item中的屬性owner時,它將包含表中的UserSQLAlchemy 模型users。使用owner_id屬性/列及其外鍵來了解要從users表中獲取哪條記錄。
items = relationship("Item", back_populates="owner")
# Item繼承Base類
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, index=True)
owner_id = Column(Integer, ForeignKey("users.id"))
owner = relationship("User", back_populates="items")
創(chuàng)建關(guān)系
items = relationship("Item", back_populates="owner")
- 當訪問 user 中的屬性items時,如 中my_user.items,它將有一個ItemSQLAlchemy 模型列表(來自items表),這些模型具有指向users表中此記錄的外鍵
- 當您訪問my_user.items時,SQLAlchemy 實際上會從items表中的獲取一批記錄并在此處填充進去。
- 同樣,當訪問 Item中的屬性owner時,它將包含表中的-UserSQLAlchemy 模型users。使用owner_id屬性/列及其外鍵來了解要從users表中獲取哪條記錄。
1.4 創(chuàng)建 Pydantic 模型 schemas.py
現(xiàn)在讓我們查看一下文件sql_app/schemas.py。
為了避免 SQLAlchemy模型和 Pydantic模型之間的混淆,我們將有models.py(SQLAlchemy 模型的文件)和schemas.py( Pydantic 模型的文件)。
這些 Pydantic 模型或多或少地定義了一個“schema”(一個有效的數(shù)據(jù)形狀)。
因此,這將幫助我們在使用兩者時避免混淆。
創(chuàng)建初始 Pydantic模型/模式?
創(chuàng)建一個ItemBase和UserBasePydantic模型(或者我們說“schema”)以及在創(chuàng)建或讀取數(shù)據(jù)時具有共同的屬性。
ItemCreate為 創(chuàng)建一個UserCreate繼承自它們的所有屬性(因此它們將具有相同的屬性),以及創(chuàng)建所需的任何其他數(shù)據(jù)(屬性)。
因此在創(chuàng)建時也應(yīng)當有一個password屬性。
但是為了安全起見,password不會出現(xiàn)在其他同類 Pydantic模型中,例如用戶請求時不應(yīng)該從 API 返回響應(yīng)中包含它。
from typing import List, Union
# 1、創(chuàng)建初始 Pydantic模型/模式
from pydantic import BaseModel
# 1、創(chuàng)建初始 Pydantic模型/模式
class ItemBase(BaseModel):
title: str
description: Union[str, None] = None
# 1、創(chuàng)建初始 Pydantic模型/模式
class ItemCreate(ItemBase):
pass
# 2、創(chuàng)建用于讀取/返回的Pydantic模型/模式
class Item(ItemBase):
id: int
owner_id: int
class Config:
orm_mode = True
# 1、創(chuàng)建初始 Pydantic模型/模式
class UserBase(BaseModel):
email: str
# 1、創(chuàng)建初始 Pydantic模型/模式
class UserCreate(UserBase):
password: str
# 2、創(chuàng)建用于讀取/返回的Pydantic模型/模式
class User(UserBase):
id: int
is_active: bool
items: List[Item] = []
class Config:
orm_mode = True
請注意,讀取用戶(從 API 返回)時將使用不包括password的User Pydantic模型。
SQLAlchemy 風格和 Pydantic 風格
請注意,SQLAlchemy模型使用 =來定義屬性,并將類型作為參數(shù)傳遞給Column,例如:
name = Column(String)
雖然 Pydantic模型使用: 聲明類型,但新的類型注釋語法/類型提示是:
name: str
請牢記這一點,這樣您在使用:還是=時就不會感到困惑。
1.5 CRUD工具 crud.py
從 sqlalchemy.orm中導(dǎo)入Session,這將允許您聲明db參數(shù)的類型,并在您的函數(shù)中進行更好的類型檢查和完成。文章來源:http://www.zghlxwxcb.cn/news/detail-792955.html
導(dǎo)入之前的models(SQLAlchemy 模型)和schemas(Pydantic模型/模式)。文章來源地址http://www.zghlxwxcb.cn/news/detail-792955.html
from sqlalchemy.orm import Session
from . import models, schemas
def get_user(db: Session, user_id: int):
return db.query(models.User).filter(models.User.id == user_id).first()
# 通過 ID 和電子郵件查詢單個用戶
def get_user_by_email(db: Session, email: str):
return db.query(models.User).filter(models.User.email == email).first()
# 查詢多個用戶
def get_users(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.User).offset(skip).limit(limit).all()
def create_user(db: Session, user: schemas.UserCreate):
fake_hashed_password = user.password + "notreallyhashed"
# 使用您的數(shù)據(jù)創(chuàng)建一個 SQLAlchemy 模型實例。
db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
# 使用add來將該實例對象添加到您的數(shù)據(jù)庫。
db.add(db_user)
# 使用commit來對數(shù)據(jù)庫的事務(wù)提交(以便保存它們)。
db.commit()
# 使用refresh來刷新您的數(shù)據(jù)庫實例(以便它包含來自數(shù)據(jù)庫的任何新數(shù)據(jù),例如生成的 ID)。
db.refresh(db_user)<
到了這里,關(guān)于Python FastAPI 框架 操作Mysql數(shù)據(jù)庫 增刪改查的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!