[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill-30754280-4a6b-45d7-8955-a120423d698e":3,"$fv6sIqfz-SzW-ghM8VbeudgiL7nP4N_0spoD7NJIXjVg":43},{"id":4,"title":5,"description":6,"categoryId":7,"moduleId":8,"tags":9,"prompt":10,"icon":11,"source":12,"sourceUrl":13,"authorId":14,"authorName":15,"isPublic":16,"stars":17,"runs":18,"createdAt":19,"updatedAt":19,"module":20,"category":27,"packages":34},"30754280-4a6b-45d7-8955-a120423d698e","python-patterns","Python开发原则和决策。框架选择、异步模式、类型提示、项目结构。教授思考，而非复制。","cat_life_career","mod_other","sickn33,other","---\nname: python-patterns\ndescription: \"Python development principles and decision-making. Framework selection, async patterns, type hints, project structure. Teaches thinking, not copying.\"\nrisk: unknown\nsource: community\ndate_added: \"2026-02-27\"\n---\n\n# Python Patterns\n\n> Python development principles and decision-making for 2025.\n> **Learn to THINK, not memorize patterns.**\n\n## When to Use\nUse this skill when making Python architecture decisions, choosing frameworks, designing async patterns, or structuring Python projects.\n\n---\n\n## ⚠️ How to Use This Skill\n\nThis skill teaches **decision-making principles**, not fixed code to copy.\n\n- ASK user for framework preference when unclear\n- Choose async vs sync based on CONTEXT\n- Don't default to same framework every time\n\n---\n\n## 1. Framework Selection (2025)\n\n### Decision Tree\n\n```\nWhat are you building?\n│\n├── API-first \u002F Microservices\n│   └── FastAPI (async, modern, fast)\n│\n├── Full-stack web \u002F CMS \u002F Admin\n│   └── Django (batteries-included)\n│\n├── Simple \u002F Script \u002F Learning\n│   └── Flask (minimal, flexible)\n│\n├── AI\u002FML API serving\n│   └── FastAPI (Pydantic, async, uvicorn)\n│\n└── Background workers\n    └── Celery + any framework\n```\n\n### Comparison Principles\n\n| Factor | FastAPI | Django | Flask |\n|--------|---------|--------|-------|\n| **Best for** | APIs, microservices | Full-stack, CMS | Simple, learning |\n| **Async** | Native | Django 5.0+ | Via extensions |\n| **Admin** | Manual | Built-in | Via extensions |\n| **ORM** | Choose your own | Django ORM | Choose your own |\n| **Learning curve** | Low | Medium | Low |\n\n### Selection Questions to Ask:\n1. Is this API-only or full-stack?\n2. Need admin interface?\n3. Team familiar with async?\n4. Existing infrastructure?\n\n---\n\n## 2. Async vs Sync Decision\n\n### When to Use Async\n\n```\nasync def is better when:\n├── I\u002FO-bound operations (database, HTTP, file)\n├── Many concurrent connections\n├── Real-time features\n├── Microservices communication\n└── FastAPI\u002FStarlette\u002FDjango ASGI\n\ndef (sync) is better when:\n├── CPU-bound operations\n├── Simple scripts\n├── Legacy codebase\n├── Team unfamiliar with async\n└── Blocking libraries (no async version)\n```\n\n### The Golden Rule\n\n```\nI\u002FO-bound → async (waiting for external)\nCPU-bound → sync + multiprocessing (computing)\n\nDon't:\n├── Mix sync and async carelessly\n├── Use sync libraries in async code\n└── Force async for CPU work\n```\n\n### Async Library Selection\n\n| Need | Async Library |\n|------|---------------|\n| HTTP client | httpx |\n| PostgreSQL | asyncpg |\n| Redis | aioredis \u002F redis-py async |\n| File I\u002FO | aiofiles |\n| Database ORM | SQLAlchemy 2.0 async, Tortoise |\n\n---\n\n## 3. Type Hints Strategy\n\n### When to Type\n\n```\nAlways type:\n├── Function parameters\n├── Return types\n├── Class attributes\n├── Public APIs\n\nCan skip:\n├── Local variables (let inference work)\n├── One-off scripts\n├── Tests (usually)\n```\n\n### Common Type Patterns\n\n```python\n# These are patterns, understand them:\n\n# Optional → might be None\nfrom typing import Optional\ndef find_user(id: int) -> Optional[User]: ...\n\n# Union → one of multiple types\ndef process(data: str | dict) -> None: ...\n\n# Generic collections\ndef get_items() -> list[Item]: ...\ndef get_mapping() -> dict[str, int]: ...\n\n# Callable\nfrom typing import Callable\ndef apply(fn: Callable[[int], str]) -> str: ...\n```\n\n### Pydantic for Validation\n\n```\nWhen to use Pydantic:\n├── API request\u002Fresponse models\n├── Configuration\u002Fsettings\n├── Data validation\n├── Serialization\n\nBenefits:\n├── Runtime validation\n├── Auto-generated JSON schema\n├── Works with FastAPI natively\n└── Clear error messages\n```\n\n---\n\n## 4. Project Structure Principles\n\n### Structure Selection\n\n```\nSmall project \u002F Script:\n├── main.py\n├── utils.py\n└── requirements.txt\n\nMedium API:\n├── app\u002F\n│   ├── __init__.py\n│   ├── main.py\n│   ├── models\u002F\n│   ├── routes\u002F\n│   ├── services\u002F\n│   └── schemas\u002F\n├── tests\u002F\n└── pyproject.toml\n\nLarge application:\n├── src\u002F\n│   └── myapp\u002F\n│       ├── core\u002F\n│       ├── api\u002F\n│       ├── services\u002F\n│       ├── models\u002F\n│       └── ...\n├── tests\u002F\n└── pyproject.toml\n```\n\n### FastAPI Structure Principles\n\n```\nOrganize by feature or layer:\n\nBy layer:\n├── routes\u002F (API endpoints)\n├── services\u002F (business logic)\n├── models\u002F (database models)\n├── schemas\u002F (Pydantic models)\n└── dependencies\u002F (shared deps)\n\nBy feature:\n├── users\u002F\n│   ├── routes.py\n│   ├── service.py\n│   └── schemas.py\n└── products\u002F\n    └── ...\n```\n\n---\n\n## 5. Django Principles (2025)\n\n### Django Async (Django 5.0+)\n\n```\nDjango supports async:\n├── Async views\n├── Async middleware\n├── Async ORM (limited)\n└── ASGI deployment\n\nWhen to use async in Django:\n├── External API calls\n├── WebSocket (Channels)\n├── High-concurrency views\n└── Background task triggering\n```\n\n### Django Best Practices\n\n```\nModel design:\n├── Fat models, thin views\n├── Use managers for common queries\n├── Abstract base classes for shared fields\n\nViews:\n├── Class-based for complex CRUD\n├── Function-based for simple endpoints\n├── Use viewsets with DRF\n\nQueries:\n├── select_related() for FKs\n├── prefetch_related() for M2M\n├── Avoid N+1 queries\n└── Use .only() for specific fields\n```\n\n---\n\n## 6. FastAPI Principles\n\n### async def vs def in FastAPI\n\n```\nUse async def when:\n├── Using async database drivers\n├── Making async HTTP calls\n├── I\u002FO-bound operations\n└── Want to handle concurrency\n\nUse def when:\n├── Blocking operations\n├── Sync database drivers\n├── CPU-bound work\n└── FastAPI runs in threadpool automatically\n```\n\n### Dependency Injection\n\n```\nUse dependencies for:\n├── Database sessions\n├── Current user \u002F Auth\n├── Configuration\n├── Shared resources\n\nBenefits:\n├── Testability (mock dependencies)\n├── Clean separation\n├── Automatic cleanup (yield)\n```\n\n### Pydantic v2 Integration\n\n```python\n# FastAPI + Pydantic are tightly integrated:\n\n# Request validation\n@app.post(\"\u002Fusers\")\nasync def create(user: UserCreate) -> UserResponse:\n    # user is already validated\n    ...\n\n# Response serialization\n# Return type becomes response schema\n```\n\n---\n\n## 7. Background Tasks\n\n### Selection Guide\n\n| Solution | Best For |\n|----------|----------|\n| **BackgroundTasks** | Simple, in-process tasks |\n| **Celery** | Distributed, complex workflows |\n| **ARQ** | Async, Redis-based |\n| **RQ** | Simple Redis queue |\n| **Dramatiq** | Actor-based, simpler than Celery |\n\n### When to Use Each\n\n```\nFastAPI BackgroundTasks:\n├── Quick operations\n├── No persistence needed\n├── Fire-and-forget\n└── Same process\n\nCelery\u002FARQ:\n├── Long-running tasks\n├── Need retry logic\n├── Distributed workers\n├── Persistent queue\n└── Complex workflows\n```\n\n---\n\n## 8. Error Handling Principles\n\n### Exception Strategy\n\n```\nIn FastAPI:\n├── Create custom exception classes\n├── Register exception handlers\n├── Return consistent error format\n└── Log without exposing internals\n\nPattern:\n├── Raise domain exceptions in services\n├── Catch and transform in handlers\n└── Client gets clean error response\n```\n\n### Error Response Philosophy\n\n```\nInclude:\n├── Error code (programmatic)\n├── Message (human readable)\n├── Details (field-level when applicable)\n└── NOT stack traces (security)\n```\n\n---\n\n## 9. Testing Principles\n\n### Testing Strategy\n\n| Type | Purpose | Tools |\n|------|---------|-------|\n| **Unit** | Business logic | pytest |\n| **Integration** | API endpoints | pytest + httpx\u002FTestClient |\n| **E2E** | Full workflows | pytest + DB |\n\n### Async Testing\n\n```python\n# Use pytest-asyncio for async tests\n\nimport pytest\nfrom httpx import AsyncClient\n\n@pytest.mark.asyncio\nasync def test_endpoint():\n    async with AsyncClient(app=app, base_url=\"http:\u002F\u002Ftest\") as client:\n        response = await client.get(\"\u002Fusers\")\n        assert response.status_code == 200\n```\n\n### Fixtures Strategy\n\n```\nCommon fixtures:\n├── db_session → Database connection\n├── client → Test client\n├── authenticated_user → User with token\n└── sample_data → Test data setup\n```\n\n---\n\n## 10. Decision Checklist\n\nBefore implementing:\n\n- [ ] **Asked user about framework preference?**\n- [ ] **Chosen framework for THIS context?** (not just default)\n- [ ] **Decided async vs sync?**\n- [ ] **Planned type hint strategy?**\n- [ ] **Defined project structure?**\n- [ ] **Planned error handling?**\n- [ ] **Considered background tasks?**\n\n---\n\n## 11. Anti-Patterns to Avoid\n\n### ❌ DON'T:\n- Default to Django for simple APIs (FastAPI may be better)\n- Use sync libraries in async code\n- Skip type hints for public APIs\n- Put business logic in routes\u002Fviews\n- Ignore N+1 queries\n- Mix async and sync carelessly\n\n### ✅ DO:\n- Choose framework based on context\n- Ask about async requirements\n- Use Pydantic for validation\n- Separate concerns (routes → services → repos)\n- Test critical paths\n\n---\n\n> **Remember**: Python patterns are about decision-making for YOUR specific context. Don't copy code—think about what serves your application best.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","","imported","https:\u002F\u002Fgithub.com\u002Fsickn33\u002Fantigravity-awesome-skills","user_system_seed","SkillOPIC",true,200,1922,"2026-05-16 13:35:57",{"id":8,"name":21,"slug":22,"icon":23,"description":24,"sort":25,"createdAt":26},"其他","other","mdi-page-next-outline","其他类型Skill",5,"2026-05-16 12:53:40",{"id":7,"name":28,"slug":29,"icon":30,"description":31,"moduleId":8,"sort":32,"skillCount":33,"createdAt":26},"职场发展","career","mdi-briefcase-outline","面试准备、简历优化、职业规划",4,575,[35],{"id":36,"skillId":4,"version":37,"fileName":38,"fileSize":39,"filePath":40,"fileHash":41,"manifest":42,"createdAt":19},"cd3f971c-cc6c-40a6-b46a-a908d59b72b3","1.0.0","python-patterns.zip",4100,"uploads\u002Fskills\u002F30754280-4a6b-45d7-8955-a120423d698e\u002Fpython-patterns.zip","de06e117a40edfd4740f6bdc1ab21bcdac2373533751449c45d96e68685facdb","[{\"path\":\"SKILL.md\",\"isDirectory\":false,\"size\":9962}]",{"code":17,"message":44,"data":45},"success",{"items":46,"stats":47,"page":50},[],{"averageRating":48,"totalRatings":48,"ratingCounts":49},0,[48,48,48,48,48],{"limit":51,"offset":48,"hasMore":52,"nextOffset":51,"ratedOnly":16},15,false]