Python(FastAPI)中ORM框架Sqlalchemy的安装及建表

一,项目中安装Sqlalchemy

在项目中执行,就会自动安装

python 复制代码
pip install sqlalchemy[asyncio] aiomysql

二,建表

流程

(1)创建数据库引擎

python 复制代码
# 1.创建异步引擎
#ASYNC_DATAASE_URL为数据库的地址
ASYNC_DATAASE_URL = "mysql+aiomysql://root:630229@localhost:3306/fast_api_db?charset=utf8"
async_engine = create_async_engine(
    ASYNC_DATAASE_URL,
    echo=True, # 可选删除SQL日志
    pool_size=10, #设置连接池活跃的连接数
    max_overflow=20, # 允许额外的连接数

)

(2)定义模型类

python 复制代码
# 2.定义模型类: 基类+表对应的模型类
# 基类:创建时间、更新时间;书籍表:id、书名、作者、价格、出版社
class Base(DeclarativeBase):

    create_time: Mapped[datetime] = mapped_column(
        DateTime,
        insert_default=func.now(),
        default=datetime.now,
        comment="创建时间"
    )
    update_time: Mapped[datetime] = mapped_column(
        DateTime,
        insert_default=func.now(),
        onupdate=func.now(),
        default=datetime.now,
        comment="修改时间"
    )


class Book(Base):
    __tablename__ = "book"
    id: Mapped[int] = mapped_column(primary_key=True, comment="书籍id")
    bookname: Mapped[str] = mapped_column(String(255), comment="书名")
    author: Mapped[str] = mapped_column(String(255), comment="作者")
    price: Mapped[float] = mapped_column(comment="价格")
    publisher: Mapped[str] = mapped_column(String(255), comment="出版社")

(3)启动应用建表

启动命令

python 复制代码
uvicorn main:app --reload
python 复制代码
# 3.启动应用时建表,FASTAPI启动时调用建表的函数
async def create_tables():
    #创建异步引擎,创建事务建表
    async with async_engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all) #模型类的元数据


@app.on_event("startup")
async def startup_event():
    await create_tables()


@app.get("/")
async def root():
    return {"message": "Hello World"}

查看建表

表以建成功

或者在Navicat 中查看

完整代码

python 复制代码
from fastapi import FastAPI
from datetime import datetime
from sqlalchemy import String, DateTime, func
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

app = FastAPI()

# 1.创建异步引擎
#ASYNC_DATAASE_URL为数据库的地址
ASYNC_DATAASE_URL = "mysql+aiomysql://root:630229@localhost:3306/fast_api_db?charset=utf8"
async_engine = create_async_engine(
    ASYNC_DATAASE_URL,
    echo=True, # 可选删除SQL日志
    pool_size=10, #设置连接池活跃的连接数
    max_overflow=20, # 允许额外的连接数

)

# 2.定义模型类: 基类+表对应的模型类
# 基类:创建时间、更新时间;书籍表:id、书名、作者、价格、出版社
class Base(DeclarativeBase):

    create_time: Mapped[datetime] = mapped_column(
        DateTime,
        insert_default=func.now(),
        default=datetime.now,
        comment="创建时间"
    )
    update_time: Mapped[datetime] = mapped_column(
        DateTime,
        insert_default=func.now(),
        onupdate=func.now(),
        default=datetime.now,
        comment="修改时间"
    )


class Book(Base):
    __tablename__ = "book"
    id: Mapped[int] = mapped_column(primary_key=True, comment="书籍id")
    bookname: Mapped[str] = mapped_column(String(255), comment="书名")
    author: Mapped[str] = mapped_column(String(255), comment="作者")
    price: Mapped[float] = mapped_column(comment="价格")
    publisher: Mapped[str] = mapped_column(String(255), comment="出版社")


# 3.启动应用时建表,FASTAPI启动时调用建表的函数
async def create_tables():
    #创建异步引擎,创建事务建表
    async with async_engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all) #模型类的元数据


@app.on_event("startup")
async def startup_event():
    await create_tables()


@app.get("/")
async def root():
    return {"message": "Hello World"}
相关推荐
weixin_447195294 小时前
【无标题】
pytorch·python
迅猛龙办公室4 小时前
Python实现简单的人名对话
python
阿坨5 小时前
firestart:一行命令启动你的日常应用和网页
python·pypi·cli·click
老歌老听老掉牙5 小时前
麻花钻切屑形态演变的力学机制与临界条件分析
python·算法·钻头
happylifetree6 小时前
Python18(补充):练习
python
weixin_416667966 小时前
银河麒麟V10看门狗试验-1
网络·chrome·python
古城小栈7 小时前
Pydantic 从入门到实践全讲解
python
happylifetree7 小时前
Python18:核心语法-数据存储与运算-运算符-算术运算符
python
打工仔折腾 AI7 小时前
从Attention到BERT:双向预训练语言模型到底解决了什么问题
人工智能·后端·python·深度学习·语言模型·bert
迅猛龙办公室7 小时前
实现第一个python程序(HelloWorld)
开发语言·python