Azure Durable Functions for Python 使用指南
1. 项目介绍
Azure Durable Functions for Python 是一个扩展库,允许你在无服务器计算环境中编写有状态的函数。Durable Functions 是 Azure Functions 的扩展,它让你能够定义有状态的工作流,通过编写 orchestrator 函数和有状态的实体函数来实现。这个扩展在后台管理状态、检查点和重启,让你专注于业务逻辑。
主要特性
- 有状态工作流:通过 orchestrator 函数定义复杂的工作流。
- 状态管理:自动管理函数的状态和检查点。
- 无服务器环境:在 Azure Functions 的无服务器环境中运行。
2. 项目快速启动
环境准备
- 安装 Visual Studio Code
- 安装 Azure Functions 扩展
- 安装 Azure Functions Core Tools(版本 3.0.2630 或更高)
- 安装 Python(版本 3.7 到 3.10)
创建项目
- 打开 Visual Studio Code,按
F1
打开命令面板。 - 输入并选择
Azure Functions: Create New Project
。 - 选择项目文件夹并按照提示完成项目创建。
安装依赖
在项目根目录下,编辑 requirements.txt
文件,添加以下内容:
azure-functions
azure-functions-durable
在终端中激活虚拟环境并安装依赖:
source venv/bin/activate # 根据你的操作系统调整命令
pip install -r requirements.txt
创建函数
-
Orchestrator 函数:
import azure.durable_functions as df def orchestrator_function(context: df.DurableOrchestrationContext): result1 = yield context.call_activity('Hello', 'Tokyo') result2 = yield context.call_activity('Hello', 'Seattle') result3 = yield context.call_activity('Hello', 'London') return [result1, result2, result3] main = df.Orchestrator.create(orchestrator_function)
-
Activity 函数:
def hello(name: str) -> str: return f'Hello {name}!'
-
HTTP Starter 函数:
import azure.functions as func import azure.durable_functions as df async def main(req: func.HttpRequest, starter: str) -> func.HttpResponse: client = df.DurableOrchestrationClient(starter) instance_id = await client.start_new(req.route_params['functionName'], None, None) return client.create_check_status_response(req, instance_id)
本地测试
- 按
F5
启动调试。 - 使用 HTTP 工具发送 POST 请求到
http://localhost:7071/api/orchestrators/HelloOrchestrator
。 - 查询状态 URL 以获取 orchestration 的结果。
3. 应用案例和最佳实践
应用案例
- 工作流自动化:自动化复杂的工作流,如订单处理、数据处理等。
- 长时间运行的任务:处理需要长时间运行的任务,如批处理、数据迁移等。
- 事件驱动架构:构建事件驱动的应用程序,响应外部事件并触发相应的操作。
最佳实践
- 模块化设计:将复杂的业务逻辑分解为多个小的 activity 函数,便于维护和扩展。
- 错误处理:在 orchestrator 函数中实现错误处理和重试机制,确保工作流的可靠性。
- 性能优化:合理使用检查点和状态管理,避免不必要的资源消耗。
4. 典型生态项目
Azure Functions Core Tools
- 功能:提供本地开发和测试 Azure Functions 的能力。
- 安装:通过 npm 安装,
npm install -g azure-functions-core-tools@3
。
Azure Storage
- 功能:提供持久化存储,用于保存函数的状态和检查点。
- 集成:Durable Functions 自动使用 Azure Storage 进行状态管理。
Application Insights
- 功能:提供监控和诊断功能,帮助你分析函数的性能和行为。
- 集成:通过 Azure Functions 扩展自动集成,提供详细的日志和性能指标。
通过以上步骤,你可以快速上手并开始使用 Azure Durable Functions for Python 构建有状态的无服务器应用程序。