AirModel实战教程:基于PostgreSQL的异步ORM轻松上手
AirModel实战教程基于PostgreSQL的异步ORM轻松上手【免费下载链接】airThe first web framework designed for AI to write. Built on Python, FastAPI, Pydantic, and HTMX. By the authors of Two Scoops of Django.项目地址: https://gitcode.com/gh_mirrors/air23/airAirModel是GitHub加速计划air23/air项目中内置的异步ORM工具专为PostgreSQL数据库设计让开发者能够轻松实现数据模型与数据库的交互。作为首个专为AI编写的Web框架AirModel基于Python、FastAPI、Pydantic和HTMX构建提供了简洁高效的数据库操作体验。为什么选择AirModelAirModel作为一款现代化的异步ORM具有以下核心优势简单易用只需一个导入和一个基类就能定义数据模型并处理验证、序列化和异步数据库操作自动迁移添加字段后create_tables()会自动使用ALTER TABLE ADD COLUMN迁移现有表Django风格API提供create、get、filter、save、delete等直观方法类型安全基于Pydantic构建提供完整的类型注解和编辑器支持快速开始安装与配置要使用AirModel首先需要安装Air框架。通过以下命令克隆项目仓库git clone https://gitcode.com/gh_mirrors/air23/air然后安装依赖cd air uv sync配置PostgreSQL连接只需设置环境变量export DATABASE_URLpostgresql://user:passwordlocalhost/dbname?sslmoderequireAir会在应用启动时自动打开asyncpg连接池并在关闭时自动关闭连接池无需手动管理连接。定义你的第一个AirModel模型创建数据模型非常简单只需继承AirModel并定义字段from air import AirField, AirModel class UnicornSighting(AirModel): id: int AirField(primary_keyTrue) name: str location: str sparkle_rating: int sighted_at: datetime每个类型注解都会直接映射到PostgreSQL列类型Python类型PostgreSQL类型intINTEGERstrTEXTboolBOOLEANdatetimeTIMESTAMPTZfloatDOUBLE PRECISION类名会自动从CamelCase转换为snake_case作为表名符合PostgreSQL的命名习惯。基本CRUD操作AirModel提供了直观的API来执行常见的数据库操作创建记录# 创建单条记录 sighting await UnicornSighting.create( nameSparkle Hoof, locationRainbow Falls, sparkle_rating9, sighted_atdatetime.now() ) # 批量创建记录 sightings await UnicornSighting.bulk_create([ UnicornSighting(nameMoonbeam, locationStar Mountain, sparkle_rating8), UnicornSighting(nameFluffball, locationCloud Valley, sparkle_rating7) ])查询记录# 获取单条记录 sighting await UnicornSighting.get(id1) # 过滤记录 high_rated await UnicornSighting.filter(sparkle_rating__gte8) # 排序和分页 recent_sightings await UnicornSighting.filter( location__icontainsfalls ).order_by(-sighted_at).limit(10).offset(20) # 计数 count await UnicornSighting.count(sparkle_rating__gte9)更新记录sighting await UnicornSighting.get(id1) sighting.sparkle_rating 10 await sighting.save() # 批量更新 await UnicornSighting.filter(locationRainbow Falls).update(sparkle_rating9)删除记录sighting await UnicornSighting.get(id1) await sighting.delete() # 批量删除 await UnicornSighting.filter(sparkle_rating__lt5).delete()事务处理AirModel支持事务操作确保数据一致性async with app.db.transaction(): sighting1 await UnicornSighting.create(nameSunny, locationMeadow, sparkle_rating8) sighting2 await UnicornSighting.create(nameTwilight, locationForest, sparkle_rating9) # 如果发生异常所有操作都会回滚与AirForm集成AirModel可以与AirForm无缝集成实现表单验证和数据库操作的一体化from air import AirForm, AirField, AirModel class ContactMessage(AirModel): id: int AirField(primary_keyTrue) name: str AirField(..., max_length100) email: str AirField(..., formatemail) message: str AirField(..., widgettextarea) class ContactForm(AirForm[ContactMessage]): pass # 在请求处理中使用 async def handle_contact(request): form await ContactForm.from_request(request) if form.is_valid(): # 直接保存到数据库 await form.data.create() return RedirectResponse(/thanks) return TemplateResponse(contact.html, {form: form})模型迁移AirModel提供自动迁移功能当你修改模型定义后只需调用await app.db.create_tables()系统会自动为每个已导入的AirModel子类创建表并为新增字段执行ALTER TABLE ADD COLUMN操作简化开发流程。深入学习资源官方文档docs/learn/airmodel.md模型源码src/air/model/测试示例tests/test_model.py示例项目examples/src/models__AirModel__to_form.py通过本教程你已经掌握了AirModel的基本使用方法。这个强大的异步ORM工具将帮助你更高效地处理PostgreSQL数据库操作让你能够专注于业务逻辑的实现。无论是小型项目还是大型应用AirModel都能提供简洁、高效且类型安全的数据访问体验。【免费下载链接】airThe first web framework designed for AI to write. Built on Python, FastAPI, Pydantic, and HTMX. By the authors of Two Scoops of Django.项目地址: https://gitcode.com/gh_mirrors/air23/air创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考