Token导航 LogoToken导航

Agent Skill · 开发

python-backend-expert(Python backend expert 测试)

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

python-backend-expert 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 12,141。

总安装 1,420周安装 58GitHub Stars 8下载 455核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:python-backend-expert(Python backend expert 测试)
来源仓库:https://github.com/hieutrtr/ai1-skills
仓库路径:skills/python-backend-expert
安装命令:
npx skills add https://github.com/hieutrtr/ai1-skills --skill python-backend-expert
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/hieutrtr/ai1-skills --skill python-backend-expert

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

python-backend-expert 用于辅助 Python 项目开发、测试和依赖管理。适合让 Agent 阅读 Python 代码、定位测试问题或整理运行命令,需确认虚拟环境和依赖版本。涉及执行脚本或访问数据库时,应先明确运行目录和输入输出范围,避免误改生产数据。

通过 npx skills add 命令从指定 GitHub 仓库安装,需确认权限和维护状态。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

来源仓库内路径:skills/python-backend-expert

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/hieutrtr/ai1-skills --skill python-backend-exp…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

python-backend-expert 怎么安装?

在终端执行 npx skills add https://github.com/hieutrtr/ai1-skills --skill python-backend-expert。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

python-backend-expert 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

python-backend-expert 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

python-backend-expert 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

python-backend-expert 用的人多吗?

公开数据是累计安装 1,420 次,近一周安装 58 次,下载 455 次,GitHub 8 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

python-backend-expert 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
python-backend-expert

Python backend expert 测试 · 本页

1,4208需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Python Backend Expert

When to Use

Activate this skill when:

  • Creating or modifying FastAPI route handlers (endpoints)
  • Defining or updating Pydantic v2 request/response schemas
  • Writing SQLAlchemy 2.0 async models, queries, or relationships
  • Implementing the repository pattern for data access
  • Writing service layer business logic
  • Creating or running Alembic migrations
  • Setting up dependency injection chains with Depends()
  • Handling errors across the route/service/repository layers

Do NOT use this skill for:

  • Writing tests for backend code (use pytest-patterns)
  • FastAPI framework mechanics — middleware, WebSockets, OpenAPI customization, CORS, lifespan (use fastapi-patterns)
  • Deployment or CI/CD pipeline configuration (use deployment-pipeline)
  • API contract design or endpoint planning (use api-design-patterns)
  • Architecture decisions or layer design (use system-architecture)

Instructions

Project Structure

app/
├── main.py              # FastAPI application factory
├── core/
│   ├── config.py        # pydantic-settings configuration
│   ├── database.py      # Async engine, session factory
│   └── security.py      # Password hashing, JWT utilities
├── models/              # SQLAlchemy ORM models
│   ├── __init__.py
│   ├── base.py          # Declarative base
│   └── user.py
├── schemas/             # Pydantic v2 schemas
│   ├── __init__.py
│   └── user.py
├── repositories/        # Data access layer
│   ├── __init__.py
│   └── user_repo.py
├── services/            # Business logic layer
│   ├── __init__.py
│   └── user_service.py
├── routes/              # FastAPI routers
│   ├── __init__.py
│   └── users.py
├── dependencies/        # Reusable Depends() providers
│   ├── __init__.py
│   └── auth.py
└── exceptions.py        # Domain exception classes

FastAPI Endpoint Pattern

Every endpoint follows this structure:

router = APIRouter(prefix="/users", tags=["Users"])

@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(
    data: UserCreate,
    session: AsyncSession = Depends(get_async_session),
) -> UserResponse:
    service = UserService(session)
    try:
        user = await service.create_user(data)
        return UserResponse.model_validate(user)
    except ConflictError as e:
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))

@router.get("/{user_id}", response_model=UserResponse)
async def get_user(
    user_id: int,
    session: AsyncSession = Depends(get_async_session),
) -> UserResponse:
    service = UserService(session)
    try:
        user = await service.get_user(user_id)
        return UserResponse.model_validate(user)
    except NotFoundError as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))

Rules:

  • Routes handle HTTP concerns only: status codes, HTTPException, response formatting
  • Routes call services, never repositories directly
  • Use response_model for automatic response serialization and OpenAPI docs
  • Use status.HTTP_* constants, not bare integers
  • Use Depends() for session, auth, and service injection

Repository Pattern

Repositories encapsulate all database access:

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.models.user import User

