cp-toolkit 2.2.3 → 2.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/package.json +1 -1
  2. package/src/commands/add.js +23 -16
  3. package/src/commands/doctor.js +15 -10
  4. package/src/commands/init.js +55 -16
  5. package/templates/AGENTS.md +47 -0
  6. package/templates/ARCHITECTURE.md +42 -0
  7. package/templates/agents/backend-specialist.md +1 -0
  8. package/templates/agents/code-archaeologist.md +116 -106
  9. package/templates/agents/database-architect.md +1 -0
  10. package/templates/agents/debugger.md +1 -0
  11. package/templates/agents/devops-engineer.md +1 -0
  12. package/templates/agents/documentation-writer.md +1 -0
  13. package/templates/agents/explorer-agent.md +83 -73
  14. package/templates/agents/frontend-specialist.md +1 -0
  15. package/templates/agents/game-developer.md +1 -0
  16. package/templates/agents/mobile-developer.md +1 -0
  17. package/templates/agents/orchestrator.md +426 -416
  18. package/templates/agents/penetration-tester.md +1 -0
  19. package/templates/agents/performance-optimizer.md +1 -0
  20. package/templates/agents/product-manager.md +122 -112
  21. package/templates/agents/product-owner.md +105 -95
  22. package/templates/agents/project-planner.md +416 -406
  23. package/templates/agents/qa-automation-engineer.md +113 -103
  24. package/templates/agents/security-auditor.md +1 -0
  25. package/templates/agents/seo-specialist.md +1 -0
  26. package/templates/agents/test-engineer.md +1 -0
  27. package/templates/skills/core/behavioral-modes/SKILL.md +244 -242
  28. package/templates/skills/core/brainstorming/SKILL.md +166 -163
  29. package/templates/skills/core/mcp-builder/SKILL.md +178 -176
  30. package/templates/skills/core/parallel-agents/SKILL.md +187 -175
  31. package/templates/skills/core/plan-writing/SKILL.md +154 -152
  32. package/templates/skills/optional/api-patterns/SKILL.md +83 -81
  33. package/templates/skills/optional/app-builder/SKILL.md +78 -75
  34. package/templates/skills/optional/app-builder/templates/SKILL.md +41 -39
  35. package/templates/skills/optional/architecture/SKILL.md +58 -55
  36. package/templates/skills/optional/bash-linux/SKILL.md +201 -199
  37. package/templates/skills/optional/code-review-checklist/SKILL.md +110 -109
  38. package/templates/skills/optional/database-design/SKILL.md +54 -52
  39. package/templates/skills/optional/deployment-procedures/SKILL.md +243 -241
  40. package/templates/skills/optional/documentation-templates/SKILL.md +196 -194
  41. package/templates/skills/optional/frontend-design/SKILL.md +421 -418
  42. package/templates/skills/optional/game-development/2d-games/SKILL.md +120 -119
  43. package/templates/skills/optional/game-development/3d-games/SKILL.md +136 -135
  44. package/templates/skills/optional/game-development/SKILL.md +169 -167
  45. package/templates/skills/optional/game-development/game-art/SKILL.md +187 -185
  46. package/templates/skills/optional/game-development/game-audio/SKILL.md +192 -190
  47. package/templates/skills/optional/game-development/game-design/SKILL.md +131 -129
  48. package/templates/skills/optional/game-development/mobile-games/SKILL.md +110 -108
  49. package/templates/skills/optional/game-development/multiplayer/SKILL.md +133 -132
  50. package/templates/skills/optional/game-development/pc-games/SKILL.md +146 -144
  51. package/templates/skills/optional/game-development/vr-ar/SKILL.md +124 -123
  52. package/templates/skills/optional/game-development/web-games/SKILL.md +152 -150
  53. package/templates/skills/optional/geo-fundamentals/SKILL.md +158 -156
  54. package/templates/skills/optional/i18n-localization/SKILL.md +156 -154
  55. package/templates/skills/optional/lint-and-validate/SKILL.md +48 -45
  56. package/templates/skills/optional/mobile-design/SKILL.md +397 -394
  57. package/templates/skills/optional/nextjs-react-expert/SKILL.md +271 -267
  58. package/templates/skills/optional/nodejs-best-practices/SKILL.md +335 -333
  59. package/templates/skills/optional/performance-profiling/SKILL.md +145 -143
  60. package/templates/skills/optional/powershell-windows/SKILL.md +169 -167
  61. package/templates/skills/optional/python-patterns/SKILL.md +443 -441
  62. package/templates/skills/optional/red-team-tactics/SKILL.md +201 -199
  63. package/templates/skills/optional/seo-fundamentals/SKILL.md +130 -129
  64. package/templates/skills/optional/server-management/SKILL.md +163 -161
  65. package/templates/skills/optional/systematic-debugging/SKILL.md +111 -109
  66. package/templates/skills/optional/tailwind-patterns/SKILL.md +271 -269
  67. package/templates/skills/optional/tdd-workflow/SKILL.md +150 -149
  68. package/templates/skills/optional/testing-patterns/SKILL.md +179 -178
  69. package/templates/skills/optional/vulnerability-scanner/SKILL.md +278 -276
  70. package/templates/skills/optional/web-design-guidelines/SKILL.md +60 -57
  71. package/templates/skills/optional/webapp-testing/SKILL.md +188 -187
