Token导航 LogoToken导航

Agent Skill · 研究检索

python(Python 开发)

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

python 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证为 MIT,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 30,203。

总安装 2,916周安装 124GitHub Stars 38下载 1,022核验 2026-05-01

安装说明

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

安装方式

通过对话安装

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

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

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/martinholovsky/claude-skills-generator --skill python

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

python 用于辅助 Python 项目开发、测试和依赖管理。适合阅读代码、定位测试问题或生成运行脚本。使用时需确认虚拟环境、依赖版本和测试入口,避免误改生产数据。通过 npx skills add 命令从指定 GitHub 仓库安装并使用。python 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/python

上手步骤

4 步
  1. 1

    确认自己的宿主工具

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

  2. 2

    拿到安装命令

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

  3. 3

    安装后重启宿主

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

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

python 怎么安装?

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

python 支持哪些 AI 工具?

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

python 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

python 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

python 用的人多吗?

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

python 安全吗?

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

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

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。
  • 需要许可证清楚、并且有第三方扫描结果的团队项目。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

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

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
python

Python 开发 · 本页

2,91638接触敏感数据MIT通过

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

SKILL.md 原文

Python Backend Development Skill

File Organization

This skill uses a split structure for HIGH-RISK requirements:

  • SKILL.md: Core principles, patterns, and essential security (this file)
  • references/security-examples.md: Complete CVE details and OWASP implementations
  • references/advanced-patterns.md: Advanced Python patterns and optimization
  • references/threat-model.md: Attack scenarios and STRIDE analysis

Validation Gates

GateStatusNotes
0.1 Domain ExpertisePASSEDType safety, async, security, testing
0.2 Vulnerability ResearchPASSED5+ CVEs documented (2025-11-20)
0.5 Hallucination CheckPASSEDExamples tested on Python 3.11+
0.11 File OrganizationSplitHIGH-RISK, ~450 lines + references

1. Overview

Risk Level: HIGH

Justification: Python backend services handle authentication, database access, file operations, and external API communication. Vulnerabilities in input validation, deserialization, command execution, and cryptography can lead to data breaches and system compromise.

You are an expert Python backend developer specializing in secure, maintainable, and performant services.

Core Expertise Areas

  • Type annotations and runtime validation
  • Async programming with asyncio
  • Security: input validation, cryptography, secrets management
  • Testing: pytest, property-based testing, security testing
  • Database access with SQLAlchemy/asyncpg
  • API development with FastAPI/Starlette

2. Core Responsibilities

Fundamental Principles

  1. TDD First: Write tests before implementation, design API through test cases
  2. Performance Aware: Use async, generators, efficient data structures by default
  3. Type Safety: Use type hints everywhere, validate at runtime boundaries
  4. Defense in Depth: Multiple validation layers, fail securely
  5. Secure Defaults: Use safe libraries, reject unsafe operations
  6. Explicit over Implicit: Clear error handling, explicit dependencies
  7. Testability: Design for testing, write security tests

Decision Framework

SituationApproach
User inputValidate with Pydantic, sanitize output
Database queriesUse ORM or parameterized queries, never format strings
File operationsValidate paths, use pathlib, check containment
SubprocessUse list args, never shell=True with user input
SecretsLoad from environment or secret manager
CryptographyUse cryptography library, never roll your own

2.1 Implementation Workflow (TDD)

Step 1: Write Failing Test First

import pytest
from my_service import UserService, UserNotFoundError

class TestUserService:
    @pytest.mark.asyncio
    async def test_get_user_returns_user_when_exists(self, db_session):
        service = UserService(db_session)
        user_id = await service.create_user("alice", "alice@example.com")
        user = await service.get_user(user_id)
        assert user.username == "alice"

    @pytest.mark.asyncio
    async def test_get_user_raises_when_not_found(self, db_session):
        service = UserService(db_session)
        with pytest.raises(UserNotFoundError):
            await service.get_user(99999)

    @pytest.mark.asyncio
    async def test_create_user_validates_email(self, db_session):
        service = UserService(db_session)
        with pytest.raises(ValueError, match="Invalid email"):
            await service.create_user("bob", "not-an-email")

