@umacloud/knowledge 1.0.1

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 (418) hide show
  1. package/00-governance/governance-capabilities.md +557 -0
  2. package/00-governance/knowledge-map.md +39 -0
  3. package/00-governance/maintenance-policy.md +76 -0
  4. package/00-governance/review-checklist.md +81 -0
  5. package/README.md +13 -0
  6. package/ai/01-standards/agent-development-complete.md +691 -0
  7. package/ai/01-standards/llm-application-complete.md +488 -0
  8. package/ai/01-standards/mlops-complete.md +798 -0
  9. package/ai/01-standards/prompt-engineering-complete.md +646 -0
  10. package/ai/01-standards/rag-architecture-complete.md +649 -0
  11. package/ai/02-playbooks/llm-evaluation-playbook.md +847 -0
  12. package/ai/03-checklists/ai-project-checklist.md +215 -0
  13. package/ai/04-antipatterns/ai-antipatterns.md +661 -0
  14. package/ai/05-cases/case-rag-production.md +147 -0
  15. package/ai/06-glossary/ai-glossary.md +162 -0
  16. package/ai/agent-evaluation-benchmark.md +53 -0
  17. package/ai/ai-agent-memory-context-management.md +41 -0
  18. package/ai/ai-cost-capacity-optimization-playbook.md +42 -0
  19. package/ai/ai-data-security-and-compliance-playbook.md +37 -0
  20. package/ai/ai-domain-index-and-checklist.md +40 -0
  21. package/ai/ai-governance-maturity-model.md +50 -0
  22. package/ai/ai-model-selection-and-routing-strategy.md +47 -0
  23. package/ai/ai-observability-and-oncall-runbook.md +52 -0
  24. package/ai/ai-rag-engineering-playbook.md +42 -0
  25. package/ai/ai-red-team-and-safety-evaluation.md +42 -0
  26. package/ai/ai-release-readiness-and-rollback-gate.md +42 -0
  27. package/ai/llm-agent-engineering-deep-dive.md +57 -0
  28. package/ai/prompt-and-tool-guardrails.md +52 -0
  29. package/api/01-standards/enterprise-api-standards.md +198 -0
  30. package/api/01-standards/rest-api-design-guide.md +63 -0
  31. package/api/02-playbooks/api-pagination-playbook.md +93 -0
  32. package/api/02-playbooks/graphql-production-playbook.md +176 -0
  33. package/api/03-checklists/api-review-checklist.md +55 -0
  34. package/api/04-antipatterns/api-antipatterns.md +112 -0
  35. package/architecture/01-standards/api-gateway-patterns.md +496 -0
  36. package/architecture/01-standards/cloud-native-patterns.md +644 -0
  37. package/architecture/01-standards/distributed-systems-patterns.md +591 -0
  38. package/architecture/01-standards/event-driven-architecture.md +595 -0
  39. package/architecture/01-standards/microservices-patterns-complete.md +968 -0
  40. package/architecture/01-standards/microservices-patterns.md +495 -0
  41. package/architecture/01-standards/system-design-interview.md +664 -0
  42. package/architecture/02-playbooks/microservices-patterns-playbook.md +137 -0
  43. package/architecture/02-playbooks/migration-playbook.md +780 -0
  44. package/architecture/02-playbooks/system-design-playbook.md +779 -0
  45. package/architecture/03-checklists/architecture-decision-checklist.md +297 -0
  46. package/architecture/04-antipatterns/architecture-antipatterns.md +417 -0
  47. package/architecture/05-cases/case-netflix-microservices.md +413 -0
  48. package/architecture/06-glossary/architecture-glossary.md +164 -0
  49. package/architecture/adr-template-and-examples.md +38 -0
  50. package/architecture/api-gateway-deep-dive.md +1291 -0
  51. package/architecture/configuration-management.md +1162 -0
  52. package/architecture/distributed-transactions.md +1220 -0
  53. package/architecture/microservices-complete.md +735 -0
  54. package/architecture/resilience-and-disaster-patterns.md +37 -0
  55. package/architecture/service-governance.md +1198 -0
  56. package/architecture/system-architecture-deep-dive.md +37 -0
  57. package/backend/01-standards/analytics-and-growth.md +65 -0
  58. package/backend/01-standards/api-and-error-conventions.md +120 -0
  59. package/backend/01-standards/application-layering-and-packaging.md +160 -0
  60. package/backend/01-standards/auth-implementation.md +104 -0
  61. package/backend/01-standards/backend-framework-idioms.md +74 -0
  62. package/backend/01-standards/background-jobs-and-async.md +66 -0
  63. package/backend/01-standards/caching-strategies-complete.md +390 -0
  64. package/backend/01-standards/config-and-observability.md +77 -0
  65. package/backend/01-standards/data-modeling-and-persistence.md +94 -0
  66. package/backend/01-standards/django-complete.md +1765 -0
  67. package/backend/01-standards/email-and-notifications.md +64 -0
  68. package/backend/01-standards/fastapi-complete.md +925 -0
  69. package/backend/01-standards/file-upload-and-storage.md +66 -0
  70. package/backend/01-standards/graphql-api-complete.md +416 -0
  71. package/backend/01-standards/llm-application-standard.md +78 -0
  72. package/backend/01-standards/message-queue-patterns.md +379 -0
  73. package/backend/01-standards/microservices-and-distributed.md +78 -0
  74. package/backend/01-standards/nestjs-complete.md +2167 -0
  75. package/backend/01-standards/payment-integration.md +80 -0
  76. package/backend/01-standards/rate-limiting-complete.md +451 -0
  77. package/backend/01-standards/realtime-and-websocket.md +65 -0
  78. package/backend/01-standards/search-and-filtering.md +64 -0
  79. package/backend/01-standards/spring-boot-complete.md +445 -0
  80. package/backend/02-playbooks/api-design-playbook.md +718 -0
  81. package/backend/02-playbooks/email-send-playbook.md +130 -0
  82. package/backend/02-playbooks/file-upload-s3-playbook.md +153 -0
  83. package/backend/02-playbooks/typescript-enterprise-playbook.md +133 -0
  84. package/backend/02-playbooks/websocket-realtime-playbook.md +154 -0
  85. package/backend/03-checklists/api-launch-checklist.md +189 -0
  86. package/backend/04-antipatterns/backend-antipatterns.md +1051 -0
  87. package/blockchain/01-standards/blockchain-basics.md +557 -0
  88. package/blockchain/01-standards/smart-contract-development.md +1315 -0
  89. package/cicd/01-standards/deployment-and-delivery-standard.md +96 -0
  90. package/cicd/01-standards/github-actions-complete.md +473 -0
  91. package/cicd/01-standards/release-and-store-submission.md +75 -0
  92. package/cicd/02-playbooks/cicd-pipeline-playbook.md +144 -0
  93. package/cicd/02-playbooks/release-management-playbook.md +605 -0
  94. package/cicd/03-checklists/pipeline-security-checklist.md +168 -0
  95. package/cicd/04-antipatterns/cicd-antipatterns.md +589 -0
  96. package/cicd/05-cases/case-deployment-automation.md +221 -0
  97. package/cicd/05-cases/case-gitops-transformation.md +212 -0
  98. package/cicd/06-glossary/cicd-glossary.md +114 -0
  99. package/cicd/cicd-blueprint-deep-dive.md +38 -0
  100. package/cicd/release-readiness-gate.md +37 -0
  101. package/cloud-native/01-standards/container-security.md +741 -0
  102. package/cloud-native/01-standards/kubernetes-complete.md +812 -0
  103. package/cloud-native/02-playbooks/api-gateway-playbook.md +155 -0
  104. package/cloud-native/02-playbooks/gitops-with-argocd.md +760 -0
  105. package/cloud-native/02-playbooks/k8s-troubleshooting-playbook.md +1942 -0
  106. package/cloud-native/02-playbooks/message-queue-playbook.md +129 -0
  107. package/cloud-native/02-playbooks/multicloud-governance.md +726 -0
  108. package/cloud-native/02-playbooks/serverless-patterns.md +788 -0
  109. package/cloud-native/02-playbooks/service-mesh-playbook.md +612 -0
  110. package/cloud-native/02-playbooks/terraform-iac-playbook.md +143 -0
  111. package/cloud-native/03-checklists/container-security-checklist.md +431 -0
  112. package/cloud-native/03-checklists/k8s-production-readiness-checklist.md +460 -0
  113. package/cloud-native/04-antipatterns/container-antipatterns.md +660 -0
  114. package/cloud-native/04-antipatterns/k8s-antipatterns.md +743 -0
  115. package/cloud-native/05-cases/case-k8s-migration.md +478 -0
  116. package/cloud-native/05-cases/case-k8s-scaling.md +642 -0
  117. package/cloud-native/05-cases/case-k8s-security-incident.md +397 -0
  118. package/cloud-native/06-glossary/cloud-native-glossary.md +337 -0
  119. package/cross-platform/01-standards/cross-platform-frameworks.md +83 -0
  120. package/cross-platform/01-standards/platform-selection-and-architecture.md +77 -0
  121. package/data/01-standards/elasticsearch-complete.md +2098 -0
  122. package/data/01-standards/postgresql-complete.md +1613 -0
  123. package/data/01-standards/redis-complete.md +1527 -0
  124. package/data/02-playbooks/database-optimization-playbook.md +403 -0
  125. package/data/02-playbooks/elasticsearch-production-playbook.md +132 -0
  126. package/data/03-checklists/database-launch-checklist.md +187 -0
  127. package/data/04-antipatterns/database-antipatterns.md +873 -0
  128. package/data/05-cases/case-database-migration.md +310 -0
  129. package/data/06-glossary/database-glossary.md +440 -0
  130. package/data/data-governance-and-modeling-deep-dive.md +39 -0
  131. package/data-engineering/01-standards/airflow-complete.md +523 -0
  132. package/data-engineering/01-standards/kafka-complete.md +1521 -0
  133. package/data-engineering/02-playbooks/spark-etl-playbook.md +496 -0
  134. package/data-engineering/03-checklists/pipeline-launch-checklist.md +194 -0
  135. package/data-engineering/04-antipatterns/data-pipeline-antipatterns.md +684 -0
  136. package/data-engineering/05-cases/case-real-time-pipeline.md +355 -0
  137. package/data-engineering/06-glossary/data-engineering-glossary.md +429 -0
  138. package/database/01-standards/database-schema-standards.md +147 -0
  139. package/database/02-playbooks/postgresql-optimization-quick.md +52 -0
  140. package/database/02-playbooks/postgresql-performance-optimization.md +58 -0
  141. package/database/02-playbooks/postgresql-production-playbook.md +146 -0
  142. package/database/02-playbooks/redis-caching-playbook.md +117 -0
  143. package/database/03-checklists/database-review-checklist.md +50 -0
  144. package/database/04-antipatterns/database-antipatterns.md +112 -0
  145. package/design/01-standards/ui-design-system-complete.md +423 -0
  146. package/design/02-playbooks/design-handoff-playbook.md +254 -0
  147. package/design/02-playbooks/design-review-playbook.md +388 -0
  148. package/design/03-checklists/design-review-checklist.md +246 -0
  149. package/design/04-antipatterns/design-antipatterns.md +378 -0
  150. package/design/05-cases/case-design-system-adoption.md +328 -0
  151. package/design/06-glossary/design-glossary.md +329 -0
  152. package/design/ui-full-lifecycle-cross-platform-playbook.md +571 -0
  153. package/design/ux-system-deep-dive.md +38 -0
  154. package/design-systems/00-craft-rules.md +71 -0
  155. package/design-systems/aesthetic-families.md +43 -0
  156. package/design-systems/anti-ai-slop.md +162 -0
  157. package/design-systems/bold-geometric.md +120 -0
  158. package/design-systems/brutalist-bold.md +103 -0
  159. package/design-systems/editorial-clean.md +109 -0
  160. package/design-systems/glass-aurora.md +108 -0
  161. package/design-systems/modern-minimal.md +145 -0
  162. package/design-systems/premium-luxury.md +106 -0
  163. package/design-systems/product-type-design-map.md +48 -0
  164. package/design-systems/soft-warm.md +123 -0
  165. package/design-systems/tech-utility.md +113 -0
  166. package/desktop/01-standards/desktop-app-standard.md +72 -0
  167. package/desktop/01-standards/desktop-design.md +71 -0
  168. package/development/00-governance/document-template.md +41 -0
  169. package/development/01-standards/api-versioning-strategies.md +432 -0
  170. package/development/01-standards/authentication-patterns-complete.md +479 -0
  171. package/development/01-standards/css-architecture-complete.md +550 -0
  172. package/development/01-standards/database-migration-strategies.md +484 -0
  173. package/development/01-standards/elasticsearch-complete.md +347 -0
  174. package/development/01-standards/git-complete.md +371 -0
  175. package/development/01-standards/golang-complete.md +1565 -0
  176. package/development/01-standards/graphql-complete.md +298 -0
  177. package/development/01-standards/javascript-bundlers-complete.md +469 -0
  178. package/development/01-standards/javascript-typescript-complete.md +528 -0
  179. package/development/01-standards/jest-complete.md +275 -0
  180. package/development/01-standards/linux-complete.md +234 -0
  181. package/development/01-standards/logging-observability-complete.md +526 -0
  182. package/development/01-standards/microservices-communication.md +502 -0
  183. package/development/01-standards/mongodb-complete.md +406 -0
  184. package/development/01-standards/oauth2-complete.md +285 -0
  185. package/development/01-standards/performance-optimization-complete.md +289 -0
  186. package/development/01-standards/playwright-complete.md +247 -0
  187. package/development/01-standards/postgresql-complete.md +456 -0
  188. package/development/01-standards/pytest-complete.md +340 -0
  189. package/development/01-standards/python-async-programming.md +902 -0
  190. package/development/01-standards/python-complete.md +956 -0
  191. package/development/01-standards/python-decorators-complete.md +799 -0
  192. package/development/01-standards/python-design-patterns.md +2854 -0
  193. package/development/01-standards/python-packaging-distribution.md +420 -0
  194. package/development/01-standards/python-testing-strategies.md +607 -0
  195. package/development/01-standards/python-web-frameworks-comparison.md +471 -0
  196. package/development/01-standards/redis-complete.md +317 -0
  197. package/development/01-standards/rest-api-complete.md +316 -0
  198. package/development/01-standards/rust-complete.md +578 -0
  199. package/development/01-standards/typescript-advanced-types.md +1513 -0
  200. package/development/01-standards/web-security-complete.md +292 -0
  201. package/development/02-playbooks/api-design-playbook.md +810 -0
  202. package/development/02-playbooks/database-migration-playbook.md +580 -0
  203. package/development/02-playbooks/debugging-playbook.md +692 -0
  204. package/development/02-playbooks/feature-delivery-playbook.md +430 -0
  205. package/development/02-playbooks/incident-hotfix-playbook.md +387 -0
  206. package/development/02-playbooks/performance-optimization-playbook.md +531 -0
  207. package/development/02-playbooks/performance-tuning-playbook.md +652 -0
  208. package/development/02-playbooks/refactor-playbook.md +403 -0
  209. package/development/02-playbooks/release-playbook.md +469 -0
  210. package/development/03-checklists/architecture-review-checklist.md +168 -0
  211. package/development/03-checklists/data-migration-checklist.md +157 -0
  212. package/development/03-checklists/oncall-handover-checklist.md +173 -0
  213. package/development/03-checklists/pr-checklist.md +158 -0
  214. package/development/03-checklists/production-readiness-checklist.md +190 -0
  215. package/development/03-checklists/release-readiness-checklist.md +154 -0
  216. package/development/03-checklists/security-review-checklist.md +182 -0
  217. package/development/04-antipatterns/api-antipatterns.md +657 -0
  218. package/development/04-antipatterns/architecture-antipatterns.md +686 -0
  219. package/development/04-antipatterns/backend-antipatterns.md +648 -0
  220. package/development/04-antipatterns/cicd-antipatterns.md +540 -0
  221. package/development/04-antipatterns/code-smell-antipatterns.md +571 -0
  222. package/development/04-antipatterns/data-antipatterns.md +658 -0
  223. package/development/04-antipatterns/database-antipatterns.md +578 -0
  224. package/development/04-antipatterns/frontend-antipatterns.md +635 -0
  225. package/development/04-antipatterns/reliability-antipatterns.md +700 -0
  226. package/development/04-antipatterns/security-antipatterns.md +747 -0
  227. package/development/05-cases/case-api-version-migration.md +428 -0
  228. package/development/05-cases/case-authorization-hardening.md +383 -0
  229. package/development/05-cases/case-bluegreen-rollback.md +466 -0
  230. package/development/05-cases/case-cache-snowball-protection.md +485 -0
  231. package/development/05-cases/case-ci-cd-pipeline.md +544 -0
  232. package/development/05-cases/case-database-scaling.md +500 -0
  233. package/development/05-cases/case-db-hotspot-optimization.md +487 -0
  234. package/development/05-cases/case-incident-mttr-reduction.md +563 -0
  235. package/development/05-cases/case-microservice-migration.md +375 -0
  236. package/development/05-cases/case-performance-optimization.md +406 -0
  237. package/development/05-cases/case-security-incident-response.md +345 -0
  238. package/development/06-glossary/full-stack-glossary.md +166 -0
  239. package/development/09-maturity/quarterly-audit-template.md +35 -0
  240. package/development/11-ui-excellence/ui-aesthetic-system.md +41 -0
  241. package/development/11-ui-excellence/ui-engineering-excellence.md +435 -0
  242. package/development/12-scenarios/development-scenarios-guide.md +565 -0
  243. package/development/13-implementation-assets/implementation-toolkit.md +282 -0
  244. package/development/13-implementation-assets/knowledge-gates-execution.md +43 -0
  245. package/development/14-full-lifecycle/software-lifecycle-gates.md +511 -0
  246. package/development/15-lifecycle-templates/project-templates-collection.md +791 -0
  247. package/development/api-contract-and-versioning-guide.md +36 -0
  248. package/development/api-governance-complete.md +43 -0
  249. package/development/backend-engineering-complete.md +43 -0
  250. package/development/code-review-quality-complete.md +43 -0
  251. package/development/concurrency-reliability-complete.md +43 -0
  252. package/development/database-engineering-complete.md +43 -0
  253. package/development/engineering-effectiveness-complete.md +43 -0
  254. package/development/engineering-standards-deep-dive.md +38 -0
  255. package/development/frontend-engineering-complete.md +43 -0
  256. package/development/performance-capacity-complete.md +43 -0
  257. package/development/refactor-migration-complete.md +42 -0
  258. package/development/refactoring-and-techdebt-playbook.md +37 -0
  259. package/development/security-in-development-complete.md +43 -0
  260. package/devops/01-standards/cicd-pipeline-complete.md +262 -0
  261. package/devops/01-standards/docker-complete.md +1490 -0
  262. package/devops/01-standards/github-actions-complete.md +337 -0
  263. package/devops/01-standards/kubernetes-complete.md +638 -0
  264. package/devops/01-standards/terraform-complete.md +2117 -0
  265. package/devops/02-playbooks/docker-compose-playbook.md +233 -0
  266. package/devops/02-playbooks/docker-k8s-production-playbook.md +186 -0
  267. package/devops/02-playbooks/docker-production-playbook.md +952 -0
  268. package/edge-iot/01-standards/edge-iot-complete.md +473 -0
  269. package/experts/architect/api-design.md +178 -0
  270. package/experts/architect/methodology.md +124 -0
  271. package/experts/architect/security.md +75 -0
  272. package/experts/backend-lead/methodology.md +216 -0
  273. package/experts/devops/methodology.md +160 -0
  274. package/experts/frontend-lead/methodology.md +178 -0
  275. package/experts/product-manager/industry/ecommerce.md +43 -0
  276. package/experts/product-manager/industry/saas.md +40 -0
  277. package/experts/product-manager/methodology.md +97 -0
  278. package/experts/qa-lead/methodology.md +123 -0
  279. package/experts/qa-lead/test-strategy.md +128 -0
  280. package/experts/uiux-designer/methodology.md +125 -0
  281. package/frontend/01-standards/accessibility-complete.md +532 -0
  282. package/frontend/01-standards/accessibility-standard.md +74 -0
  283. package/frontend/01-standards/admin-dashboard-and-crud.md +72 -0
  284. package/frontend/01-standards/design-tokens-complete.md +444 -0
  285. package/frontend/01-standards/forms-and-validation.md +77 -0
  286. package/frontend/01-standards/frontend-architecture-and-layering.md +119 -0
  287. package/frontend/01-standards/i18n-and-localization.md +65 -0
  288. package/frontend/01-standards/nextjs-complete.md +451 -0
  289. package/frontend/01-standards/react-complete.md +713 -0
  290. package/frontend/01-standards/react-hooks-complete-guide.md +1100 -0
  291. package/frontend/01-standards/react-hooks-complete.md +1171 -0
  292. package/frontend/01-standards/seo-and-web-vitals.md +77 -0
  293. package/frontend/01-standards/state-management-complete.md +444 -0
  294. package/frontend/01-standards/vue-complete.md +499 -0
  295. package/frontend/01-standards/vue3-complete.md +2002 -0
  296. package/frontend/01-standards/web-framework-best-practices.md +64 -0
  297. package/frontend/01-standards/web-performance-complete.md +495 -0
  298. package/frontend/02-playbooks/accessibility-a11y-playbook.md +161 -0
  299. package/frontend/02-playbooks/frontend-performance-playbook.md +707 -0
  300. package/frontend/02-playbooks/i18n-internationalization-playbook.md +120 -0
  301. package/frontend/02-playbooks/performance-optimization-playbook.md +163 -0
  302. package/frontend/02-playbooks/react-nextjs-production-playbook.md +167 -0
  303. package/frontend/02-playbooks/react-state-management-playbook.md +173 -0
  304. package/frontend/03-checklists/component-quality-checklist.md +166 -0
  305. package/frontend/03-checklists/frontend-launch-checklist.md +299 -0
  306. package/frontend/04-antipatterns/frontend-antipatterns.md +886 -0
  307. package/frontend/05-cases/case-performance-optimization.md +274 -0
  308. package/harmony/01-standards/harmonyos-arkts-standard.md +75 -0
  309. package/harmony/01-standards/harmonyos-design.md +65 -0
  310. package/high-quality-engineering-playbook.md +54 -0
  311. package/incident/01-standards/incident-response-complete.md +303 -0
  312. package/incident/02-playbooks/chaos-engineering-playbook.md +883 -0
  313. package/incident/02-playbooks/postmortem-playbook.md +398 -0
  314. package/incident/03-checklists/incident-readiness-checklist.md +181 -0
  315. package/incident/04-antipatterns/incident-antipatterns.md +490 -0
  316. package/incident/05-cases/case-cascade-failure.md +176 -0
  317. package/incident/06-glossary/incident-glossary.md +114 -0
  318. package/incident/postmortem-and-response-deep-dive.md +39 -0
  319. package/industries/ecommerce/ecommerce-complete.md +631 -0
  320. package/industries/education/education-complete.md +555 -0
  321. package/industries/fintech/fintech-complete.md +501 -0
  322. package/industries/gaming/gaming-complete.md +587 -0
  323. package/industries/healthcare/healthcare-complete.md +452 -0
  324. package/low-code/01-standards/low-code-complete.md +944 -0
  325. package/miniprogram/01-standards/ai-common-mistakes.md +61 -0
  326. package/miniprogram/01-standards/miniprogram-custom-navbar-capsule.md +77 -0
  327. package/miniprogram/01-standards/miniprogram-design.md +61 -0
  328. package/miniprogram/01-standards/miniprogram-standard.md +81 -0
  329. package/mobile/01-standards/android-material-design.md +70 -0
  330. package/mobile/01-standards/flutter-complete.md +384 -0
  331. package/mobile/01-standards/ios-design-hig.md +78 -0
  332. package/mobile/01-standards/mobile-app-standard.md +85 -0
  333. package/mobile/01-standards/react-native-complete.md +352 -0
  334. package/mobile/02-playbooks/mobile-cross-platform-playbook.md +175 -0
  335. package/mobile/02-playbooks/mobile-performance.md +473 -0
  336. package/mobile/03-checklists/mobile-release-checklist.md +234 -0
  337. package/mobile/04-antipatterns/mobile-antipatterns.md +798 -0
  338. package/mobile/05-cases/case-app-performance.md +500 -0
  339. package/mobile/05-cases/case-app-startup-optimization.md +218 -0
  340. package/mobile/06-glossary/mobile-glossary.md +484 -0
  341. package/observability/01-standards/observability-standards.md +103 -0
  342. package/observability/02-playbooks/prometheus-grafana-playbook.md +135 -0
  343. package/observability/02-playbooks/structured-logging-playbook.md +73 -0
  344. package/observability/03-checklists/observability-checklist.md +54 -0
  345. package/observability/04-antipatterns/observability-antipatterns.md +106 -0
  346. package/operations/01-standards/prometheus-monitoring-complete.md +1578 -0
  347. package/operations/02-playbooks/capacity-planning-playbook.md +620 -0
  348. package/operations/03-checklists/production-launch-checklist.md +365 -0
  349. package/operations/04-antipatterns/operations-antipatterns.md +664 -0
  350. package/operations/05-cases/case-sre-practices.md +581 -0
  351. package/operations/06-glossary/operations-glossary.md +120 -0
  352. package/operations/aiops-anomaly-detection.md +758 -0
  353. package/operations/capacity-planning.md +1061 -0
  354. package/operations/chaos-engineering.md +659 -0
  355. package/operations/incident-command-system.md +38 -0
  356. package/operations/observability-complete.md +442 -0
  357. package/operations/slo-sli-playbook.md +517 -0
  358. package/operations/sre-operations-deep-dive.md +39 -0
  359. package/package.json +8 -0
  360. package/performance/01-standards/performance-and-scalability.md +80 -0
  361. package/performance/01-standards/performance-standards.md +156 -0
  362. package/performance/02-playbooks/query-optimization-playbook.md +103 -0
  363. package/performance/03-checklists/performance-checklist.md +56 -0
  364. package/performance/04-antipatterns/performance-antipatterns.md +146 -0
  365. package/product/01-standards/product-management-complete.md +285 -0
  366. package/product/02-playbooks/feature-launch-playbook.md +207 -0
  367. package/product/02-playbooks/user-research-playbook.md +532 -0
  368. package/product/03-checklists/feature-launch-checklist.md +275 -0
  369. package/product/04-antipatterns/product-antipatterns.md +355 -0
  370. package/product/05-cases/case-mvp-to-scale.md +384 -0
  371. package/product/06-glossary/product-glossary.md +462 -0
  372. package/product/feature-prioritization-framework.md +40 -0
  373. package/product/kpi-and-metric-tree.md +37 -0
  374. package/product/product-discovery-and-prd-deep-dive.md +41 -0
  375. package/quantum/01-standards/quantum-complete.md +1186 -0
  376. package/security/01-standards/api-security-complete.md +511 -0
  377. package/security/01-standards/container-runtime-security.md +574 -0
  378. package/security/01-standards/data-protection-gdpr.md +543 -0
  379. package/security/01-standards/owasp-top10-complete.md +1890 -0
  380. package/security/01-standards/secure-coding-baseline.md +90 -0
  381. package/security/01-standards/supply-chain-security.md +441 -0
  382. package/security/01-standards/web-security-checklist.md +108 -0
  383. package/security/01-standards/zero-trust-architecture.md +521 -0
  384. package/security/02-playbooks/auth-sso-playbook.md +166 -0
  385. package/security/02-playbooks/incident-response-security-playbook.md +588 -0
  386. package/security/02-playbooks/owasp-api-security-playbook.md +129 -0
  387. package/security/02-playbooks/payment-integration-playbook.md +119 -0
  388. package/security/02-playbooks/penetration-testing-playbook.md +517 -0
  389. package/security/03-checklists/security-audit-checklist.md +356 -0
  390. package/security/04-antipatterns/security-coding-antipatterns.md +580 -0
  391. package/security/05-cases/case-log4shell-incident.md +537 -0
  392. package/security/05-cases/case-major-breaches.md +468 -0
  393. package/security/06-glossary/security-glossary.md +212 -0
  394. package/security/compliance-automation.md +993 -0
  395. package/security/container-security.md +680 -0
  396. package/security/devsecops-complete.md +426 -0
  397. package/security/sast-dast-sca.md +775 -0
  398. package/security/secrets-management.md +594 -0
  399. package/security/security-architecture-deep-dive.md +37 -0
  400. package/security/threat-modeling-stride-playbook.md +40 -0
  401. package/seed-templates/auth-system.md +59 -0
  402. package/seed-templates/blog-content.md +94 -0
  403. package/seed-templates/dashboard.md +89 -0
  404. package/seed-templates/docs-site.md +73 -0
  405. package/seed-templates/e-commerce.md +50 -0
  406. package/seed-templates/saas-landing.md +92 -0
  407. package/seed-templates/settings-page.md +51 -0
  408. package/testing/01-standards/test-strategy-and-layering.md +83 -0
  409. package/testing/01-standards/testing-strategy-complete.md +422 -0
  410. package/testing/01-standards/unit-testing-best-practices.md +118 -0
  411. package/testing/02-playbooks/e2e-testing-playbook.md +988 -0
  412. package/testing/02-playbooks/testing-strategy-playbook.md +126 -0
  413. package/testing/03-checklists/test-strategy-checklist.md +208 -0
  414. package/testing/04-antipatterns/testing-antipatterns.md +718 -0
  415. package/testing/05-cases/case-testing-transformation.md +300 -0
  416. package/testing/06-glossary/testing-glossary.md +110 -0
  417. package/testing/risk-based-test-matrix.md +36 -0
  418. package/testing/testing-strategy-deep-dive.md +37 -0
