关于 python-database-ops
面向 Python 开发者的 SQLAlchemy 2.0 数据库实践技能,涵盖同步与异步用法、查询模式及 FastAPI 会话集成。
主要功能
- 01SQLAlchemy 2.0 ORM 模式
- 02异步会话与引擎
- 03关系定义与查询示例
- 04FastAPI 会话依赖
- 05迁移与连接池指南
适用场景
- 01实现带类型的 SQLAlchemy 模型
- 02构建异步数据库访问
- 03编写常用查询与连接
- 04在 FastAPI 中设置数据库会话
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ 0xdarkmatter/ claude-mods --skill python-database-ops安装后在 Claude Code 中输入/python-database-ops确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/alembic.ini.templatereferences/connection-pooling.mdmigrations.mdsqlalchemy-async.mdtransactions.mdscripts/.gitkeep详细介绍
Python 数据库模式
SQLAlchemy 2.0 与数据库最佳实践。
SQLAlchemy 2.0 基础知识
from sqlalchemy import create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
email: Mapped[str] = mapped_column(String(255), unique=True)
is_active: Mapped[bool] = mapped_column(default=True)
# Create engine and tables
engine = create_engine("postgresql://user:pass@localhost/db")
Base.metadata.create_all(engine)
# Query with 2.0 style
with Session(engine) as session:
stmt = select(User).where(User.is_active == True)
users = session.execute(stmt).scalars().all()
异步 SQLAlchemy
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy import select
# Async engine
engine = create_async_engine(
"postgresql+asyncpg://user:pass@localhost/db",
echo=False,
pool_size=5,
max_overflow=10,
)
# Session factory
async_session = async_sessionmaker(engine, expire_on_commit=False)
# Usage
async with async_session() as session:
result = await session.execute(select(User).where(User.id == 1))
user = result.scalar_one_or_none()
模型关系
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship, Mapped, mapped_column
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
# One-to-many
posts: Mapped[list["Post"]] = relationship(back_populates="author")
class Post(Base):
__tablename__ = "posts"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str]
author_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
# Many-to-one
author: Mapped["User"] = relationship(back_populates="posts")
常见查询模式
from sqlalchemy import select, and_, or_, func
# Basic select
stmt = select(User).where(User.is_active == True)
# Multiple conditions
stmt = select(User).where(
and_(
User.is_active == True,
User.age >= 18
)
)
# OR conditions
stmt = select(User).where(
or_(User.role == "admin", User.role == "moderator")
)
# Ordering and limiting
stmt = select(User).order_by(User.created_at.desc()).limit(10)
# Aggregates
stmt = select(func.count(User.id)).where(User.is_active == True)
# Joins
stmt = select(User, Post).join(Post, User.id == Post.author_id)
# Eager loading
from sqlalchemy.orm import selectinload
stmt = select(User).options(selectinload(User.posts))
FastAPI 集成
from fastapi import Depends, FastAPI
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Annotated
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with async_session() as session:
yield session
DB = Annotated[AsyncSession, Depends(get_db)]
@app.get("/users/{user_id}")
async def get_user(user_id: int, db: DB):
result = await db.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404)
return user
快速参考
| 操作 | SQLAlchemy 2.0 风格 |
|---|---|
| 查询全部 | select(User) |
| 筛选 | .where(User.id == 1) |
| 第一条 | .scalar_one_or_none() |
| 全部 | .scalars().all() |
| 计数 | select(func.count(User.id)) |
| 联接 | .join(Post) |
| 预加载 | .options(selectinload(User.posts)) |
更多资源
./references/sqlalchemy-async.md- 异步模式、会话管理./references/connection-pooling.md- 连接池配置、健康检查./references/transactions.md- 事务模式、隔离级别./references/migrations.md- Alembic 设置、迁移策略
资源文件
./assets/alembic.ini.template- Alembic 配置模板
另请参阅
前置条件:
python-typing-ops- 映射类型和注解python-async-ops- 异步数据库会话
相关技能:
python-fastapi-ops- 数据库会话的依赖注入python-pytest-ops- 数据库固件和测试
评论
支持 Markdown