python-backend-expert by oimiragieo/agent-studio
npx skills add https://github.com/oimiragieo/agent-studio --skill python-backend-expert在审查或编写代码时,请遵循以下准则:
在审查或编写代码时,请遵循以下准则:
在审查或编写代码时,请遵循以下准则:
在审查或编写代码时,请遵循以下准则:
在审查或编写代码时,请遵循以下准则:
在审查或编写代码时,请遵循以下准则:
在审查或编写代码时,请遵循以下准则:
在审查或编写代码时,请遵循以下准则:
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
在审查或编写代码时,请遵循以下准则:
在审查或编写代码时,请遵循以下准则:
在审查或编写代码时,请遵循以下准则:
db_default 来设置数据库计算的默认值(例如,db_default=Now()),而不是使用应由数据库拥有值的 Python 端默认值ModelAdmin.show_facets),以便在筛选选项旁显示计数async 原生查询集方法——在异步视图中优先使用 await qs.acount()、await qs.afirst()、async for obj in qsMIDDLEWARE 列表进行声明式中间件配置;对于高吞吐量的 ASGI 部署,优先使用支持异步的中间件LoginRequiredMiddleware(Django 5.1+)而不是装饰每个视图GeneratedField 处理数据库生成的列(在数据库级别从其他列计算得出)在审查或编写代码时,请遵循以下准则:
使用 lifespan 上下文管理器(而非已弃用的 @app.on_event)进行启动/关闭资源管理:
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager async def lifespan(app: FastAPI): # 启动:初始化数据库连接池、HTTP 客户端、缓存 app.state.db_pool = await create_pool() yield # 关闭:关闭资源 await app.state.db_pool.close()
app = FastAPI(lifespan=lifespan)
对所有请求/响应模式使用 Pydantic v2 模型;Pydantic v2 是 FastAPI 0.100+ 的默认版本。使用 model_config = ConfigDict(...) 而不是内部的 class Config
使用带有 lru_cache 的 pydantic-settings(BaseSettings)进行配置管理:
from functools import lru_cache
from pydantic_settings import BaseSettings
class Settings(BaseSettings): database_url: str model_config = ConfigDict(env_prefix="APP_")
@lru_cache def get_settings() -> Settings: return Settings()
正确界定依赖范围:每个请求(数据库会话、身份验证)、路由器级别(审计日志记录、命名空间缓存)、应用程序生命周期(Kafka 生产者、功能标志 SDK、追踪导出器)
使用带有 Depends 的 Annotated 类型提示以获得更清晰的依赖签名:
from typing import Annotated
from fastapi import Depends
DbSession = Annotated[AsyncSession, Depends(get_db)] CurrentUser = Annotated[User, Depends(get_current_user)]
按领域组织项目结构:routers/、services/、repositories/、schemas/、models/——避免在原型之外使用扁平的单一文件应用
对于 I/O 密集型路由,优先使用 async def 路径操作;仅对应在线程池中运行的 CPU 密集型工作使用 def(同步)
使用带有 prefix、tags 和 dependencies 的 APIRouter 来分组相关路由并应用共享中间件
在审查或编写代码时,请遵循以下准则:
使用 create_async_engine + async_sessionmaker(不要直接使用已弃用的 AsyncSession 工厂);在应用程序启动时为每个服务创建一个引擎
使用新的 Mapped + mapped_column 声明式风格(SQLAlchemy 2.0+),而不是传统的 Column 风格:
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String
class Base(DeclarativeBase): pass
class User(Base): tablename = "users" id: Mapped[int] = mapped_column(primary_key=True) email: Mapped[str] = mapped_column(String(255), unique=True) is_active: Mapped[bool] = mapped_column(default=True)
使用 async with 会话作用域,通过 FastAPI 依赖注入提供数据库会话:
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
async_session = async_sessionmaker(engine, expire_on_commit=False)
async def get_db() -> AsyncGenerator[AsyncSession, None]: async with async_session() as session: yield session
在 SQLAlchemy 2.0+ 中,所有查询都使用 select()(而不是传统的 session.query())
在异步上下文中,显式使用 selectinload / joinedload 以避免隐式延迟加载 I/O(延迟加载在异步环境中会引发 MissingGreenlet 错误)
对于 upsert 操作,使用 insert().on_conflict_do_update()(PostgreSQL)或特定数据库方言的等效方法,而不是单独的 select + update 往返
使用适合异步的连接池大小:异步驱动(asyncpg、aiomysql)比同步驱动需要更小的连接池;对于中等负载,pool_size=5, max_overflow=10 是一个安全的默认值
在审查或编写代码时,请遵循以下准则:
python3.13t(无 GIL 构建)禁用 GIL。在为 3.13+ 编写的新代码中,避免假设 GIL 对共享可变状态的保护;使用显式锁或线程安全的数据结构。未经对所有 C 扩展的全面测试,请勿在生产环境中启用无 GIL 模式PYTHON_JIT=1 启用。为紧密循环和数值计算代码提供可观的加速。无需更改代码;只需了解其存在,以便用于性能敏感的服务t"..." 字符串字面量,延迟插值,适用于构建安全的 SQL/HTML 而无需注入风险。在构建动态查询或 HTML 片段时,优先使用 T-字符串而不是 f-字符串from __future__ import annotations)。这以零运行时成本解决了类型提示中的前向引用问题interpreters 标准库模块通过子解释器实现真正的并行性,而无需禁用 GIL。适用于以前需要多进程处理的 CPU 密集型工作负载pyproject.toml(不仅仅是 setup.py / requirements.txt);使用 uv 或 pip 配合 pyproject.toml 进行可复现的依赖管理pyproject.toml 的 requires-python 字段中指定最低 Python 版本此专家技能整合了 1 项独立技能:
lifespan 上下文管理器进行 FastAPI 启动/关闭资源管理——@app.on_event 已弃用,并将在未来版本中移除。session.query()——使用带有 2.0 风格 API 的 select();传统查询 API 将被移除。async def 或 run_in_executor,以避免事件循环饥饿。| 反模式 | 失败原因 | 正确方法 |
|---|---|---|
使用 @app.on_event 进行启动/关闭 | 在 FastAPI 中已弃用;版本升级时会中断 | 使用带有 lifespan 参数的 @asynccontextmanager |
在 SQLAlchemy 2.0+ 中使用 session.query() | 传统查询 API 已弃用并将被移除 | 使用 select() 语句配合 session.execute() |
使用 f-字符串或 % 格式化构建 SQL 字符串 | SQL 注入漏洞;严重的安全缺陷 | 通过 ORM 或带有绑定参数的 text() 使用参数化查询 |
在 async def 路由中直接调用阻塞 I/O | 阻塞整个事件循环;导致级联延迟 | 使用可等待的异步驱动;对同步代码使用 loop.run_in_executor() |
| 将业务逻辑放在 FastAPI 路径函数中 | 将路由与逻辑耦合;使单元测试无法进行 | 将逻辑提取到服务/仓库层;通过 Depends() 注入 |
开始前:
cat .claude/context/memory/learnings.md
完成后: 记录发现的任何新模式或例外情况。
假设中断:您的上下文可能会重置。如果它不在记忆中,那就没有发生。
每周安装次数
74
仓库
GitHub 星标数
19
首次出现
2026年1月27日
安全审计
安装于
github-copilot72
cursor71
gemini-cli70
opencode70
kimi-cli69
codex69
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
When reviewing or writing code, apply these guidelines:
db_default on model fields (e.g., db_default=Now()) instead of Python-side defaults where the database should own the valueModelAdmin.show_facets) to get counts alongside filter optionsasync-native queryset methods — prefer await qs.acount(), await qs.afirst(), async for obj in qs in async viewsMIDDLEWARE list; async-capable middleware is preferred for high-throughput ASGI deploymentsLoginRequiredMiddleware (Django 5.1+) instead of decorating every view when all views require authenticationWhen reviewing or writing code, apply these guidelines:
Use the lifespan context manager (not deprecated @app.on_event) for startup/shutdown resource management:
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager async def lifespan(app: FastAPI): # startup: initialize DB pool, HTTP clients, caches app.state.db_pool = await create_pool() yield # shutdown: close resources await app.state.db_pool.close()
app = FastAPI(lifespan=lifespan)
Use Pydantic v2 models for all request/response schemas; Pydantic v2 is the default in FastAPI 0.100+. Use model_config = ConfigDict(...) instead of the inner class Config
Use pydantic-settings (BaseSettings) with lru_cache for config management:
When reviewing or writing code, apply these guidelines:
Use create_async_engine + async_sessionmaker (not the deprecated AsyncSession factory directly); create one engine per service at application startup
Use the new Mapped + mapped_column declarative style (SQLAlchemy 2.0+) instead of the legacy Column style:
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String
class Base(DeclarativeBase): pass
class User(Base): tablename = "users" id: Mapped[int] = mapped_column(primary_key=True) email: Mapped[str] = mapped_column(String(255), unique=True) is_active: Mapped[bool] = mapped_column(default=True)
Provide the DB session via FastAPI dependency injection using async with session scope:
When reviewing or writing code, apply these guidelines:
python3.13t (free-threaded build). Avoid assuming GIL protection for shared mutable state in new code targeting 3.13+; use explicit locks or thread-safe data structures. Do not enable free-threaded mode in production without thorough testing of all C extensionsPYTHON_JIT=1. Provides measurable speedups for tight loops and numeric code. No code changes needed; just be aware it exists for performance-sensitive servicest"..." string literals that defer interpolation, useful for safe SQL/HTML construction without injection risk. Prefer T-strings over f-strings when building dynamic queries or HTML fragmentsfrom __future__ import annotations needed). This resolves forward-reference issues in type hints at zero runtime costThis expert skill consolidates 1 individual skills:
lifespan context manager for FastAPI startup/shutdown resource management — @app.on_event is deprecated and will be removed in a future release.session.query() in SQLAlchemy 2.0+ — use select() with the 2.0-style API; legacy query API will be removed.async def with awaitable drivers or run_in_executor for blocking operations to avoid event loop starvation.| Anti-Pattern | Why It Fails | Correct Approach |
|---|---|---|
Using @app.on_event for startup/shutdown | Deprecated in FastAPI; will break on version upgrade | Use @asynccontextmanager with lifespan parameter |
Using session.query() in SQLAlchemy 2.0+ | Legacy query API is deprecated and will be removed | Use select() statements with session.execute() |
Building SQL strings with f-strings or % formatting |
Before starting:
cat .claude/context/memory/learnings.md
After completing: Record any new patterns or exceptions discovered.
ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.
Weekly Installs
74
Repository
GitHub Stars
19
First Seen
Jan 27, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykFail
Installed on
github-copilot72
cursor71
gemini-cli70
opencode70
kimi-cli69
codex69
agent-browser 浏览器自动化工具 - Vercel Labs 命令行网页操作与测试
163,300 周安装
GeneratedField for database-generated columns (computed from other columns at the DB level)from functools import lru_cache
from pydantic_settings import BaseSettings
class Settings(BaseSettings): database_url: str model_config = ConfigDict(env_prefix="APP_")
@lru_cache def get_settings() -> Settings: return Settings()
Scope dependencies correctly: per-request (DB sessions, auth), router-level (audit logging, namespace caches), application lifespan (Kafka producers, feature flag SDKs, tracing exporters)
Use Annotated type hints with Depends for cleaner dependency signatures:
from typing import Annotated
from fastapi import Depends
DbSession = Annotated[AsyncSession, Depends(get_db)] CurrentUser = Annotated[User, Depends(get_current_user)]
Structure projects by domain: routers/, services/, repositories/, schemas/, models/ — avoid flat single-file apps beyond prototypes
Prefer async def path operations for I/O-bound routes; use def (sync) only for CPU-bound work that should run in a thread pool
Use APIRouter with prefix, tags, and dependencies to group related routes and apply shared middleware
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
async_session = async_sessionmaker(engine, expire_on_commit=False)
async def get_db() -> AsyncGenerator[AsyncSession, None]: async with async_session() as session: yield session
Use select() (not the legacy session.query()) for all queries in SQLAlchemy 2.0+
Use selectinload / joinedload explicitly to avoid implicit lazy-load I/O in async contexts (lazy loading raises MissingGreenlet in async)
For upserts, use insert().on_conflict_do_update() (PostgreSQL) or the dialect-specific equivalent rather than separate select + update round trips
Use connection pool sizing appropriate for async: async drivers (asyncpg, aiomysql) need smaller pools than sync drivers; pool_size=5, max_overflow=10 is a safe default for moderate load
interpreterspyproject.toml (not setup.py / requirements.txt alone) for all new projects; use uv or pip with pyproject.toml for reproducible dependency managementpyproject.toml requires-python field| SQL injection vulnerability; critical security flaw |
Use parameterized queries via ORM or text() with bound params |
Calling blocking I/O directly in async def routes | Blocks the entire event loop; causes cascading latency | Use awaitable async drivers; loop.run_in_executor() for sync code |
| Putting business logic in FastAPI path functions | Couples routing to logic; makes unit testing impossible | Extract logic to service/repository layer; inject via Depends() |