Step 2: Implement Minimum to Pass

class UserNotFoundError(Exception): pass

class UserService:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def get_user(self, user_id: int) -> User:
        user = await self.db.get(User, user_id)
        if not user:
            raise UserNotFoundError(f"User {user_id} not found")
        return user

    async def create_user(self, username: str, email: str) -> int:
        if "@" not in email:
            raise ValueError("Invalid email format")
        # ... minimal implementation to pass tests

Step 3: Refactor if Needed

  • Extract common patterns, add type hints, ensure errors don't leak internals

Step 4: Run Full Verification

pytest --cov=src           # All tests pass
mypy src/ --strict         # Type check passes
bandit -r src/ -ll         # Security scan passes
pip-audit && safety check  # Dependencies clean

2.2 Performance Patterns

Pattern 1: Async I/O with asyncio.gather

# BAD: Sequential requests (slow)
for url in urls:
    response = await client.get(url)  # Waits for each one

# GOOD: Concurrent requests with gather
tasks = [client.get(url) for url in urls]
responses = await asyncio.gather(*tasks)  # All at once

Pattern 2: Generators for Large Data Processing

# BAD: Load all into memory
return [process(line) for line in f.readlines()]  # OOM risk

# GOOD: Generator yields one at a time
def process_large_file(filepath: str) -> Iterator[dict]:
    with open(filepath) as f:
        for line in f:
            yield process(line)  # Memory efficient

Pattern 3: Efficient Data Structures

# BAD: List for membership testing - O(n)
required in user_perms_list  # Slow for large lists

# GOOD: Set for membership testing - O(1)
required in user_perms_set  # Fast lookup

# BAD: Repeated string concatenation
result = ""; for f in fields: result += f + ", "  # Creates new string each time

# GOOD: Join for string building
", ".join(fields)  # Single allocation

Pattern 4: Connection Pooling

# BAD: New connection per request
engine = create_async_engine(DATABASE_URL)  # Connection overhead each time

# GOOD: Reuse pooled connections
engine = create_async_engine(DATABASE_URL, pool_size=20, max_overflow=10)
async_session = sessionmaker(engine, class_=AsyncSession)

async def get_user(user_id: int):
    async with async_session() as session:  # Reuses pooled connection
        return await session.get(User, user_id)

Pattern 5: Batch Database Operations

# BAD: Individual inserts (N round trips)
for user in users:
    db.add(User(**user)); await db.commit()  # N commits = slow

# GOOD: Batch insert (1 round trip)
stmt = insert(User).values(users)
await db.execute(stmt); await db.commit()  # Single commit

# GOOD: Chunked for very large datasets
for i in range(0, len(users), 1000):
    await db.execute(insert(User).values(users[i:i+1000]))
await db.commit()

3. Technical Foundation

Version Recommendations

CategoryVersionNotes
LTS/RecommendedPython 3.11+Performance improvements, better errors
MinimumPython 3.9Security support until Oct 2025
AvoidPython 3.8-EOL, no security patches

Security Dependencies

# pyproject.toml
[project]
dependencies = [
    "pydantic>=2.0", "email-validator>=2.0",      # Validation
    "cryptography>=41.0", "argon2-cffi>=21.0",    # Cryptography
    "PyJWT>=2.8", "sqlalchemy>=2.0", "asyncpg>=0.28",
    "httpx>=0.25", "bandit>=1.7",
]

[project.optional-dependencies]
dev = ["pytest>=7.0", "pytest-asyncio>=0.21", "hypothesis>=6.0", "safety>=2.0", "pip-audit>=2.0"]

4. Implementation Patterns

Pattern 1: Type-Safe Input Validation

from pydantic import BaseModel, Field, field_validator, EmailStr
from typing import Annotated
import re

class UserCreate(BaseModel):
    """Validated user creation request."""
    username: Annotated[str, Field(min_length=3, max_length=50)]
    email: EmailStr
    password: Annotated[str, Field(min_length=12)]

    @field_validator('username')
    @classmethod
    def validate_username(cls, v: str) -> str:
        if not re.match(r'^[a-zA-Z0-9_-]+$', v):
            raise ValueError('Username must be alphanumeric')
        return v

    @field_validator('password')
    @classmethod
    def validate_password_strength(cls, v: str) -> str:
        if not all([re.search(r'[A-Z]', v), re.search(r'[a-z]', v), re.search(r'\d', v)]):
            raise ValueError('Password needs uppercase, lowercase, and digit')
        return v

Pattern 2: Secure Password Hashing

from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError

ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4)

def hash_password(password: str) -> str:
    return ph.hash(password)

def verify_password(password: str, hash: str) -> bool:
    try:
        ph.verify(hash, password)
        return True
    except VerifyMismatchError:
        return False

Pattern 3: Safe Database Queries

from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession

# NEVER: f"SELECT * FROM users WHERE username = '{username}'"

async def get_user_safe(db: AsyncSession, username: str) -> User | None:
    stmt = select(User).where(User.username == username)
    result = await db.execute(stmt)
    return result.scalar_one_or_none()

async def search_users(db: AsyncSession, pattern: str) -> list:
    stmt = text("SELECT * FROM users WHERE username LIKE :pattern")
    result = await db.execute(stmt, {"pattern": f"%{pattern}%"})
    return result.fetchall()

Pattern 4: Safe File Operations

from pathlib import Path

def safe_read_file(base_dir: Path, user_filename: str) -> str:
    if '..' in user_filename or user_filename.startswith('/'):
        raise ValueError("Invalid filename")

    file_path = (base_dir / user_filename).resolve()
    if not file_path.is_relative_to(base_dir.resolve()):
        raise ValueError("Path traversal detected")

    return file_path.read_text()

Pattern 5: Safe Subprocess Execution

import subprocess

ALLOWED_PROGRAMS = {'git', 'python', 'pip'}

def run_command_safe(program: str, args: list[str]) -> str:
    if program not in ALLOWED_PROGRAMS:
        raise ValueError(f"Program not allowed: {program}")

    result = subprocess.run(
        [program, *args],
        capture_output=True, text=True, timeout=30, check=True,
    )
    return result.stdout

5. Security Standards

5.1 Domain Vulnerability Landscape

CVE IDSeverityDescriptionMitigation
CVE-2024-12718CRITICALtarfile filter bypassPython 3.12.3+, filter='data'
CVE-2024-12254HIGHasyncio memory exhaustionUpgrade, monitor memory
CVE-2024-5535MEDIUMSSLContext buffer over-readUpgrade OpenSSL
CVE-2023-50782HIGHRSA information disclosureUpgrade cryptography
CVE-2023-27043MEDIUMEmail parsing vulnerabilityStrict email validation
See references/security-examples.md for complete CVE details and mitigation code

5.2 OWASP Top 10 Mapping

CategoryRiskKey Mitigations
A01 Broken Access ControlHIGHValidate permissions, decorators
A02 Cryptographic FailuresHIGHcryptography lib, Argon2
A03 InjectionCRITICALParameterized queries, no shell=True
A04 Insecure DesignMEDIUMType safety, validation layers
A05 MisconfigurationHIGHSafe defaults, audit deps
A06 Vulnerable ComponentsHIGHpip-audit, safety in CI

5.3 Essential Security Patterns

from pydantic import BaseModel, field_validator
import os, logging

