Python Service Dev
ASecurity用 Python 写接口 / FastAPI / Django model / Celery 任务 / pytest → implement, modify, scaffold, test, and wire Python backend services, workers, packages, standalone CLI/tooling, migrations, Redis, queues, config, observability, and clients. Triggers also include "用 Python 写个命令行工具", "重构 Python 服务里的某文件/某类(局部)", "refactor a file/class within a Python service". For reproduction, isolation, or root-cause debugging, use defect-diagnosis first; for architecture/layering decisions or a service-wide refact...
- 6 stars
- 0 votes
- 0 copies
- 5 views
- Added September 2, 2026
Works with
Security analysis
100/100Pro scans all 20 files and shows the line behind each finding
npx -y skills add ccoalm/ccl-skills --skill python-service-dev --agent claude-codeAre you the author of Python Service Dev?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/ccoalm-python-service-dev)---
name: python-service-dev
description: 用 Python 写接口 / FastAPI / Django model / Celery 任务 / pytest → implement, modify, scaffold, test, and wire Python backend services, workers, packages, standalone CLI/tooling, migrations, Redis, queues, config, observability, and clients. Triggers also include "用 Python 写个命令行工具", "重构 Python 服务里的某文件/某类(局部)", "refactor a file/class within a Python service". For reproduction, isolation, or root-cause debugging, use defect-diagnosis first; for architecture/layering decisions or a service-wide refactor, use software-architecture; for a multi-stage / cross-module refactor delivery, re-enter product-rd-workflow.
---
# Python Service Dev
Use this for implementation of Python backend products, services, microservices, AI-service hosts, workers, packages, and batch tools. For new backend products, implement the smallest deployable or package shape justified by ownership, data boundary, runtime isolation, scaling, release cadence, and rollback needs. It should adapt to the repository in front of you, but the workflow is independent of any prior codebase. After code/test edits, self-check and invoke `code-review` automatically before completion.
## Skill Routing
- Use this skill for Python implementation, scaffolding, handlers/routes/views, schemas, services, microservices, repositories, migrations, Redis, queues, workers, external/inter-service clients, config, observability, packaging, and tests.
- Use `product-rd-workflow` first when the request is an end-to-end product delivery workflow, product idea to implementation plan, release workflow, cross-skill coordination, bug postmortem, or durable process improvement.
- Use `defect-diagnosis` first when the task is to reproduce, isolate, instrument, fix, verify, or root-cause a backend defect, regression, repeated failure, review finding, or failing test.
- System design, service boundaries, contract strategy, storage ownership, reliability design, or architecture review without code changes must go to `software-architecture`.
- Use `testing-strategy` when the main question is which unit, integration, contract, or E2E layer should prove behavior; then return here for Python-specific implementation.
- Use `test-artifact-management` when the ask is about generating structured test cases from a Feishu requirements doc or codebase and tracking them in Feishu Bitable before implementation begins.
- Use `llm-inference-integration` for inference, RAG, prompt, model-routing, evaluation, replay, token-cost, and batch-inference design. Return here for Python API, worker, adapter, persistence, and observability implementation.
- Use `go-microservice-dev` for Go services. Do not load Go implementation rules for Python work unless the task is explicitly cross-language contract or generated-client integration.
- Use codebase-specific skills only when the task is explicitly about an existing repository.
- For money, billing, quota, permission, tenant/user data isolation, high-impact AI, repeated writes, async finality, or incident-explanation risk, apply `product-rd-workflow` high-risk resilience gates and route test-layer design through `testing-strategy`.
- When a change can alter what a client renders or which state, action, or decision path it offers—including strings/templates/config/flags and API/event/schema fields, enums, status/progress, permission/capability signals, defaults, or result shapes—load `../product-ui-ux-design/references/delivery-contract.md`, create the applicable full or lightweight record in that contract, and follow its canonical consumer-universe classification, design/test/client handoffs, and terminal-status rules.
- This Python owner returns only its `producer_record` delta: immutable binding, build/schema/config artifact identity, exact command/environment, and API/event/log/output observation.
- For a standalone Python CLI, this skill owns Python parser/library implementation mechanics. Any change to a user-facing command tree, subcommand, flag/default/action path, help/output/exit behavior, confirmation, progress, or recovery path also loads `terminal-cli-dev`, which owns the terminal contract and its UI/UX/testing handoff. Only internal parser refactors proven to preserve all user-visible semantics may skip that owner.
## Generalization Discipline
- Implement the repo in front of you, but do not import product nouns, service names, package paths, provider names, IDs, dashboards, or organization-specific habits from prior codebases.
- Convert domain-specific source patterns into reusable mechanics: route shape, schema validation, repository/unit-of-work boundary, transaction scope, cache key strategy, idempotency, job lease, config object, trace context, fake client, or test style.
- If an observed pattern only works for one product domain, discard it instead of turning it into a rule.
- Resolve conflicts by choosing the safer generic default: explicit schemas over dicts, typed settings over ad hoc environment reads, reviewed migrations over blind autogeneration, bounded async concurrency over unbounded gather, dependency injection over import-time clients, focused pytest tests over live-infra tests by default, and fail-closed for auth/permission/data-integrity paths.
- When adding or revising durable Python implementation guidance, check whether the lesson is generic backend service practice that should also update the sibling stack owners `go-microservice-dev` and `nodejs-service-dev`, or belongs in a shared workflow skill instead. Record each sibling as `update`, `unchanged`, or `route-to-shared` rather than leaving it unexamined. If the rule depends on Python tooling, FastAPI/Flask/Django, Pydantic, asyncio, pytest, or Python package layout, keep it here and do not force a Go or Node mirror.
## Development Workflow
Before editing code, generated files, migrations, configs, or tests, complete enough analysis and planning for the change to be reviewable. Scale the plan to risk: a simple low-risk single-package change can use a short inline plan; multi-file, contract-visible, data/schema, async, release, bug-fix, branch/MR, unclear-risk, or high-risk work needs explicit task split, acceptance checks, verification commands, rollback or stop conditions, and named handoffs to architecture, testing, or diagnosis skills before edits.
Repo-local agent contracts (`AGENTS.md` at the repo root and in source directories) are part of the delivery contract: when a change moves a stable boundary, generated surface, workflow, or directory-local rule, update the nearest contract in the same MR and keep coverage in sync per `product-rd-workflow`'s spec / repo-contract sync gate.
1. Establish the target Python project shape.
- Find the nearest `pyproject.toml`, lockfile, package root, app entrypoint, framework app, settings, migrations, tests, and documented commands.
- Identify whether this is an HTTP API microservice, internal microservice, worker service, scheduled job service, SDK/package, CLI, AI-service host, or batch tool.
- Check whether tests are split by unit, integration, contract, API, E2E, and live-infra markers.
2. Start from contracts and data.
- Update Pydantic/OpenAPI, Django serializer/form, or protobuf/gRPC contracts before changing request/response behavior.
- Define ORM model and migration changes before repository code.
3. Keep layers clean.
- Transport layer: framework mapping, validation, auth context, response mapping.
- Application/service layer: use-case orchestration and transactions.
- Domain layer: rules and invariants.
- Infrastructure layer: DB, Redis, MQ, HTTP clients, object storage, inference clients.
- Generated code: never hand-edit generated clients or protobuf output. Migration files are reviewable source.
4. Wire dependencies explicitly.
- Constructors and dependency providers should declare what they need.
- Prefer small boundary interfaces or protocols where tests or adapters matter.
- Keep production and test dependency graphs separate when clients need fakes.
5. Verify at the right scope.
- Run focused pytest tests for changed packages.
- When writing the test code itself (structure, naming, smells, fixtures, behavior-vs-state, coverage, isolation, parameterization), pick the matching § from the decision table in `testing-strategy/references/test-code-authoring-patterns.md`; enable the per-stack lint executors for its machine-decidable smells (conditional logic / sleep / assertion-free tests) per `testing-strategy/references/fitness-functions.md` §4.1.4 (e.g. Ruff `TID251` banning `time.sleep`).
- Run async tests with the repo's configured `pytest-asyncio` mode.
- Run integration tests only when required services and credentials are available.
- **TC traceability and the deprecation cascade** are mandatory when the repo tracks test cases in Bitable: before adding a test, check existing TC coverage; before deleting one, run the caller-liveness sequence. Mechanics (marker registration, coverage grep, the four-step 废弃级联, dynamic-import boundaries) live in `references/testing-and-quality-patterns.md` (TC Traceability And Deprecation Cascade).
- Run ruff, mypy/pyright, formatting, and codegen/migration checks when the repo uses them.
- Keep fast tests deterministic; isolate live infrastructure, long sleeps, generated files, and external credentials behind markers.
## Implementation Rules
- Validate inputs at framework boundaries.
- Use typed Pydantic or framework schemas for public APIs.
- Pass request/trace context through external calls where the stack supports it. The carve-out is narrow and behavioral: only a genuinely side-effect-free function — no external calls, task spawning, filesystem/env, clock/random, or logging/trace/tenant/feature lookup across its body and callees — may omit it. A mapper or helper that does, or later gains, any such call takes it. The test is behavior, not the name.
- Set timeouts for HTTP/DB/Redis/MQ/inference calls.
- Honor cancellation and request deadlines in async code.
- Do not block the event loop with sync clients, CPU-heavy processing, large file I/O, or GPU work.
- Use SQLAlchemy/Django transactions for multi-step writes inside one database.
- Keep SQLAlchemy, SQLModel, Django ORM, and raw SQL behind repository or data-access modules; routes/views and business services should not scatter SQL or ORM query construction.
- Treat queue delivery as at-least-once; consumers must be idempotent.
- Treat write retries as unsafe by default. Add automatic retry only when the operation has a durable idempotency key, unique constraint, state machine, dedupe table, or equivalent proof, and test duplicate submit/callback/queue/job-restart behavior.
- For money, quota, entitlement, permission, tenant/user isolation, privacy, and sensitive state changes, fail closed on uncertainty and return the canonical error before side effects.
- Do not default missing tenant, actor, subject, or resource scope on high-risk paths. Reject before side effects unless the code is an explicit bootstrap, seed, or maintenance path with separate approval.
- Use Redis locks with unique values and compare-and-delete unlock.
- Keep config typed and environment-specific.
- Use pytest fakes/mocks for external clients by default; reserve live dependency tests for explicit integration gates.
- For high-risk synchronous or async user-visible operations, read `references/state-machine-task-patterns.md`.
- For service registration, model serving, or worker bootstraps (readiness-before-registration and bounded shutdown), read `references/ai-service-wiring-patterns.md`.
- For release-facing runtime config, readiness, entrypoint, rollback controls, and live-infra release gates, read `references/testing-and-quality-patterns.md`.
## Reference Loading
- For source provenance, current extraction boundary, and keep/merge/discard decisions, read `references/source-evidence-map.md` when auditing or re-extracting this skill.
- For feature implementation steps, read `references/feature-playbook.md`.
- For project layout, package roots, uv/poetry/pip, import mode, and tooling, read `references/project-structure-and-tooling.md`.
- For FastAPI, Flask, Django, routes/views, dependencies, and app factories, read `references/web-framework-patterns.md`.
- For Pydantic/OpenAPI/schema validation, protobuf/gRPC handlers or adapters, manual population of generated DTOs, and generated clients, read `references/schema-and-validation-patterns.md`.
- For public API implementation, partner app auth, signature verification, callback handling, authorization scope, and API security tests, read `references/public-api-security-patterns.md`.
- For SQLAlchemy/Django ORM, Alembic, migrations, repositories, and transactions, read `references/sqlalchemy-and-migrations-patterns.md`.
- For asyncio, blocking work isolation, concurrency limits, and cancellation, read `references/async-and-worker-patterns.md`.
- For Redis, cache, locks, idempotency, counters, and rate limits, read `references/redis-cache-lock-patterns.md`.
- For Celery/RQ/arq, queues, scheduled tasks, and job execution, read `references/background-job-patterns.md`.
- For durable task state machines, status transitions, leases, terminal states, and scheduled repair jobs, read `references/state-machine-task-patterns.md`.
- For audit logs, operation records, resource history, and change tracking, read `references/audit-history-patterns.md`.
- For notification delivery, operator alerts, outbound webhooks, and realtime client channels, read `references/notification-patterns.md`.
- For replay jobs, shadow execution, response comparison, and migration verification, read `references/replay-comparison-patterns.md`.
- For external HTTP clients, SDKs, generated clients, service discovery, and dependency adapters, read `references/dependency-client-patterns.md`.
- For errors, exception mapping, response envelopes, and validation errors, read `references/error-handling-patterns.md`.
- For logs, metrics, traces, health checks, and instrumentation, read `references/observability-implementation-patterns.md`.
- For pytest, async tests, fakes, fixtures, markers, ruff, mypy/pyright, and CI gates, read `references/testing-and-quality-patterns.md`.
- For Python API/worker wiring around LLM/RAG/inference systems, read `references/ai-service-wiring-patterns.md`.
- For import/export, backfill, repair scripts, generated artifacts, and batch reports, read `references/batch-and-artifact-patterns.md`.
Files in this skill
- SKILL.md
- agents/openai.yaml
- references/ai-service-wiring-patterns.md
- references/async-and-worker-patterns.md
- references/audit-history-patterns.md
- references/background-job-patterns.md
- references/batch-and-artifact-patterns.md
- references/dependency-client-patterns.md
- references/error-handling-patterns.md
- references/feature-playbook.md
- references/notification-patterns.md
- references/observability-implementation-patterns.md
- references/project-structure-and-tooling.md
- references/public-api-security-patterns.md
- references/redis-cache-lock-patterns.md
- references/replay-comparison-patterns.md
- references/schema-and-validation-patterns.md
- references/source-evidence-map.md
- references/sqlalchemy-and-migrations-patterns.md
- references/state-machine-task-patterns.md
Attribution
Related skills
View all in ai-agents →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.