class UserRepository:
    def __init__(self, session: AsyncSession) -> None:
        self._session = session

    async def get_by_id(self, user_id: int) -> User | None:
        result = await self._session.execute(
            select(User).where(User.id == user_id)
        )
        return result.scalar_one_or_none()

    async def get_by_email(self, email: str) -> User | None:
        result = await self._session.execute(
            select(User).where(User.email == email)
        )
        return result.scalar_one_or_none()

    async def list_with_posts(
        self, *, offset: int = 0, limit: int = 20
    ) -> list[User]:
        result = await self._session.execute(
            select(User)
            .options(selectinload(User.posts))
            .offset(offset)
            .limit(limit)
        )
        return list(result.scalars().all())

    async def create(self, user: User) -> User:
        self._session.add(user)
        await self._session.flush()
        await self._session.refresh(user)
        return user

    async def update(self, user: User, **kwargs: object) -> User:
        for key, value in kwargs.items():
            setattr(user, key, value)
        await self._session.flush()
        await self._session.refresh(user)
        return user

    async def delete(self, user: User) -> None:
        await self._session.delete(user)
        await self._session.flush()

Rules:

  • One repository per model (or aggregate root)
  • Repositories return model instances or None — never HTTP responses
  • No business logic in repositories
  • Always flush() + refresh() after add() to get generated fields (id, timestamps)
  • Use selectinload() for eager loading relationships in async context
  • Never raise HTTPException from repositories

Service Layer Pattern

Services contain business logic and orchestrate repositories:

from app.exceptions import ConflictError, NotFoundError
from app.models.user import User
from app.repositories.user_repo import UserRepository
from app.schemas.user import UserCreate, UserPatch
from app.core.security import hash_password

class UserService:
    def __init__(self, session: AsyncSession) -> None:
        self.repo = UserRepository(session)

    async def create_user(self, data: UserCreate) -> User:
        # Business rule: email must be unique
        existing = await self.repo.get_by_email(data.email)
        if existing:
            raise ConflictError(f"Email {data.email} already registered")

        # Business logic: hash password before storing
        user = User(
            email=data.email,
            hashed_password=hash_password(data.password),
            display_name=data.display_name,
        )
        return await self.repo.create(user)

    async def get_user(self, user_id: int) -> User:
        user = await self.repo.get_by_id(user_id)
        if user is None:
            raise NotFoundError(f"User {user_id} not found")
        return user

    async def update_user(self, user_id: int, data: UserPatch) -> User:
        user = await self.get_user(user_id)
        update_fields = data.model_dump(exclude_unset=True)
        if "password" in update_fields:
            update_fields["hashed_password"] = hash_password(update_fields.pop("password"))
        return await self.repo.update(user, **update_fields)

Rules:

  • Services raise domain exceptions (NotFoundError, ConflictError), NEVER HTTPException
  • Services are the only place for business logic
  • Services call repositories for data access, never run raw queries
  • Services receive AsyncSession via constructor and create their own repository instances
  • Services validate business rules before calling repositories

Domain Exceptions

Define a hierarchy of domain exceptions:

class AppError(Exception):
    """Base application error."""

class NotFoundError(AppError):
    """Resource not found."""

class ConflictError(AppError):
    """Resource conflict (duplicate, version mismatch)."""

class ValidationError(AppError):
    """Business rule violation."""

class PermissionError(AppError):
    """Insufficient permissions."""

Register global exception handlers in the FastAPI app:

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

app = FastAPI()

@app.exception_handler(NotFoundError)
async def not_found_handler(request: Request, exc: NotFoundError) -> JSONResponse:
    return JSONResponse(status_code=404, content={"detail": str(exc), "code": "NOT_FOUND"})

@app.exception_handler(ConflictError)
async def conflict_handler(request: Request, exc: ConflictError) -> JSONResponse:
    return JSONResponse(status_code=409, content={"detail": str(exc), "code": "CONFLICT"})

This allows services to raise domain exceptions without knowing about HTTP, and routes don't need try/except blocks.

Pydantic v2 Schema Conventions

from datetime import datetime
from pydantic import BaseModel, ConfigDict, EmailStr, Field

class UserCreate(BaseModel):
    """POST request body — writable fields only, no id/timestamps."""
    email: EmailStr
    password: str = Field(min_length=8, max_length=128)
    display_name: str = Field(min_length=1, max_length=100)

class UserPatch(BaseModel):
    """PATCH request body — all fields Optional."""
    email: EmailStr | None = None
    password: str | None = Field(default=None, min_length=8, max_length=128)
    display_name: str | None = Field(default=None, min_length=1, max_length=100)

class UserResponse(BaseModel):
    """Response body — all fields including id and timestamps."""
    model_config = ConfigDict(from_attributes=True)

    id: int
    email: str
    display_name: str
    is_active: bool
    created_at: datetime
    updated_at: datetime

Key Pydantic v2 patterns:

  • Use ConfigDict(from_attributes=True) instead of class Config: orm_mode = True
  • Use model_validate() instead of from_orm()
  • Use model_dump() instead of .dict()
  • Use model_dump(exclude_unset=True) for PATCH to distinguish "not sent" from "set to null"
  • Use Field() for validation constraints
  • Use str | None syntax (Python 3.12+), not Optional[str]