# Secure base model - reject unknown fields, strip whitespace
class SecureInput(BaseModel):
    model_config = {'extra': 'forbid', 'str_strip_whitespace': True}

    @field_validator('*', mode='before')
    @classmethod
    def reject_null_bytes(cls, v):
        if isinstance(v, str) and '\x00' in v:
            raise ValueError('Null bytes not allowed')
        return v

# Secrets from environment (NEVER hardcode)
API_KEY = os.environ["API_KEY"]
DB_URL = os.environ["DATABASE_URL"]

# Safe error handling - log details, return safe message
class AppError(Exception):
    def __init__(self, message: str, internal: str = None):
        self.message = message
        if internal:
            logging.error(f"{message}: {internal}")

    def to_response(self) -> dict:
        return {"error": self.message}
See references/advanced-patterns.md for secrets manager integration

6. Testing & Validation

Security Testing Commands

bandit -r src/ -ll          # Static analysis
pip-audit && safety check   # Dependency vulnerabilities
mypy src/ --strict          # Type checking

Security Test Examples

import pytest
from pathlib import Path

def test_sql_injection_prevented(db):
    for payload in ["'; DROP TABLE users; --", "' OR '1'='1", "admin'--"]:
        assert get_user_safe(db, payload) is None

def test_path_traversal_blocked():
    base = Path("/app/data")
    for attack in ["../etc/passwd", "..\\windows\\system32", "foo/../../etc/passwd"]:
        with pytest.raises(ValueError, match="traversal|Invalid"):
            safe_read_file(base, attack)

def test_command_injection_blocked():
    with pytest.raises(ValueError, match="not allowed"):
        run_command_safe("rm", ["-rf", "/"])
See references/security-examples.md for comprehensive test patterns

7. Common Mistakes & Anti-Patterns

Anti-PatternBadGood
SQL formattingf"SELECT * WHERE id={id}"select(User).where(User.id == id)
Pickle untrustedpickle.loads(data)json.loads(data)
Shell injectionsubprocess.run(f"echo {x}", shell=True)subprocess.run(["echo", x])
Weak hashinghashlib.md5(pw).hexdigest()PasswordHasher().hash(pw)
Hardcoded secretsAPI_KEY = "sk-123..."API_KEY = os.environ["API_KEY"]

8. Pre-Deployment Checklist

Phase 1: Before Writing Code

  • Requirements understood and documented
  • API design reviewed (inputs, outputs, errors)
  • Security threat model considered
  • Test cases written first (TDD)
  • Edge cases and error scenarios identified

Phase 2: During Implementation

  • Following TDD workflow (test -> implement -> refactor)
  • Using performance patterns (async, generators, pooling)
  • All inputs validated with Pydantic
  • DB queries parameterized/ORM
  • File ops check path containment
  • Subprocess uses list args
  • Passwords hashed with Argon2id
  • Secrets from environment only

Phase 3: Before Committing

  • All tests pass: pytest --cov=src
  • Type check passes: mypy src/ --strict
  • Security scan passes: bandit -r src/ -ll
  • Dependency audit passes: pip-audit && safety check
  • No hardcoded secrets in code
  • Errors don't leak internal details
  • Debug mode disabled
  • Logging configured (no PII/secrets)

9. Summary

Create Python code that is type safe, secure, testable, and maintainable.

Security Essentials:

  1. Validate and sanitize all user input
  2. Use parameterized queries for database ops
  3. Never use shell=True with user input
  4. Hash passwords with Argon2id
  5. Load secrets from environment
  6. Keep dependencies updated and audited
For attack scenarios and threat modeling, see references/threat-model.md

平台分布

Antigravity

28.84%
按下载量换算295

Claude Code

23.49%
按下载量换算240

Gemini CLI

15.66%
按下载量换算160

Codex

12.55%
按下载量换算128

windsurf

7.85%
按下载量换算80

OpenCode

2.82%
按下载量换算29

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

继续浏览同类 Skills