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"}
相关推荐
用户8356290780514 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780514 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生12 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师13 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码13 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf13 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780511 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent1 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6251 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python