Async Session Management

from collections.abc import AsyncGenerator
from sqlalchemy.ext.asyncio import (
    AsyncSession,
    async_sessionmaker,
    create_async_engine,
)

from app.core.config import settings

engine = create_async_engine(
    settings.database_url,
    echo=settings.debug,
    pool_size=5,
    max_overflow=10,
    pool_pre_ping=True,
)

async_session_factory = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
)

async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
    async with async_session_factory() as session:
        async with session.begin():
            yield session

Rules:

  • expire_on_commit=False prevents detached instance errors after commit
  • session.begin() context manager auto-commits on success, rolls back on exception
  • One session per request via Depends(get_async_session)
  • Never share sessions across concurrent tasks
  • For background tasks, create a new session — never reuse the request session

SQLAlchemy 2.0 Model Pattern

from datetime import datetime
from sqlalchemy import String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship

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, index=True)
    hashed_password: Mapped[str] = mapped_column(String(255))
    display_name: Mapped[str] = mapped_column(String(100))
    is_active: Mapped[bool] = mapped_column(default=True)
    created_at: Mapped[datetime] = mapped_column(server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        server_default=func.now(), onupdate=func.now()
    )

    # Relationships — ALWAYS use selectin or joined for async
    posts: Mapped[list["Post"]] = relationship(
        back_populates="author", lazy="selectin"
    )

Rules:

  • Use Mapped[type] annotations (SQLAlchemy 2.0 style)
  • Use mapped_column() instead of Column()
  • Set lazy="selectin" on relationships for async compatibility
  • Use server_default for database-generated defaults
  • Always include created_at and updated_at timestamps

Alembic Migration Workflow

# Generate migration from model changes
alembic revision --autogenerate -m "add_users_table"

# Review the generated migration file before applying

# Apply migration
alembic upgrade head

# Rollback one step
alembic downgrade -1

# Show current revision
alembic current

# Show migration history
alembic history

Migration naming convention:

# alembic/env.py
naming_convention = {
    "ix": "ix_%(column_0_label)s",
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}

Rules:

  • Always review autogenerated migrations before applying
  • Every migration must have a working downgrade() function
  • One migration per logical schema change
  • Test both upgrade and downgrade
  • Use descriptive migration messages: "add_users_table", "add_email_index_to_users"

Dependency Injection Pattern

from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_async_session
from app.services.user_service import UserService

async def get_user_service(
    session: AsyncSession = Depends(get_async_session),
) -> UserService:
    return UserService(session)

# Chain dependencies for auth
async def get_current_user(
    token: str = Depends(oauth2_scheme),
    session: AsyncSession = Depends(get_async_session),
) -> User:
    user_id = decode_token(token)
    service = UserService(session)
    return await service.get_user(user_id)

async def require_admin(
    user: User = Depends(get_current_user),
) -> User:
    if user.role != "admin":
        raise HTTPException(status_code=403, detail="Admin required")
    return user

Examples

Complete Request Flow

A request to POST /users flows through all layers:

  1. Route receives UserCreate (Pydantic validates the request body)
  2. Route calls UserService.create_user(data) via Depends()
  3. Service checks business rule (email uniqueness) via UserRepository.get_by_email()
  4. Service hashes password, creates User model instance
  5. Service calls UserRepository.create(user) to persist
  6. Repository adds to session, flushes, refreshes to get generated fields
  7. Route converts the ORM model to UserResponse via model_validate()

If the email is duplicate, the service raises ConflictError, the global exception handler returns 409 Conflict. No try/except needed in the route.

Edge Cases

  • Detached instance errors: Always call flush() + refresh() after session.add(). Set expire_on_commit=False on the session factory.
  • Async session in background tasks: Never reuse the request session. Create a new session: async def background_job(): async with async_session_factory() as session: async with session.begin(): # do work
  • N+1 queries: Use selectinload() in repository queries for relationships that will be accessed. Set lazy="selectin" as the default on model relationships.
  • Bulk operations: Use session.execute(insert(User).values(list_of_dicts)) for bulk inserts instead of adding one by one.
  • Transaction spanning multiple services: Pass the same session to all services. The session's begin() context manager handles the transaction boundary.
  • Pydantic v2 computed fields: Use @computed_field for derived values in response schemas. See references/pydantic-v2-migration.md.

See references/sqlalchemy-patterns.md for advanced query optimization patterns.

平台分布

Codex

34.38%
按下载量换算156

Claude

31.23%
按下载量换算142

Cursor

20.86%
按下载量换算95

Gemini CLI

10.37%
按下载量换算47

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills