moai-lang-python
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseQuick Reference (30 seconds)
快速参考(30秒)
Python 3.13+ Development Specialist - FastAPI, Django, async patterns, pytest, and modern Python features.
Auto-Triggers: Python files with .py extension, pyproject.toml, requirements.txt, pytest.ini, FastAPI or Django discussions
Core Capabilities:
- Python 3.13 Features: JIT compiler via PEP 744, GIL-free mode via PEP 703, pattern matching with match and case statements
- Web Frameworks: FastAPI 0.115 and later, Django 5.2 LTS
- Data Validation: Pydantic v2.9 with model_validate patterns
- ORM: SQLAlchemy 2.0 async patterns
- Testing: pytest with fixtures, async testing, parametrize decorators
- Package Management: poetry, uv, pip with pyproject.toml
- Type Hints: Protocol, TypeVar, ParamSpec, and modern typing patterns
- Async: asyncio, async generators, and task groups
- Data Science: numpy, pandas, and polars basics
Python 3.13+开发专家 - 涵盖FastAPI、Django、异步模式、pytest及现代Python特性。
自动触发场景:.py后缀的Python文件、pyproject.toml、requirements.txt、pytest.ini,以及FastAPI或Django相关讨论
核心能力:
- Python 3.13特性:通过PEP 744实现的JIT编译器、通过PEP 703实现的无GIL模式、使用match和case语句的模式匹配
- Web框架:FastAPI 0.115及以上版本、Django 5.2 LTS
- 数据验证:Pydantic v2.9及model_validate模式
- ORM:SQLAlchemy 2.0异步模式
- 测试:pytest及fixtures、异步测试、parametrize装饰器
- 包管理:poetry、uv、搭配pyproject.toml的pip
- 类型提示:Protocol、TypeVar、ParamSpec及现代类型标注模式
- 异步编程:asyncio、异步生成器及任务组
- 数据科学:numpy、pandas及polars基础
Quick Patterns
快速实现模式
FastAPI Endpoint Pattern:
Import FastAPI and Depends from fastapi, and BaseModel from pydantic. Create a FastAPI application instance. Define a UserCreate model class inheriting from BaseModel with name and email string fields. Create an async post endpoint at the users path that accepts a UserCreate parameter and returns a User by calling UserService.create with await.
Pydantic v2.9 Validation Pattern:
Import BaseModel and ConfigDict from pydantic. Define a User class inheriting from BaseModel. Set model_config using ConfigDict with from_attributes set to True and str_strip_whitespace set to True. Add id as integer, name as string, and email as string fields. Use model_validate to create from ORM objects and model_validate_json to create from JSON data.
pytest Async Test Pattern:
Import pytest and mark the test function with pytest.mark.asyncio decorator. Create an async test function that takes async_client as a fixture parameter. Send a post request to the users endpoint with a JSON body containing a name field. Assert that the response status_code equals 201.
FastAPI端点模式:
从fastapi导入FastAPI和Depends,从pydantic导入BaseModel。创建FastAPI应用实例。定义继承自BaseModel的UserCreate模型类,包含name和email字符串字段。在/users路径创建异步post端点,接收UserCreate参数,通过await调用UserService.create并返回User对象。
Pydantic v2.9验证模式:
从pydantic导入BaseModel和ConfigDict。定义继承自BaseModel的User类。使用ConfigDict设置model_config,将from_attributes设为True、str_strip_whitespace设为True。添加id(整数类型)、name(字符串类型)、email(字符串类型)字段。使用model_validate从ORM对象创建实例,使用model_validate_json从JSON数据创建实例。
pytest异步测试模式:
导入pytest,使用pytest.mark.asyncio装饰器标记测试函数。创建异步测试函数,接收async_client作为fixture参数。向/users端点发送包含name字段的JSON post请求。断言响应status_code等于201。
Implementation Guide (5 minutes)
实现指南(5分钟)
Python 3.13 New Features
Python 3.13新特性
JIT Compiler via PEP 744:
- Experimental feature disabled by default
- Enable using the PYTHON_JIT environment variable set to 1
- Build option available as enable-experimental-jit flag
- Provides performance improvements for CPU-bound code
- Uses copy-and-patch JIT that translates specialized bytecode to machine code
GIL-Free Mode via PEP 703:
- Experimental free-threaded build available as python3.13t
- Allows true parallel thread execution
- Available in official Windows and macOS installers
- Best suited for CPU-intensive multi-threaded applications
- Not recommended for production use yet
Pattern Matching with match and case:
Create a process_response function that takes a response dictionary and returns a string. Use match statement on response. For case with status ok and data field, return success message with the data. For case with status error and message field, return error message. For case with status matching pending or processing using a guard condition, return in progress message. For default case using underscore, return unknown response.
通过PEP 744实现的JIT编译器:
- 实验性特性,默认禁用
- 通过设置环境变量PYTHON_JIT=1启用
- 构建时可使用enable-experimental-jit标志开启
- 为CPU密集型代码提供性能提升
- 使用复制-补丁JIT将专用字节码转换为机器码
通过PEP 703实现的无GIL模式:
- 实验性自由线程构建版本为python3.13t
- 支持真正的并行线程执行
- 官方Windows和macOS安装包中提供
- 最适合CPU密集型多线程应用
- 暂不推荐用于生产环境
使用match和case的模式匹配:
创建process_response函数,接收response字典并返回字符串。对response使用match语句。当status为ok且包含data字段时,返回带data的成功消息;当status为error且包含message字段时,返回错误消息;当status匹配pending或processing(使用守卫条件)时,返回处理中消息;默认情况(使用下划线)返回未知响应。
FastAPI 0.115+ Patterns
FastAPI 0.115+模式
Async Dependency Injection:
Import FastAPI, Depends from fastapi, AsyncSession from sqlalchemy.ext.asyncio, and asynccontextmanager from contextlib. Create a lifespan async context manager decorated with asynccontextmanager that takes the FastAPI app. In the lifespan, call await init_db for startup, yield, then call await cleanup for shutdown. Create the FastAPI app with the lifespan parameter. Define an async get_db function returning AsyncGenerator of AsyncSession that uses async with on async_session and yields the session. Create a get endpoint for users with user_id path parameter, using Depends with get_db to inject the database session. Call await get_user_by_id and return UserResponse.model_validate with the user.
Class-Based Dependencies:
Create a Paginator class with an init method accepting page defaulting to 1 and size defaulting to 20. Set self.page to max of 1 and page, self.size to min of 100 and max of 1 and size, and self.offset to page minus 1 multiplied by size. Create a list_items endpoint using Depends on Paginator to inject pagination and return items using get_page with offset and size.
异步依赖注入:
从fastapi导入FastAPI、Depends,从sqlalchemy.ext.asyncio导入AsyncSession,从contextlib导入asynccontextmanager。创建带asynccontextmanager装饰器的lifespan异步上下文管理器,接收FastAPI app。在lifespan中,启动时调用await init_db,yield,然后关闭时调用await cleanup。使用lifespan参数创建FastAPI应用。定义返回AsyncGenerator[AsyncSession]的异步get_db函数,使用async with async_session并yield会话。创建带user_id路径参数的/users get端点,使用Depends(get_db)注入数据库会话。调用await get_user_by_id并返回UserResponse.model_validate(user)。
基于类的依赖:
创建Paginator类,其init方法接收默认值为1的page和默认值为20的size。设置self.page为1和page的最大值,self.size为1和size的最大值与100的最小值,self.offset为(page-1)*size。创建使用Depends(Paginator)注入分页的list_items端点,使用offset和size调用get_page并返回结果。
Django 5.2 LTS Features
Django 5.2 LTS特性
Composite Primary Keys:
Create an OrderItem model with ForeignKey to Order with CASCADE deletion, ForeignKey to Product with CASCADE deletion, and an IntegerField for quantity. In the Meta class, set pk to models.CompositePrimaryKey with order and product fields.
URL Reverse with Query Parameters:
Import reverse from django.urls. Call reverse with the search view name, query dictionary containing q set to django and page set to 1, and fragment set to results. The result is the search path with query string and fragment.
Automatic Model Imports in Shell:
Run python manage.py shell and models from all installed apps are automatically imported without explicit import statements.
复合主键:
创建OrderItem模型,包含指向Order的ForeignKey(级联删除)、指向Product的ForeignKey(级联删除),以及IntegerField类型的quantity。在Meta类中,设置pk为models.CompositePrimaryKey,包含order和product字段。
带查询参数的URL反向解析:
从django.urls导入reverse。调用reverse,传入搜索视图名称、包含q=django和page=1的查询字典,以及fragment=results。返回结果为带查询字符串和片段的搜索路径。
Shell中的自动模型导入:
运行python manage.py shell,所有已安装应用的模型会自动导入,无需显式导入语句。
Pydantic v2.9 Deep Patterns
Pydantic v2.9深度模式
Reusable Validators with Annotated:
Import Annotated from typing and AfterValidator and BaseModel from pydantic. Define a validate_positive function that takes an integer v and returns an integer. If v is less than or equal to 0, raise ValueError with must be positive message. Otherwise return v. Create PositiveInt as Annotated with int and AfterValidator using validate_positive. Use PositiveInt in model fields for price and quantity.
Model Validator for Cross-Field Validation:
Import BaseModel and model_validator from pydantic, and Self from typing. Create a DateRange model with start_date and end_date as date fields. Add a model_validator decorator with mode set to after. In the validate_dates method returning Self, check if end_date is before start_date and raise ValueError if so, otherwise return self.
ConfigDict Best Practices:
Create a BaseSchema model with model_config set to ConfigDict. Set from_attributes to True for ORM object support, populate_by_name to True to allow aliases, extra to forbid to fail on unknown fields, and str_strip_whitespace to True to clean strings.
使用Annotated的可复用验证器:
从typing导入Annotated,从pydantic导入AfterValidator和BaseModel。定义validate_positive函数,接收整数v并返回整数。如果v<=0,抛出ValueError(消息为must be positive),否则返回v。创建PositiveInt为Annotated[int, AfterValidator(validate_positive)]。在模型字段price和quantity中使用PositiveInt。
用于跨字段验证的模型验证器:
从pydantic导入BaseModel和model_validator,从typing导入Self。创建DateRange模型,包含start_date和end_date日期字段。添加mode设为after的model_validator装饰器。在返回Self的validate_dates方法中,检查end_date是否早于start_date,若是则抛出ValueError,否则返回self。
ConfigDict最佳实践:
创建BaseSchema模型,设置model_config为ConfigDict。设置from_attributes=True以支持ORM对象,populate_by_name=True以允许别名,extra=forbid以在出现未知字段时抛出错误,str_strip_whitespace=True以清理字符串。
SQLAlchemy 2.0 Async Patterns
SQLAlchemy 2.0异步模式
Engine and Session Setup:
Import create_async_engine, async_sessionmaker, and AsyncSession from sqlalchemy.ext.asyncio. Create engine using create_async_engine with the postgresql+asyncpg connection string, pool_pre_ping set to True, and echo set to True. Create async_session using async_sessionmaker with the engine, class_ set to AsyncSession, and expire_on_commit set to False to prevent detached instance errors.
Repository Pattern:
Create a UserRepository class with an init method taking an AsyncSession. Define an async get_by_id method that executes a select query with a where clause for user_id, returning scalar_one_or_none result. Define an async create method that creates a User from UserCreate model_dump, adds to session, commits, refreshes, and returns the user.
Streaming Large Results:
Create an async stream_users function that takes an AsyncSession. Call await db.stream with the select User query. Use async for to iterate over result.scalars and yield each user.
引擎和会话设置:
从sqlalchemy.ext.asyncio导入create_async_engine、async_sessionmaker和AsyncSession。使用create_async_engine创建引擎,传入postgresql+asyncpg连接字符串,设置pool_pre_ping=True、echo=True。使用async_sessionmaker创建async_session,传入engine,设置class_=AsyncSession、expire_on_commit=False以避免分离实例错误。
仓库模式:
创建UserRepository类,其init方法接收AsyncSession。定义异步get_by_id方法,执行带user_id条件的select查询,返回scalar_one_or_none结果。定义异步create方法,从UserCreate.model_dump创建User,添加到会话,提交,刷新并返回用户。
流式返回大结果:
创建接收AsyncSession的异步stream_users函数。调用await db.stream(select(User))查询。使用async for遍历result.scalars并逐个yield用户。
pytest Advanced Patterns
pytest高级模式
Async Fixtures with pytest-asyncio:
Import pytest, pytest_asyncio, and AsyncClient from httpx. Decorate fixtures with pytest_asyncio.fixture. Create an async_client fixture that uses async with on AsyncClient with app and base_url, yielding the client. Create a db_session fixture that uses async with on async_session and session.begin, yielding session and calling await session.rollback.
Parametrized Tests:
Use pytest.mark.parametrize decorator with input_data and expected_status parameter names. Provide test cases as tuples with dictionaries and expected status codes. Add ids for valid, empty_name, and missing_name cases. The test function takes async_client, input_data, and expected_status, posts to users endpoint, and asserts status_code matches expected.
Fixture Factories:
Create a user_factory fixture that returns an async function. The inner function takes db as AsyncSession and keyword arguments. Set defaults dictionary with name and email. Create User with defaults merged with kwargs using the pipe operator, add to db, commit, and return user.
使用pytest-asyncio的异步Fixture:
导入pytest、pytest_asyncio和httpx.AsyncClient。用pytest_asyncio.fixture装饰fixture。创建async_client fixture,使用async with AsyncClient(app=app, base_url=...)并yield client。创建db_session fixture,使用async with async_session和session.begin,yield session并调用await session.rollback。
参数化测试:
使用pytest.mark.parametrize装饰器,参数名为input_data和expected_status。提供测试用例为元组,包含字典和预期状态码。为valid、empty_name、missing_name案例添加ids。测试函数接收async_client、input_data、expected_status,向/users端点发送post请求,断言status_code与预期匹配。
Fixture工厂:
创建user_factory fixture,返回异步函数。内部函数接收db(AsyncSession)和关键字参数。设置包含name和email的defaults字典。使用管道操作符合并defaults与kwargs创建User,添加到db,提交并返回用户。
Type Hints Modern Patterns
现代类型提示模式
Protocol for Structural Typing:
Import Protocol and runtime_checkable from typing. Apply runtime_checkable decorator. Define a Repository Protocol with generic type T. Add abstract async get method taking int id returning T or None, async create method taking dict data returning T, and async delete method taking int id returning bool.
ParamSpec for Decorators:
Import ParamSpec, TypeVar, and Callable from typing, and wraps from functools. Define P as ParamSpec and R as TypeVar. Create a retry decorator function taking times defaulting to 3 that returns a callable wrapper. The inner decorator wraps the function and the wrapper iterates for the specified times, trying to await the function and re-raising on the last attempt.
用于结构类型的Protocol:
从typing导入Protocol和runtime_checkable。应用runtime_checkable装饰器。定义带泛型类型T的Repository Protocol。添加抽象异步get方法(接收int id,返回T或None)、抽象异步create方法(接收dict data,返回T)、抽象异步delete方法(接收int id,返回bool)。
用于装饰器的ParamSpec:
从typing导入ParamSpec、TypeVar和Callable,从functools导入wraps。定义P为ParamSpec,R为TypeVar。创建retry装饰器函数,接收默认值为3的times,返回可调用的wrapper。内部装饰器包装函数,wrapper迭代指定次数,尝试await函数,最后一次尝试失败时重新抛出异常。
Package Management
包管理
pyproject.toml with Poetry:
In the tool.poetry section, set name, version, and python version constraint. Under dependencies, add fastapi, pydantic, and sqlalchemy with asyncio extra. Under dev dependencies, add pytest, pytest-asyncio, and ruff. Configure ruff with line-length and target-version. Set pytest asyncio_mode to auto in ini_options.
uv Fast Package Manager:
Install uv using curl with the install script from astral.sh. Create virtual environment with uv venv. Install dependencies with uv pip install from requirements.txt. Add dependencies with uv add command.
使用Poetry的pyproject.toml:
在tool.poetry部分,设置name、version和Python版本约束。在dependencies下添加fastapi、pydantic和带asyncio扩展的sqlalchemy。在dev-dependencies下添加pytest、pytest-asyncio和ruff。配置ruff的line-length和target-version。在ini_options中设置pytest的asyncio_mode为auto。
uv快速包管理器:
使用curl从astral.sh的安装脚本安装uv。使用uv venv创建虚拟环境。使用uv pip install -r requirements.txt安装依赖。使用uv add命令添加依赖。
Advanced Implementation (10+ minutes)
高级实现(10+分钟)
For comprehensive coverage including:
- Production deployment patterns for Docker and Kubernetes
- Advanced async patterns including task groups and semaphores
- Data science integration with numpy, pandas, and polars
- Performance optimization techniques
- Security best practices following OWASP patterns
- CI/CD integration patterns
See:
- reference.md for complete reference documentation
- examples.md for production-ready code examples
如需以下内容的全面覆盖:
- Docker和Kubernetes的生产部署模式
- 高级异步模式,包括任务组和信号量
- 与numpy、pandas、polars的数据科学集成
- 性能优化技巧
- 遵循OWASP模式的安全最佳实践
- CI/CD集成模式
请查看:
- reference.md:完整参考文档
- examples.md:生产就绪代码示例
Context7 Library Mappings
Context7库映射
- tiangolo/fastapi for FastAPI async web framework
- django/django for Django web framework
- pydantic/pydantic for data validation with type annotations
- sqlalchemy/sqlalchemy for SQL toolkit and ORM
- pytest-dev/pytest for testing framework
- numpy/numpy for numerical computing
- pandas-dev/pandas for data analysis library
- pola-rs/polars for fast DataFrame library
- tiangolo/fastapi:FastAPI异步Web框架
- django/django:Django Web框架
- pydantic/pydantic:带类型注解的数据验证
- sqlalchemy/sqlalchemy:SQL工具包和ORM
- pytest-dev/pytest:测试框架
- numpy/numpy:数值计算
- pandas-dev/pandas:数据分析库
- pola-rs/polars:快速DataFrame库
Works Well With
协同工具
- moai-domain-backend for REST API and microservices architecture
- moai-domain-database for SQL patterns and ORM optimization
- moai-workflow-testing for DDD and testing strategies
- moai-essentials-debug for AI-powered debugging
- moai-foundation-quality for TRUST 5 quality principles
- moai-domain-backend:REST API和微服务架构
- moai-domain-database:SQL模式和ORM优化
- moai-workflow-testing:领域驱动设计(DDD)和测试策略
- moai-essentials-debug:AI驱动的调试
- moai-foundation-quality:TRUST 5质量原则
Troubleshooting
故障排除
Common Issues:
Python Version Check:
Run python with version flag to verify 3.13 or later. Use python with -c flag to print sys.version_info for detailed version information.
Async Session Detached Error:
Set expire_on_commit to False in session configuration. Alternatively, use await session.refresh with the object after commit.
pytest asyncio Mode Warning:
In pyproject.toml under tool.pytest.ini_options, set asyncio_mode to auto and asyncio_default_fixture_loop_scope to function.
Pydantic v2 Migration:
The parse_obj method is now model_validate. The parse_raw method is now model_validate_json. The from_orm functionality requires from_attributes set to True in ConfigDict.
Last Updated: 2026-01-11
Status: Active (v1.1.0)
常见问题:
Python版本检查:
运行python --version验证版本为3.13或更高。使用python -c "import sys; print(sys.version_info)"查看详细版本信息。
异步会话分离错误:
在会话配置中设置expire_on_commit=False。或者,提交后使用await session.refresh(object)。
pytest asyncio模式警告:
在pyproject.toml的tool.pytest.ini_options下,设置asyncio_mode=auto和asyncio_default_fixture_loop_scope=function。
Pydantic v2迁移:
原parse_obj方法现在为model_validate。原parse_raw方法现在为model_validate_json。from_orm功能需要在ConfigDict中设置from_attributes=True。
最后更新:2026-01-11
状态:活跃(v1.1.0)