@@ -1,441 +1,443 @@
1
- ---
2
- name: python-patterns
3
- description: Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.
4
- allowed-tools: Read, Write, Edit, Glob, Grep
5
- ---
6
-
7
- # Python Patterns
8
-
9
- > Python development principles and decision-making for 2025.
10
- > **Learn to THINK, not memorize patterns.**
11
-
12
- ---
13
-
14
- ## ⚠️ How to Use This Skill
15
-
16
- This skill teaches **decision-making principles**, not fixed code to copy.
17
-
18
- - ASK user for framework preference when unclear
19
- - Choose async vs sync based on CONTEXT
20
- - Don't default to same framework every time
21
-
22
- ---
23
-
24
- ## 1. Framework Selection (2025)
25
-
26
- ### Decision Tree
27
-
28
- ```
29
- What are you building?
30
-
31
- ├── API-first / Microservices
32
- └── FastAPI (async, modern, fast)
33
-
34
- ├── Full-stack web / CMS / Admin
35
- └── Django (batteries-included)
36
-
37
- ├── Simple / Script / Learning
38
- └── Flask (minimal, flexible)
39
-
40
- ├── AI/ML API serving
41
- └── FastAPI (Pydantic, async, uvicorn)
42
-
43
- └── Background workers
44
- └── Celery + any framework
45
- ```
46
-
47
- ### Comparison Principles
48
-
49
- | Factor | FastAPI | Django | Flask |
50
- |--------|---------|--------|-------|
51
- | **Best for** | APIs, microservices | Full-stack, CMS | Simple, learning |
52
- | **Async** | Native | Django 5.0+ | Via extensions |
53
- | **Admin** | Manual | Built-in | Via extensions |
54
- | **ORM** | Choose your own | Django ORM | Choose your own |
55
- | **Learning curve** | Low | Medium | Low |
56
-
57
- ### Selection Questions to Ask:
58
- 1. Is this API-only or full-stack?
59
- 2. Need admin interface?
60
- 3. Team familiar with async?
61
- 4. Existing infrastructure?
62
-
63
- ---
64
-
65
- ## 2. Async vs Sync Decision
66
-
67
- ### When to Use Async
68
-
69
- ```
70
- async def is better when:
71
- ├── I/O-bound operations (database, HTTP, file)
72
- ├── Many concurrent connections
73
- ├── Real-time features
74
- ├── Microservices communication
75
- └── FastAPI/Starlette/Django ASGI
76
-
77
- def (sync) is better when:
78
- ├── CPU-bound operations
79
- ├── Simple scripts
80
- ├── Legacy codebase
81
- ├── Team unfamiliar with async
82
- └── Blocking libraries (no async version)
83
- ```
84
-
85
- ### The Golden Rule
86
-
87
- ```
88
- I/O-bound → async (waiting for external)
89
- CPU-bound → sync + multiprocessing (computing)
90
-
91
- Don't:
92
- ├── Mix sync and async carelessly
93
- ├── Use sync libraries in async code
94
- └── Force async for CPU work
95
- ```
96
-
97
- ### Async Library Selection
98
-
99
- | Need | Async Library |
100
- |------|---------------|
101
- | HTTP client | httpx |
102
- | PostgreSQL | asyncpg |
103
- | Redis | aioredis / redis-py async |
104
- | File I/O | aiofiles |
105
- | Database ORM | SQLAlchemy 2.0 async, Tortoise |
106
-
107
- ---
108
-
109
- ## 3. Type Hints Strategy
110
-
111
- ### When to Type
112
-
113
- ```
114
- Always type:
115
- ├── Function parameters
116
- ├── Return types
117
- ├── Class attributes
118
- ├── Public APIs
119
-
120
- Can skip:
121
- ├── Local variables (let inference work)
122
- ├── One-off scripts
123
- ├── Tests (usually)
124
- ```
125
-
126
- ### Common Type Patterns
127
-
128
- ```python
129
- # These are patterns, understand them:
130
-
131
- # Optional might be None
132
- from typing import Optional
133
- def find_user(id: int) -> Optional[User]: ...
134
-
135
- # Union one of multiple types
136
- def process(data: str | dict) -> None: ...
137
-
138
- # Generic collections
139
- def get_items() -> list[Item]: ...
140
- def get_mapping() -> dict[str, int]: ...
141
-
142
- # Callable
143
- from typing import Callable
144
- def apply(fn: Callable[[int], str]) -> str: ...
145
- ```
146
-
147
- ### Pydantic for Validation
148
-
149
- ```
150
- When to use Pydantic:
151
- ├── API request/response models
152
- ├── Configuration/settings
153
- ├── Data validation
154
- ├── Serialization
155
-
156
- Benefits:
157
- ├── Runtime validation
158
- ├── Auto-generated JSON schema
159
- ├── Works with FastAPI natively
160
- └── Clear error messages
161
- ```
162
-
163
- ---
164
-
165
- ## 4. Project Structure Principles
166
-
167
- ### Structure Selection
168
-
169
- ```
170
- Small project / Script:
171
- ├── main.py
172
- ├── utils.py
173
- └── requirements.txt
174
-
175
- Medium API:
176
- ├── app/
177
- │ ├── __init__.py
178
- ├── main.py
179
- │ ├── models/
180
- │ ├── routes/
181
- │ ├── services/
182
- └── schemas/
183
- ├── tests/
184
- └── pyproject.toml
185
-
186
- Large application:
187
- ├── src/
188
- │ └── myapp/
189
- ├── core/
190
- ├── api/
191
- │ ├── services/
192
- │ ├── models/
193
- └── ...
194
- ├── tests/
195
- └── pyproject.toml
196
- ```
197
-
198
- ### FastAPI Structure Principles
199
-
200
- ```
201
- Organize by feature or layer:
202
-
203
- By layer:
204
- ├── routes/ (API endpoints)
205
- ├── services/ (business logic)
206
- ├── models/ (database models)
207
- ├── schemas/ (Pydantic models)
208
- └── dependencies/ (shared deps)
209
-
210
- By feature:
211
- ├── users/
212
- │ ├── routes.py
213
- ├── service.py
214
- └── schemas.py
215
- └── products/
216
- └── ...
217
- ```
218
-
219
- ---
220
-
221
- ## 5. Django Principles (2025)
222
-
223
- ### Django Async (Django 5.0+)
224
-
225
- ```
226
- Django supports async:
227
- ├── Async views
228
- ├── Async middleware
229
- ├── Async ORM (limited)
230
- └── ASGI deployment
231
-
232
- When to use async in Django:
233
- ├── External API calls
234
- ├── WebSocket (Channels)
235
- ├── High-concurrency views
236
- └── Background task triggering
237
- ```
238
-
239
- ### Django Best Practices
240
-
241
- ```
242
- Model design:
243
- ├── Fat models, thin views
244
- ├── Use managers for common queries
245
- ├── Abstract base classes for shared fields
246
-
247
- Views:
248
- ├── Class-based for complex CRUD
249
- ├── Function-based for simple endpoints
250
- ├── Use viewsets with DRF
251
-
252
- Queries:
253
- ├── select_related() for FKs
254
- ├── prefetch_related() for M2M
255
- ├── Avoid N+1 queries
256
- └── Use .only() for specific fields
257
- ```
258
-
259
- ---
260
-
261
- ## 6. FastAPI Principles
262
-
263
- ### async def vs def in FastAPI
264
-
265
- ```
266
- Use async def when:
267
- ├── Using async database drivers
268
- ├── Making async HTTP calls
269
- ├── I/O-bound operations
270
- └── Want to handle concurrency
271
-
272
- Use def when:
273
- ├── Blocking operations
274
- ├── Sync database drivers
275
- ├── CPU-bound work
276
- └── FastAPI runs in threadpool automatically
277
- ```
278
-
279
- ### Dependency Injection
280
-
281
- ```
282
- Use dependencies for:
283
- ├── Database sessions
284
- ├── Current user / Auth
285
- ├── Configuration
286
- ├── Shared resources
287
-
288
- Benefits:
289
- ├── Testability (mock dependencies)
290
- ├── Clean separation
291
- ├── Automatic cleanup (yield)
292
- ```
293
-
294
- ### Pydantic v2 Integration
295
-
296
- ```python
297
- # FastAPI + Pydantic are tightly integrated:
298
-
299
- # Request validation
300
- @app.post("/users")
301
- async def create(user: UserCreate) -> UserResponse:
302
- # user is already validated
303
- ...
304
-
305
- # Response serialization
306
- # Return type becomes response schema
307
- ```
308
-
309
- ---
310
-
311
- ## 7. Background Tasks
312
-
313
- ### Selection Guide
314
-
315
- | Solution | Best For |
316
- |----------|----------|
317
- | **BackgroundTasks** | Simple, in-process tasks |
318
- | **Celery** | Distributed, complex workflows |
319
- | **ARQ** | Async, Redis-based |
320
- | **RQ** | Simple Redis queue |
321
- | **Dramatiq** | Actor-based, simpler than Celery |
322
-
323
- ### When to Use Each
324
-
325
- ```
326
- FastAPI BackgroundTasks:
327
- ├── Quick operations
328
- ├── No persistence needed
329
- ├── Fire-and-forget
330
- └── Same process
331
-
332
- Celery/ARQ:
333
- ├── Long-running tasks
334
- ├── Need retry logic
335
- ├── Distributed workers
336
- ├── Persistent queue
337
- └── Complex workflows
338
- ```
339
-
340
- ---
341
-
342
- ## 8. Error Handling Principles
343
-
344
- ### Exception Strategy
345
-
346
- ```
347
- In FastAPI:
348
- ├── Create custom exception classes
349
- ├── Register exception handlers
350
- ├── Return consistent error format
351
- └── Log without exposing internals
352
-
353
- Pattern:
354
- ├── Raise domain exceptions in services
355
- ├── Catch and transform in handlers
356
- └── Client gets clean error response
357
- ```
358
-
359
- ### Error Response Philosophy
360
-
361
- ```
362
- Include:
363
- ├── Error code (programmatic)
364
- ├── Message (human readable)
365
- ├── Details (field-level when applicable)
366
- └── NOT stack traces (security)
367
- ```
368
-
369
- ---
370
-
371
- ## 9. Testing Principles
372
-
373
- ### Testing Strategy
374
-
375
- | Type | Purpose | Tools |
376
- |------|---------|-------|
377
- | **Unit** | Business logic | pytest |
378
- | **Integration** | API endpoints | pytest + httpx/TestClient |
379
- | **E2E** | Full workflows | pytest + DB |
380
-
381
- ### Async Testing
382
-
383
- ```python
384
- # Use pytest-asyncio for async tests
385
-
386
- import pytest
387
- from httpx import AsyncClient
388
-
389
- @pytest.mark.asyncio
390
- async def test_endpoint():
391
- async with AsyncClient(app=app, base_url="http://test") as client:
392
- response = await client.get("/users")
393
- assert response.status_code == 200
394
- ```
395
-
396
- ### Fixtures Strategy
397
-
398
- ```
399
- Common fixtures:
400
- ├── db_session → Database connection
401
- ├── client → Test client
402
- ├── authenticated_userUser with token
403
- └── sample_data → Test data setup
404
- ```
405
-
406
- ---
407
-
408
- ## 10. Decision Checklist
409
-
410
- Before implementing:
411
-
412
- - [ ] **Asked user about framework preference?**
413
- - [ ] **Chosen framework for THIS context?** (not just default)
414
- - [ ] **Decided async vs sync?**
415
- - [ ] **Planned type hint strategy?**
416
- - [ ] **Defined project structure?**
417
- - [ ] **Planned error handling?**
418
- - [ ] **Considered background tasks?**
419
-
420
- ---
421
-
422
- ## 11. Anti-Patterns to Avoid
423
-
424
- ### DON'T:
425
- - Default to Django for simple APIs (FastAPI may be better)
426
- - Use sync libraries in async code
427
- - Skip type hints for public APIs
428
- - Put business logic in routes/views
429
- - Ignore N+1 queries
430
- - Mix async and sync carelessly
431
-
432
- ### DO:
433
- - Choose framework based on context
434
- - Ask about async requirements
435
- - Use Pydantic for validation
436
- - Separate concerns (routes → services → repos)
437
- - Test critical paths
438
-
439
- ---
440
-
441
- > **Remember**: Python patterns are about decision-making for YOUR specific context. Don't copy code—think about what serves your application best.
1
+ ---
2
+ name: python-patterns
3
+ description: Python development principles and decision-making. Framework selection,
4
+ async patterns, type hints, project structure. Teaches thinking, not copying.
5
+ allowed-tools: Read, Write, Edit, Glob, Grep
6
+ version: '1.0'
7
+ ---
8
+
9
+ # Python Patterns
10
+
11
+ > Python development principles and decision-making for 2025.
12
+ > **Learn to THINK, not memorize patterns.**
13
+
14
+ ---
15
+
16
+ ## ⚠️ How to Use This Skill
17
+
18
+ This skill teaches **decision-making principles**, not fixed code to copy.
19
+
20
+ - ASK user for framework preference when unclear
21
+ - Choose async vs sync based on CONTEXT
22
+ - Don't default to same framework every time
23
+
24
+ ---
25
+
26
+ ## 1. Framework Selection (2025)
27
+
28
+ ### Decision Tree
29
+
30
+ ```
31
+ What are you building?
32
+
33
+ ├── API-first / Microservices
34
+ │ └── FastAPI (async, modern, fast)
35
+
36
+ ├── Full-stack web / CMS / Admin
37
+ │ └── Django (batteries-included)
38
+
39
+ ├── Simple / Script / Learning
40
+ │ └── Flask (minimal, flexible)
41
+
42
+ ├── AI/ML API serving
43
+ └── FastAPI (Pydantic, async, uvicorn)
44
+
45
+ └── Background workers
46
+ └── Celery + any framework
47
+ ```
48
+
49
+ ### Comparison Principles
50
+
51
+ | Factor | FastAPI | Django | Flask |
52
+ |--------|---------|--------|-------|
53
+ | **Best for** | APIs, microservices | Full-stack, CMS | Simple, learning |
54
+ | **Async** | Native | Django 5.0+ | Via extensions |
55
+ | **Admin** | Manual | Built-in | Via extensions |
56
+ | **ORM** | Choose your own | Django ORM | Choose your own |
57
+ | **Learning curve** | Low | Medium | Low |
58
+
59
+ ### Selection Questions to Ask:
60
+ 1. Is this API-only or full-stack?
61
+ 2. Need admin interface?
62
+ 3. Team familiar with async?
63
+ 4. Existing infrastructure?
64
+
65
+ ---
66
+
67
+ ## 2. Async vs Sync Decision
68
+
69
+ ### When to Use Async
70
+
71
+ ```
72
+ async def is better when:
73
+ ├── I/O-bound operations (database, HTTP, file)
74
+ ├── Many concurrent connections
75
+ ├── Real-time features
76
+ ├── Microservices communication
77
+ └── FastAPI/Starlette/Django ASGI
78
+
79
+ def (sync) is better when:
80
+ ├── CPU-bound operations
81
+ ├── Simple scripts
82
+ ├── Legacy codebase
83
+ ├── Team unfamiliar with async
84
+ └── Blocking libraries (no async version)
85
+ ```
86
+
87
+ ### The Golden Rule
88
+
89
+ ```
90
+ I/O-bound → async (waiting for external)
91
+ CPU-bound → sync + multiprocessing (computing)
92
+
93
+ Don't:
94
+ ├── Mix sync and async carelessly
95
+ ├── Use sync libraries in async code
96
+ └── Force async for CPU work
97
+ ```
98
+
99
+ ### Async Library Selection
100
+
101
+ | Need | Async Library |
102
+ |------|---------------|
103
+ | HTTP client | httpx |
104
+ | PostgreSQL | asyncpg |
105
+ | Redis | aioredis / redis-py async |
106
+ | File I/O | aiofiles |
107
+ | Database ORM | SQLAlchemy 2.0 async, Tortoise |
108
+
109
+ ---
110
+
111
+ ## 3. Type Hints Strategy
112
+
113
+ ### When to Type
114
+
115
+ ```
116
+ Always type:
117
+ ├── Function parameters
118
+ ├── Return types
119
+ ├── Class attributes
120
+ ├── Public APIs
121
+
122
+ Can skip:
123
+ ├── Local variables (let inference work)
124
+ ├── One-off scripts
125
+ ├── Tests (usually)
126
+ ```
127
+
128
+ ### Common Type Patterns
129
+
130
+ ```python
131
+ # These are patterns, understand them:
132
+
133
+ # Optional might be None
134
+ from typing import Optional
135
+ def find_user(id: int) -> Optional[User]: ...
136
+
137
+ # Union → one of multiple types
138
+ def process(data: str | dict) -> None: ...
139
+
140
+ # Generic collections
141
+ def get_items() -> list[Item]: ...
142
+ def get_mapping() -> dict[str, int]: ...
143
+
144
+ # Callable
145
+ from typing import Callable
146
+ def apply(fn: Callable[[int], str]) -> str: ...
147
+ ```
148
+
149
+ ### Pydantic for Validation
150
+
151
+ ```
152
+ When to use Pydantic:
153
+ ├── API request/response models
154
+ ├── Configuration/settings
155
+ ├── Data validation
156
+ ├── Serialization
157
+
158
+ Benefits:
159
+ ├── Runtime validation
160
+ ├── Auto-generated JSON schema
161
+ ├── Works with FastAPI natively
162
+ └── Clear error messages
163
+ ```
164
+
165
+ ---
166
+
167
+ ## 4. Project Structure Principles
168
+
169
+ ### Structure Selection
170
+
171
+ ```
172
+ Small project / Script:
173
+ ├── main.py
174
+ ├── utils.py
175
+ └── requirements.txt
176
+
177
+ Medium API:
178
+ ├── app/
179
+ │ ├── __init__.py
180
+ │ ├── main.py
181
+ │ ├── models/
182
+ ├── routes/
183
+ ├── services/
184
+ └── schemas/
185
+ ├── tests/
186
+ └── pyproject.toml
187
+
188
+ Large application:
189
+ ├── src/
190
+ └── myapp/
191
+ │ ├── core/
192
+ │ ├── api/
193
+ ├── services/
194
+ ├── models/
195
+ └── ...
196
+ ├── tests/
197
+ └── pyproject.toml
198
+ ```
199
+
200
+ ### FastAPI Structure Principles
201
+
202
+ ```
203
+ Organize by feature or layer:
204
+
205
+ By layer:
206
+ ├── routes/ (API endpoints)
207
+ ├── services/ (business logic)
208
+ ├── models/ (database models)
209
+ ├── schemas/ (Pydantic models)
210
+ └── dependencies/ (shared deps)
211
+
212
+ By feature:
213
+ ├── users/
214
+ ├── routes.py
215
+ │ ├── service.py
216
+ └── schemas.py
217
+ └── products/
218
+ └── ...
219
+ ```
220
+
221
+ ---
222
+
223
+ ## 5. Django Principles (2025)
224
+
225
+ ### Django Async (Django 5.0+)
226
+
227
+ ```
228
+ Django supports async:
229
+ ├── Async views
230
+ ├── Async middleware
231
+ ├── Async ORM (limited)
232
+ └── ASGI deployment
233
+
234
+ When to use async in Django:
235
+ ├── External API calls
236
+ ├── WebSocket (Channels)
237
+ ├── High-concurrency views
238
+ └── Background task triggering
239
+ ```
240
+
241
+ ### Django Best Practices
242
+
243
+ ```
244
+ Model design:
245
+ ├── Fat models, thin views
246
+ ├── Use managers for common queries
247
+ ├── Abstract base classes for shared fields
248
+
249
+ Views:
250
+ ├── Class-based for complex CRUD
251
+ ├── Function-based for simple endpoints
252
+ ├── Use viewsets with DRF
253
+
254
+ Queries:
255
+ ├── select_related() for FKs
256
+ ├── prefetch_related() for M2M
257
+ ├── Avoid N+1 queries
258
+ └── Use .only() for specific fields
259
+ ```
260
+
261
+ ---
262
+
263
+ ## 6. FastAPI Principles
264
+
265
+ ### async def vs def in FastAPI
266
+
267
+ ```
268
+ Use async def when:
269
+ ├── Using async database drivers
270
+ ├── Making async HTTP calls
271
+ ├── I/O-bound operations
272
+ └── Want to handle concurrency
273
+
274
+ Use def when:
275
+ ├── Blocking operations
276
+ ├── Sync database drivers
277
+ ├── CPU-bound work
278
+ └── FastAPI runs in threadpool automatically
279
+ ```
280
+
281
+ ### Dependency Injection
282
+
283
+ ```
284
+ Use dependencies for:
285
+ ├── Database sessions
286
+ ├── Current user / Auth
287
+ ├── Configuration
288
+ ├── Shared resources
289
+
290
+ Benefits:
291
+ ├── Testability (mock dependencies)
292
+ ├── Clean separation
293
+ ├── Automatic cleanup (yield)
294
+ ```
295
+
296
+ ### Pydantic v2 Integration
297
+
298
+ ```python
299
+ # FastAPI + Pydantic are tightly integrated:
300
+
301
+ # Request validation
302
+ @app.post("/users")
303
+ async def create(user: UserCreate) -> UserResponse:
304
+ # user is already validated
305
+ ...
306
+
307
+ # Response serialization
308
+ # Return type becomes response schema
309
+ ```
310
+
311
+ ---
312
+
313
+ ## 7. Background Tasks
314
+
315
+ ### Selection Guide
316
+
317
+ | Solution | Best For |
318
+ |----------|----------|
319
+ | **BackgroundTasks** | Simple, in-process tasks |
320
+ | **Celery** | Distributed, complex workflows |
321
+ | **ARQ** | Async, Redis-based |
322
+ | **RQ** | Simple Redis queue |
323
+ | **Dramatiq** | Actor-based, simpler than Celery |
324
+
325
+ ### When to Use Each
326
+
327
+ ```
328
+ FastAPI BackgroundTasks:
329
+ ├── Quick operations
330
+ ├── No persistence needed
331
+ ├── Fire-and-forget
332
+ └── Same process
333
+
334
+ Celery/ARQ:
335
+ ├── Long-running tasks
336
+ ├── Need retry logic
337
+ ├── Distributed workers
338
+ ├── Persistent queue
339
+ └── Complex workflows
340
+ ```
341
+
342
+ ---
343
+
344
+ ## 8. Error Handling Principles
345
+
346
+ ### Exception Strategy
347
+
348
+ ```
349
+ In FastAPI:
350
+ ├── Create custom exception classes
351
+ ├── Register exception handlers
352
+ ├── Return consistent error format
353
+ └── Log without exposing internals
354
+
355
+ Pattern:
356
+ ├── Raise domain exceptions in services
357
+ ├── Catch and transform in handlers
358
+ └── Client gets clean error response
359
+ ```
360
+
361
+ ### Error Response Philosophy
362
+
363
+ ```
364
+ Include:
365
+ ├── Error code (programmatic)
366
+ ├── Message (human readable)
367
+ ├── Details (field-level when applicable)
368
+ └── NOT stack traces (security)
369
+ ```
370
+
371
+ ---
372
+
373
+ ## 9. Testing Principles
374
+
375
+ ### Testing Strategy
376
+
377
+ | Type | Purpose | Tools |
378
+ |------|---------|-------|
379
+ | **Unit** | Business logic | pytest |
380
+ | **Integration** | API endpoints | pytest + httpx/TestClient |
381
+ | **E2E** | Full workflows | pytest + DB |
382
+
383
+ ### Async Testing
384
+
385
+ ```python
386
+ # Use pytest-asyncio for async tests
387
+
388
+ import pytest
389
+ from httpx import AsyncClient
390
+
391
+ @pytest.mark.asyncio
392
+ async def test_endpoint():
393
+ async with AsyncClient(app=app, base_url="http://test") as client:
394
+ response = await client.get("/users")
395
+ assert response.status_code == 200
396
+ ```
397
+
398
+ ### Fixtures Strategy
399
+
400
+ ```
401
+ Common fixtures:
402
+ ├── db_sessionDatabase connection
403
+ ├── client → Test client
404
+ ├── authenticated_user → User with token
405
+ └── sample_data → Test data setup
406
+ ```
407
+
408
+ ---
409
+
410
+ ## 10. Decision Checklist
411
+
412
+ Before implementing:
413
+
414
+ - [ ] **Asked user about framework preference?**
415
+ - [ ] **Chosen framework for THIS context?** (not just default)
416
+ - [ ] **Decided async vs sync?**
417
+ - [ ] **Planned type hint strategy?**
418
+ - [ ] **Defined project structure?**
419
+ - [ ] **Planned error handling?**
420
+ - [ ] **Considered background tasks?**
421
+
422
+ ---
423
+
424
+ ## 11. Anti-Patterns to Avoid
425
+
426
+ ### DON'T:
427
+ - Default to Django for simple APIs (FastAPI may be better)
428
+ - Use sync libraries in async code
429
+ - Skip type hints for public APIs
430
+ - Put business logic in routes/views
431
+ - Ignore N+1 queries
432
+ - Mix async and sync carelessly
433
+
434
+ ### DO:
435
+ - Choose framework based on context
436
+ - Ask about async requirements
437
+ - Use Pydantic for validation
438
+ - Separate concerns (routes → services → repos)
439
+ - Test critical paths
440
+
441
+ ---
442
+
443
+ > **Remember**: Python patterns are about decision-making for YOUR specific context. Don't copy code—think about what serves your application best.