@@ -0,0 +1,902 @@
1
+ ---
2
+ id: python-async-programming
3
+ title: Python 异步编程完整指南
4
+ domain: development
5
+ category: 01-standards
6
+ difficulty: intermediate
7
+ tags: [async, development, programming, python, 实战案例, 常见陷阱与反模式, 异步编程模式, 性能优化技巧]
8
+ quality_score: 70
9
+ last_updated: 2026-06-15
10
+ ---
11
+ # Python 异步编程完整指南
12
+
13
+ ## 概述
14
+
15
+ Python 异步编程是一种并发编程范式,通过 `asyncio` 库和 `async/await` 语法实现高效的 I/O 密集型任务处理。与多线程/多进程相比,异步编程使用单线程事件循环,避免了线程切换开销和 GIL(全局解释器锁)限制,适合处理大量并发网络请求、文件 I/O、数据库操作等场景。
16
+
17
+ ### 核心优势
18
+
19
+ - **高并发性能**: 单线程可处理数千个并发连接
20
+ - **低资源消耗**: 相比多线程,内存和 CPU 开销更小
21
+ - **简洁的代码**: `async/await` 语法让异步代码像同步代码一样易读
22
+ - **适合 I/O 密集型**: 网络请求、文件操作、数据库查询的理想选择
23
+
24
+ ### 适用场景
25
+
26
+ ✅ **适合异步编程**:
27
+ - Web 服务器和 API 服务(FastAPI, Sanic, Tornado)
28
+ - 网络爬虫和 HTTP 客户端
29
+ - WebSocket 实时通信
30
+ - 数据库异步查询(SQLAlchemy async, Tortoise ORM)
31
+ - 消息队列消费者
32
+ - 微服务间通信
33
+
34
+ ❌ **不适合异步编程**:
35
+ - CPU 密集型计算(图像处理、机器学习训练)
36
+ - 需要真正的并行计算(应使用多进程)
37
+ - 与阻塞式库交互(如 requests, psycopg2)
38
+
39
+ ---
40
+
41
+ ## 核心概念
42
+
43
+ ### 1. 事件循环 (Event Loop)
44
+
45
+ 事件循环是异步编程的核心,负责调度和执行协程。它维护一个任务队列,不断从队列中取出任务执行,当任务遇到 I/O 操作时挂起,让出控制权,等待 I/O 完成后恢复执行。
46
+
47
+ ```python
48
+ import asyncio
49
+
50
+ # 获取当前事件循环
51
+ loop = asyncio.get_event_loop()
52
+
53
+ # Python 3.7+ 推荐方式
54
+ async def main():
55
+ print("Hello, Async!")
56
+
57
+ asyncio.run(main()) # 自动创建和关闭事件循环
58
+ ```
59
+
60
+ ### 2. 协程 (Coroutine)
61
+
62
+ 协程是使用 `async def` 定义的函数,调用时不会立即执行,而是返回一个协程对象。协程需要被事件循环调度才能执行。
63
+
64
+ ```python
65
+ async def fetch_data(url):
66
+ """定义协程"""
67
+ print(f"Fetching {url}")
68
+ await asyncio.sleep(1) # 模拟 I/O 操作
69
+ return f"Data from {url}"
70
+
71
+ # 调用协程(不执行)
72
+ coro = fetch_data("https://example.com")
73
+ print(coro) # <coroutine object fetch_data at 0x...>
74
+
75
+ # 执行协程
76
+ result = asyncio.run(fetch_data("https://example.com"))
77
+ print(result) # Data from https://example.com
78
+ ```
79
+
80
+ ### 3. await 关键字
81
+
82
+ `await` 用于挂起当前协程,等待另一个协程完成。它只能在 `async def` 函数内部使用。
83
+
84
+ ```python
85
+ async def step1():
86
+ await asyncio.sleep(1)
87
+ return "Step 1 done"
88
+
89
+ async def step2():
90
+ await asyncio.sleep(1)
91
+ return "Step 2 done"
92
+
93
+ async def main():
94
+ result1 = await step1() # 等待 step1 完成
95
+ result2 = await step2() # 等待 step2 完成
96
+ print(result1, result2)
97
+
98
+ asyncio.run(main())
99
+ ```
100
+
101
+ ### 4. Task (任务)
102
+
103
+ Task 是协程的包装器,用于在事件循环中调度协程。使用 `asyncio.create_task()` 可以并发执行多个协程。
104
+
105
+ ```python
106
+ async def download_file(url):
107
+ await asyncio.sleep(2)
108
+ return f"Downloaded {url}"
109
+
110
+ async def main():
111
+ # 创建 3 个并发任务
112
+ task1 = asyncio.create_task(download_file("file1.txt"))
113
+ task2 = asyncio.create_task(download_file("file2.txt"))
114
+ task3 = asyncio.create_task(download_file("file3.txt"))
115
+
116
+ # 等待所有任务完成
117
+ results = await asyncio.gather(task1, task2, task3)
118
+ print(results)
119
+
120
+ asyncio.run(main())
121
+ ```
122
+
123
+ ### 5. Future (未来对象)
124
+
125
+ Future 是一个低级别的可等待对象,代表一个异步操作的最终结果。Task 是 Future 的子类。
126
+
127
+ ```python
128
+ async def set_future_value(future, value):
129
+ await asyncio.sleep(1)
130
+ future.set_result(value)
131
+
132
+ async def main():
133
+ future = asyncio.Future()
134
+
135
+ # 在另一个任务中设置 Future 的值
136
+ asyncio.create_task(set_future_value(future, "Hello"))
137
+
138
+ # 等待 Future
139
+ result = await future
140
+ print(result) # Hello
141
+
142
+ asyncio.run(main())
143
+ ```
144
+
145
+ ---
146
+
147
+ ## 异步编程模式
148
+
149
+ ### 模式 1: 并发执行多个任务
150
+
151
+ 使用 `asyncio.gather()` 并发执行多个协程:
152
+
153
+ ```python
154
+ import asyncio
155
+ import aiohttp
156
+
157
+ async def fetch_url(session, url):
158
+ async with session.get(url) as response:
159
+ return await response.text()
160
+
161
+ async def fetch_all(urls):
162
+ async with aiohttp.ClientSession() as session:
163
+ tasks = [fetch_url(session, url) for url in urls]
164
+ results = await asyncio.gather(*tasks)
165
+ return results
166
+
167
+ urls = [
168
+ "https://example.com",
169
+ "https://httpbin.org",
170
+ "https://jsonplaceholder.typicode.com"
171
+ ]
172
+
173
+ results = asyncio.run(fetch_all(urls))
174
+ print(f"Fetched {len(results)} pages")
175
+ ```
176
+
177
+ ### 模式 2: 超时控制
178
+
179
+ 使用 `asyncio.wait_for()` 设置超时:
180
+
181
+ ```python
182
+ async def slow_operation():
183
+ await asyncio.sleep(10)
184
+ return "Done"
185
+
186
+ async def main():
187
+ try:
188
+ result = await asyncio.wait_for(slow_operation(), timeout=3.0)
189
+ print(result)
190
+ except asyncio.TimeoutError:
191
+ print("Operation timed out!")
192
+
193
+ asyncio.run(main())
194
+ ```
195
+
196
+ ### 模式 3: 取消任务
197
+
198
+ ```python
199
+ async def long_running_task():
200
+ try:
201
+ print("Task started")
202
+ await asyncio.sleep(10)
203
+ print("Task completed")
204
+ except asyncio.CancelledError:
205
+ print("Task was cancelled")
206
+ raise
207
+
208
+ async def main():
209
+ task = asyncio.create_task(long_running_task())
210
+
211
+ await asyncio.sleep(2)
212
+ task.cancel() # 取消任务
213
+
214
+ try:
215
+ await task
216
+ except asyncio.CancelledError:
217
+ print("Main: Task cancelled")
218
+
219
+ asyncio.run(main())
220
+ ```
221
+
222
+ ### 模式 4: 异步上下文管理器
223
+
224
+ ```python
225
+ from contextlib import asynccontextmanager
226
+
227
+ @asynccontextmanager
228
+ async def async_database_connection():
229
+ print("Connecting to database...")
230
+ await asyncio.sleep(1)
231
+ conn = {"connected": True}
232
+ try:
233
+ yield conn
234
+ finally:
235
+ print("Closing connection...")
236
+ await asyncio.sleep(0.5)
237
+
238
+ async def main():
239
+ async with async_database_connection() as conn:
240
+ print(f"Using connection: {conn}")
241
+
242
+ asyncio.run(main())
243
+ ```
244
+
245
+ ### 模式 5: 异步迭代器
246
+
247
+ ```python
248
+ class AsyncRange:
249
+ def __init__(self, count):
250
+ self.count = count
251
+ self.current = 0
252
+
253
+ def __aiter__(self):
254
+ return self
255
+
256
+ async def __anext__(self):
257
+ if self.current < self.count:
258
+ await asyncio.sleep(0.1)
259
+ value = self.current
260
+ self.current += 1
261
+ return value
262
+ else:
263
+ raise StopAsyncIteration
264
+
265
+ async def main():
266
+ async for number in AsyncRange(5):
267
+ print(number)
268
+
269
+ asyncio.run(main())
270
+ ```
271
+
272
+ ### 模式 6: 异步生成器
273
+
274
+ ```python
275
+ async def async_fibonacci(n):
276
+ a, b = 0, 1
277
+ for _ in range(n):
278
+ await asyncio.sleep(0.1)
279
+ yield a
280
+ a, b = b, a + b
281
+
282
+ async def main():
283
+ async for fib in async_fibonacci(10):
284
+ print(fib)
285
+
286
+ asyncio.run(main())
287
+ ```
288
+
289
+ ---
290
+
291
+ ## 实战案例
292
+
293
+ ### 案例 1: 异步 HTTP 爬虫
294
+
295
+ ```python
296
+ import asyncio
297
+ import aiohttp
298
+ from typing import List, Dict
299
+ import time
300
+
301
+ class AsyncWebCrawler:
302
+ def __init__(self, max_concurrent: int = 10):
303
+ self.max_concurrent = max_concurrent
304
+ self.semaphore = asyncio.Semaphore(max_concurrent)
305
+
306
+ async def fetch_page(self, session: aiohttp.ClientSession, url: str) -> Dict:
307
+ async with self.semaphore:
308
+ try:
309
+ async with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as response:
310
+ html = await response.text()
311
+ return {
312
+ "url": url,
313
+ "status": response.status,
314
+ "length": len(html),
315
+ "success": True
316
+ }
317
+ except Exception as e:
318
+ return {
319
+ "url": url,
320
+ "error": str(e),
321
+ "success": False
322
+ }
323
+
324
+ async def crawl(self, urls: List[str]) -> List[Dict]:
325
+ async with aiohttp.ClientSession() as session:
326
+ tasks = [self.fetch_page(session, url) for url in urls]
327
+ results = await asyncio.gather(*tasks, return_exceptions=True)
328
+ return results
329
+
330
+ async def main():
331
+ urls = [f"https://httpbin.org/delay/{i}" for i in range(1, 20)]
332
+
333
+ crawler = AsyncWebCrawler(max_concurrent=5)
334
+
335
+ start = time.time()
336
+ results = await crawler.crawl(urls)
337
+ end = time.time()
338
+
339
+ success_count = sum(1 for r in results if isinstance(r, dict) and r.get("success"))
340
+ print(f"Crawled {success_count}/{len(urls)} pages in {end-start:.2f}s")
341
+
342
+ asyncio.run(main())
343
+ ```
344
+
345
+ ### 案例 2: 异步数据库操作 (使用 SQLAlchemy 2.0)
346
+
347
+ ```python
348
+ from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
349
+ from sqlalchemy.orm import sessionmaker, declarative_base
350
+ from sqlalchemy import Column, Integer, String, select
351
+ import asyncio
352
+
353
+ Base = declarative_base()
354
+
355
+ class User(Base):
356
+ __tablename__ = "users"
357
+ id = Column(Integer, primary_key=True)
358
+ name = Column(String)
359
+ email = Column(String)
360
+
361
+ # SQLite 异步引擎
362
+ engine = create_async_engine("sqlite+aiosqlite:///test.db", echo=True)
363
+ AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
364
+
365
+ async def create_tables():
366
+ async with engine.begin() as conn:
367
+ await conn.run_sync(Base.metadata.create_all)
368
+
369
+ async def insert_users():
370
+ async with AsyncSessionLocal() as session:
371
+ users = [
372
+ User(name="Alice", email="alice@example.com"),
373
+ User(name="Bob", email="bob@example.com"),
374
+ User(name="Charlie", email="charlie@example.com"),
375
+ ]
376
+ session.add_all(users)
377
+ await session.commit()
378
+
379
+ async def query_users():
380
+ async with AsyncSessionLocal() as session:
381
+ result = await session.execute(select(User).where(User.name.like("A%")))
382
+ users = result.scalars().all()
383
+ for user in users:
384
+ print(f"{user.name}: {user.email}")
385
+
386
+ async def main():
387
+ await create_tables()
388
+ await insert_users()
389
+ await query_users()
390
+
391
+ asyncio.run(main())
392
+ ```
393
+
394
+ ### 案例 3: 异步消息队列消费者
395
+
396
+ ```python
397
+ import asyncio
398
+ import json
399
+ from collections import deque
400
+
401
+ class AsyncMessageQueue:
402
+ def __init__(self):
403
+ self.queue = deque()
404
+ self.condition = asyncio.Condition()
405
+
406
+ async def put(self, message):
407
+ async with self.condition:
408
+ self.queue.append(message)
409
+ self.condition.notify()
410
+
411
+ async def get(self):
412
+ async with self.condition:
413
+ while not self.queue:
414
+ await self.condition.wait()
415
+ return self.queue.popleft()
416
+
417
+ async def producer(queue, producer_id):
418
+ for i in range(10):
419
+ message = {"producer": producer_id, "data": i}
420
+ await queue.put(message)
421
+ print(f"Producer {producer_id} sent: {message}")
422
+ await asyncio.sleep(0.5)
423
+
424
+ async def consumer(queue, consumer_id):
425
+ while True:
426
+ message = await queue.get()
427
+ print(f"Consumer {consumer_id} received: {message}")
428
+ await asyncio.sleep(1)
429
+
430
+ async def main():
431
+ queue = AsyncMessageQueue()
432
+
433
+ # 启动 2 个生产者和 3 个消费者
434
+ producers = [producer(queue, i) for i in range(2)]
435
+ consumers = [consumer(queue, i) for i in range(3)]
436
+
437
+ await asyncio.gather(*producers)
438
+ await asyncio.gather(*consumers)
439
+
440
+ asyncio.run(main())
441
+ ```
442
+
443
+ ### 案例 4: 异步 API 服务器 (FastAPI)
444
+
445
+ ```python
446
+ from fastapi import FastAPI, HTTPException
447
+ from pydantic import BaseModel
448
+ import asyncio
449
+ import aiohttp
450
+
451
+ app = FastAPI()
452
+
453
+ class Item(BaseModel):
454
+ name: str
455
+ price: float
456
+
457
+ # 模拟数据库
458
+ fake_db = {}
459
+
460
+ @app.post("/items/")
461
+ async def create_item(item: Item):
462
+ await asyncio.sleep(0.1) # 模拟数据库延迟
463
+ item_id = len(fake_db) + 1
464
+ fake_db[item_id] = item
465
+ return {"id": item_id, "item": item}
466
+
467
+ @app.get("/items/{item_id}")
468
+ async def read_item(item_id: int):
469
+ await asyncio.sleep(0.05)
470
+ if item_id not in fake_db:
471
+ raise HTTPException(status_code=404, detail="Item not found")
472
+ return fake_db[item_id]
473
+
474
+ @app.get("/external-api")
475
+ async def call_external_api():
476
+ async with aiohttp.ClientSession() as session:
477
+ async with session.get("https://httpbin.org/json") as response:
478
+ data = await response.json()
479
+ return data
480
+
481
+ if __name__ == "__main__":
482
+ import uvicorn
483
+ uvicorn.run(app, host="0.0.0.0", port=8000)
484
+ ```
485
+
486
+ ---
487
+
488
+ ## 性能优化技巧
489
+
490
+ ### 1. 使用连接池
491
+
492
+ ```python
493
+ import aiohttp
494
+
495
+ # 错误: 每次请求创建新连接
496
+ async def bad_approach():
497
+ for url in urls:
498
+ async with aiohttp.ClientSession() as session:
499
+ async with session.get(url) as response:
500
+ await response.text()
501
+
502
+ # 正确: 复用连接池
503
+ async def good_approach():
504
+ async with aiohttp.ClientSession() as session:
505
+ tasks = [session.get(url) for url in urls]
506
+ responses = await asyncio.gather(*tasks)
507
+ ```
508
+
509
+ ### 2. 限制并发数量
510
+
511
+ ```python
512
+ async def fetch_with_limit(urls, max_concurrent=10):
513
+ semaphore = asyncio.Semaphore(max_concurrent)
514
+
515
+ async def fetch(url):
516
+ async with semaphore:
517
+ async with aiohttp.ClientSession() as session:
518
+ async with session.get(url) as response:
519
+ return await response.text()
520
+
521
+ return await asyncio.gather(*[fetch(url) for url in urls])
522
+ ```
523
+
524
+ ### 3. 批处理操作
525
+
526
+ ```python
527
+ async def batch_insert(items, batch_size=100):
528
+ for i in range(0, len(items), batch_size):
529
+ batch = items[i:i+batch_size]
530
+ # 批量插入数据库
531
+ await database_insert_batch(batch)
532
+ ```
533
+
534
+ ### 4. 避免阻塞操作
535
+
536
+ ```python
537
+ import asyncio
538
+ import time
539
+
540
+ # 错误: 使用阻塞式 sleep
541
+ async def bad():
542
+ time.sleep(1) # 阻塞整个事件循环!
543
+
544
+ # 正确: 使用异步 sleep
545
+ async def good():
546
+ await asyncio.sleep(1) # 让出控制权
547
+ ```
548
+
549
+ ### 5. 使用 `asyncio.to_thread()` 处理 CPU 密集型任务
550
+
551
+ ```python
552
+ import asyncio
553
+
554
+ def cpu_intensive_task(n):
555
+ """CPU 密集型函数"""
556
+ return sum(i * i for i in range(n))
557
+
558
+ async def main():
559
+ # 在单独的线程中运行 CPU 密集型任务
560
+ result = await asyncio.to_thread(cpu_intensive_task, 10**6)
561
+ print(result)
562
+
563
+ asyncio.run(main())
564
+ ```
565
+
566
+ ---
567
+
568
+ ## 常见陷阱与反模式
569
+
570
+ ### 反模式 1: 忘记 await
571
+
572
+ ```python
573
+ # ❌ 错误: 忘记 await
574
+ async def bad():
575
+ result = async_function() # 返回协程对象,不执行
576
+ print(result) # <coroutine object>
577
+
578
+ # ✅ 正确
579
+ async def good():
580
+ result = await async_function()
581
+ print(result)
582
+ ```
583
+
584
+ ### 反模式 2: 在同步代码中调用异步函数
585
+
586
+ ```python
587
+ # ❌ 错误: 在同步函数中调用异步函数
588
+ def bad():
589
+ result = await async_function() # SyntaxError!
590
+
591
+ # ✅ 正确: 使用 asyncio.run()
592
+ def good():
593
+ result = asyncio.run(async_function())
594
+ ```
595
+
596
+ ### 反模式 3: 过度使用 asyncio.sleep(0)
597
+
598
+ ```python
599
+ # ❌ 不好: 过度让步
600
+ async def bad():
601
+ for i in range(10000):
602
+ await asyncio.sleep(0) # 不必要的让步
603
+ process(i)
604
+
605
+ # ✅ 更好: 只在必要时让步
606
+ async def good():
607
+ for i in range(10000):
608
+ process(i)
609
+ if i % 100 == 0: # 每 100 次让步一次
610
+ await asyncio.sleep(0)
611
+ ```
612
+
613
+ ### 反模式 4: 不处理异常
614
+
615
+ ```python
616
+ # ❌ 错误: 不处理异常会导致任务静默失败
617
+ async def bad():
618
+ tasks = [task1(), task2(), task3()]
619
+ await asyncio.gather(*tasks) # 如果一个失败,其他继续
620
+
621
+ # ✅ 正确: 捕获和处理异常
622
+ async def good():
623
+ tasks = [task1(), task2(), task3()]
624
+ results = await asyncio.gather(*tasks, return_exceptions=True)
625
+ for result in results:
626
+ if isinstance(result, Exception):
627
+ print(f"Task failed: {result}")
628
+ ```
629
+
630
+ ### 反模式 5: 不关闭资源
631
+
632
+ ```python
633
+ # ❌ 错误: 不关闭会话
634
+ async def bad():
635
+ session = aiohttp.ClientSession()
636
+ await session.get("https://example.com")
637
+ # 忘记关闭 session!
638
+
639
+ # ✅ 正确: 使用上下文管理器
640
+ async def good():
641
+ async with aiohttp.ClientSession() as session:
642
+ await session.get("https://example.com")
643
+ # 自动关闭
644
+ ```
645
+
646
+ ---
647
+
648
+ ## 调试技巧
649
+
650
+ ### 1. 启用异步调试模式
651
+
652
+ ```python
653
+ import asyncio
654
+
655
+ # 启用调试模式
656
+ asyncio.run(main(), debug=True)
657
+ ```
658
+
659
+ ### 2. 检查协程是否被 await
660
+
661
+ ```python
662
+ import warnings
663
+
664
+ # 启用协程未 await 警告
665
+ warnings.filterwarnings("error", category=RuntimeWarning)
666
+ ```
667
+
668
+ ### 3. 使用 `asyncio.all_tasks()` 查看运行中的任务
669
+
670
+ ```python
671
+ async def monitor_tasks():
672
+ while True:
673
+ tasks = asyncio.all_tasks()
674
+ print(f"Running tasks: {len(tasks)}")
675
+ for task in tasks:
676
+ print(f" - {task.get_name()}: {task.get_coro()}")
677
+ await asyncio.sleep(5)
678
+ ```
679
+
680
+ ### 4. 使用 `asyncio.current_task()` 获取当前任务
681
+
682
+ ```python
683
+ async def my_task():
684
+ current = asyncio.current_task()
685
+ print(f"Current task: {current.get_name()}")
686
+ ```
687
+
688
+ ---
689
+
690
+ ## 测试异步代码
691
+
692
+ ### 使用 pytest + pytest-asyncio
693
+
694
+ ```python
695
+ # 安装: pip install pytest pytest-asyncio
696
+
697
+ import pytest
698
+ import asyncio
699
+
700
+ @pytest.mark.asyncio
701
+ async def test_async_function():
702
+ result = await async_function()
703
+ assert result == expected_value
704
+
705
+ @pytest.mark.asyncio
706
+ async def test_concurrent_tasks():
707
+ task1 = asyncio.create_task(slow_operation())
708
+ task2 = asyncio.create_task(another_operation())
709
+
710
+ results = await asyncio.gather(task1, task2)
711
+ assert len(results) == 2
712
+
713
+ # 测试异常
714
+ @pytest.mark.asyncio
715
+ async def test_exception_handling():
716
+ with pytest.raises(ValueError):
717
+ await function_that_raises()
718
+ ```
719
+
720
+ ### Mock 异步函数
721
+
722
+ ```python
723
+ from unittest.mock import AsyncMock, patch
724
+
725
+ @pytest.mark.asyncio
726
+ async def test_with_mock():
727
+ with patch("module.async_function") as mock_func:
728
+ mock_func.return_value = "mocked result"
729
+
730
+ result = await module.async_function()
731
+ assert result == "mocked result"
732
+ mock_func.assert_called_once()
733
+ ```
734
+
735
+ ---
736
+
737
+ ## 迁移指南: 从同步到异步
738
+
739
+ ### Step 1: 识别阻塞点
740
+
741
+ ```python
742
+ # 同步代码
743
+ import requests
744
+ import time
745
+
746
+ def fetch_all(urls):
747
+ results = []
748
+ for url in urls:
749
+ response = requests.get(url) # 阻塞点!
750
+ results.append(response.text)
751
+ return results
752
+ ```
753
+
754
+ ### Step 2: 替换为异步库
755
+
756
+ ```python
757
+ # 异步代码
758
+ import aiohttp
759
+ import asyncio
760
+
761
+ async def fetch_all(urls):
762
+ async with aiohttp.ClientSession() as session:
763
+ tasks = []
764
+ for url in urls:
765
+ task = session.get(url) # 非阻塞
766
+ tasks.append(task)
767
+
768
+ responses = await asyncio.gather(*tasks)
769
+ results = [await r.text() for r in responses]
770
+ return results
771
+ ```
772
+
773
+ ### Step 3: 使用异步数据库驱动
774
+
775
+ | 同步库 | 异步替代 |
776
+ |--------|---------|
777
+ | `psycopg2` | `asyncpg` 或 `psycopg` (3.0+) |
778
+ | `pymysql` | `aiomysql` |
779
+ | `sqlite3` | `aiosqlite` |
780
+ | `redis-py` | `aioredis` (已集成到 redis-py 4.2+) |
781
+ | `pymongo` | `motor` |
782
+
783
+ ### Step 4: 更新函数签名
784
+
785
+ ```python
786
+ # 同步
787
+ def process_data(data):
788
+ result = database.query(data)
789
+ return result
790
+
791
+ # 异步
792
+ async def process_data(data):
793
+ result = await database.query(data)
794
+ return result
795
+ ```
796
+
797
+ ---
798
+
799
+ ## 性能对比
800
+
801
+ ### 场景: 并发请求 100 个 URL
802
+
803
+ ```python
804
+ import asyncio
805
+ import aiohttp
806
+ import requests
807
+ import time
808
+
809
+ urls = ["https://httpbin.org/delay/1" for _ in range(100)]
810
+
811
+ # 同步版本
812
+ def sync_fetch():
813
+ start = time.time()
814
+ for url in urls:
815
+ requests.get(url)
816
+ end = time.time()
817
+ print(f"Sync: {end-start:.2f}s")
818
+
819
+ # 异步版本
820
+ async def async_fetch():
821
+ start = time.time()
822
+ async with aiohttp.ClientSession() as session:
823
+ tasks = [session.get(url) for url in urls]
824
+ await asyncio.gather(*tasks)
825
+ end = time.time()
826
+ print(f"Async: {end-start:.2f}s")
827
+
828
+ # 结果:
829
+ # Sync: 105.32s (串行执行)
830
+ # Async: 2.15s (并发执行,提速 50 倍!)
831
+ ```
832
+
833
+ ---
834
+
835
+ ## 最佳实践总结
836
+
837
+ 1. **✅ 使用 Python 3.7+ 的 `asyncio.run()`**: 自动管理事件循环生命周期
838
+ 2. **✅ 优先使用高层 API**: `asyncio.gather()`, `asyncio.create_task()`
839
+ 3. **✅ 限制并发数量**: 使用 `asyncio.Semaphore` 防止资源耗尽
840
+ 4. **✅ 处理所有异常**: 使用 `try/except` 或 `return_exceptions=True`
841
+ 5. **✅ 使用异步上下文管理器**: 确保资源正确关闭
842
+ 6. **✅ 测试异步代码**: 使用 `pytest-asyncio`
843
+ 7. **✅ 避免 CPU 密集型任务**: 使用 `asyncio.to_thread()` 或多进程
844
+ 8. **✅ 使用类型提示**: 提高代码可维护性
845
+
846
+ ```python
847
+ from typing import List, Coroutine, Any
848
+
849
+ async def fetch_urls(urls: List[str]) -> List[str]:
850
+ ...
851
+ ```
852
+
853
+ ---
854
+
855
+ ## 参考资料
856
+
857
+ ### 官方文档
858
+ - [Python asyncio 文档](https://docs.python.org/3/library/asyncio.html)
859
+ - [PEP 492 -- Coroutines with async and await syntax](https://www.python.org/dev/peps/pep-0492/)
860
+
861
+ ### 推荐库
862
+ - **HTTP 客户端**: `aiohttp`, `httpx`
863
+ - **数据库**: `asyncpg`, `SQLAlchemy 2.0`, `Tortoise ORM`, `Motor`
864
+ - **Web 框架**: `FastAPI`, `Starlette`, `Sanic`, `Tornado`
865
+ - **任务队列**: `arq`, `dramatiq` (异步支持)
866
+ - **测试**: `pytest-asyncio`, `aresponses`
867
+
868
+ ### 进阶阅读
869
+ - [Async IO in Python: A Complete Walkthrough](https://realpython.com/async-io-python/)
870
+ - [FastAPI 官方文档 - Async](https://fastapi.tiangolo.com/async/)
871
+ - [SQLAlchemy 2.0 Async](https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html)
872
+
873
+ ---
874
+
875
+ ## 学习路径
876
+
877
+ ### 初级 (1-2 周)
878
+ 1. 理解事件循环和协程的基本概念
879
+ 2. 掌握 `async/await` 语法
880
+ 3. 使用 `asyncio.gather()` 并发执行任务
881
+ 4. 编写简单的异步 HTTP 客户端
882
+
883
+ ### 中级 (3-4 周)
884
+ 1. 理解 Task, Future 的区别
885
+ 2. 使用 `asyncio.Semaphore` 控制并发
886
+ 3. 掌握异步上下文管理器和异步迭代器
887
+ 4. 使用异步数据库驱动
888
+ 5. 编写 FastAPI 异步 API
889
+
890
+ ### 高级 (1-2 月)
891
+ 1. 实现自定义事件循环
892
+ 2. 编写异步中间件和装饰器
893
+ 3. 优化异步性能(连接池、批处理)
894
+ 4. 处理复杂的异步错误场景
895
+ 5. 贡献异步开源项目
896
+
897
+ ---
898
+
899
+ **文档版本**: v1.0
900
+ **最后更新**: 2026-03-28
901
+ **维护者**: UmaDev 团队
902
+ **质量评分**: 92/100