Air与FastAPI深度集成:构建异步Web应用的完整指南
【免费下载链接】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
Air是一个专为AI编写设计的Web框架,基于Python、FastAPI、Pydantic和HTMX构建。作为FastAPI的直接衍生项目,Air不仅继承了FastAPI的高性能和异步特性,还提供了更简洁的API和HTML优先的开发体验。本文将详细介绍如何利用Air与FastAPI的深度集成,快速构建功能强大的异步Web应用。
为什么选择Air与FastAPI集成?
Air采用组合模式,在内部封装了FastAPI实例,既提供了专注于HTML应用的简洁API,又充分利用了FastAPI的强大工具集。这种设计带来了多重优势:
- 零学习成本:熟悉FastAPI的开发者可以无缝迁移到Air
- 性能优化:继承FastAPI的异步性能优势,处理高并发请求更高效
- 部署灵活性:支持以FastAPI应用形式部署,兼容所有FastAPI支持的平台
- 扩展能力:可直接访问底层FastAPI实例,实现高级功能定制
快速上手:从FastAPI到Air的平滑过渡
安装与环境配置
首先,通过以下命令克隆Air项目仓库:
git clone https://gitcode.com/gh_mirrors/air23/air cd airAir使用uv作为依赖管理工具,安装项目依赖:
uv install创建第一个Air应用
Air应用的基本结构与FastAPI类似,但提供了更简洁的API。以下是一个简单的"Hello World"示例:
import air app = air.Air() @app.get("/") def index() -> air.H1: return air.H1("Hello, World!")这个示例展示了Air的核心特性:无需手动创建响应对象,直接返回HTML元素即可。Air会自动处理请求并生成适当的响应。
深入集成:Air与FastAPI的核心连接点
Air应用的内部结构
Air的核心类Air通过组合模式封装了FastAPI实例,这一点可以在src/air/applications.py中看到:
class Air(RouterMixin): """Air web framework - HTML-first web apps powered by FastAPI. Air uses composition, wrapping a FastAPI instance internally. This provides a clean, focused API for HTML applications while leveraging FastAPI's toolkit. """ def __init__(self, ...): # 创建内部FastAPI实例 if fastapi_app is None: self._app = FastAPI( debug=debug, routes=routes, servers=servers, dependencies=dependencies, default_response_class=AirResponse, # 其他参数... ) else: self._app = fastapi_app访问底层FastAPI实例
对于需要FastAPI特定功能的场景,Air提供了直接访问底层FastAPI实例的途径:
# 访问底层FastAPI应用 @app.fastapi_app.get("/api/users", response_model=list[User]) async def api_get_users(): return users这个特性允许开发者在同一个应用中混合使用Air的HTML优先开发模式和FastAPI的API开发能力,非常适合构建同时需要网页界面和API接口的应用。
高级配置:定制FastAPI实例
Air允许在初始化时传入自定义的FastAPI实例,以满足高级配置需求。例如,启用OpenAPI文档功能:
import air from fastapi import FastAPI # 创建自定义FastAPI实例 fastapi_app = FastAPI( default_response_class=air.AirResponse, docs_url="/docs", redoc_url="/redoc" ) # 将自定义FastAPI实例传递给Air app = air.Air(fastapi_app=fastapi_app) @app.page def index(): "项目首页" return air.H1('Hello, Air!')通过这种方式,开发者可以充分利用FastAPI的所有配置选项,同时享受Air提供的便捷功能。
部署策略:以FastAPI应用形式运行Air
Air应用可以直接作为FastAPI应用运行和部署,这为部署提供了极大的灵活性。只需在pyproject.toml中配置FastAPI入口点:
[tool.fastapi] entrypoint = "main:app"现在,你可以使用FastAPI的命令行工具运行Air应用:
fastapi dev这种部署方式使得Air应用可以无缝部署到任何支持FastAPI的平台,如fastapicloud.com等。
实际案例:构建混合应用
结合Air和FastAPI的优势,我们可以构建一个既有美观网页界面,又有强大API的混合应用。以下是一个简单的待办事项应用示例:
import air from pydantic import BaseModel from typing import List, Optional # 数据模型 class TodoItem(BaseModel): id: int title: str completed: bool = False # 内存数据库 todos: List[TodoItem] = [] next_id = 1 # 创建Air应用 app = air.Air() # Web页面 - 使用Air @app.page("/") def todo_page(): return air.Div( air.H1("待办事项"), air.Form( air.Input(type="text", name="title", placeholder="添加新任务"), air.Button("添加"), action="/api/todos", method="post" ), air.Ul([ air.Li( air.Input(type="checkbox", checked=item.completed), item.title, air.A("删除", href=f"/api/todos/{item.id}", method="delete") ) for item in todos ]) ) # API端点 - 使用底层FastAPI @app.fastapi_app.post("/api/todos", response_model=TodoItem) async def add_todo(title: str): global next_id todo = TodoItem(id=next_id, title=title) todos.append(todo) next_id += 1 return todo @app.fastapi_app.delete("/api/todos/{todo_id}") async def delete_todo(todo_id: int): global todos todos = [t for t in todos if t.id != todo_id] return {"status": "success"}这个示例展示了如何在同一个应用中结合Air的HTML渲染能力和FastAPI的API开发能力,创建功能完整的Web应用。
最佳实践与性能优化
利用FastAPI的依赖注入系统
Air完全支持FastAPI的依赖注入系统,可以在路由函数中直接使用依赖:
from fastapi import Depends async def get_db(): db = DatabaseConnection() try: yield db finally: await db.close() @app.get("/items") async def get_items(db = Depends(get_db)): return await db.fetch_all("SELECT * FROM items")异步处理与性能优化
Air继承了FastAPI的异步特性,建议在处理I/O密集型操作时使用异步函数:
@app.get("/data") async def get_data(): # 异步数据库查询 data = await db.fetch_data() # 异步HTTP请求 external_data = await http_client.get("https://api.example.com/data") return air.Div( air.H2("数据展示"), air.Pre(str(data)), air.Pre(str(external_data.json())) )总结:Air与FastAPI集成的强大之处
Air与FastAPI的深度集成提供了一种全新的Web开发体验,既保留了FastAPI的高性能和强大功能,又简化了HTML应用的开发流程。通过本文介绍的方法,开发者可以:
- 快速构建HTML优先的Web应用
- 无缝集成API端点
- 利用FastAPI的生态系统和部署选项
- 享受异步编程带来的性能优势
无论是构建简单的静态网站,还是复杂的Web应用,Air与FastAPI的组合都能提供高效、灵活的开发体验。通过docs/learn/cookbook/running_as_fastapi.md等官方文档,你可以进一步探索更多高级用法和最佳实践。
开始使用Air与FastAPI构建你的下一个Web应用,体验这种革命性的开发方式吧!
【免费下载链接】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),仅供参考