在Azure Functions中实现Python依赖注入库遇错求助
问题:Python Azure Functions中使用Dependency Injector库出现AttributeError错误
在Python Azure Functions中实现依赖注入,选用Dependency Injector库(安装命令:pip install dependency-injector),运行时遇到如下错误:
Error: "unctions.http_app_func. System.Private.CoreLib: Result: Failure
Exception: AttributeError: 'dict' object has no attribute 'encode'"
相关实现代码如下:
function_app.py
import azure.functions as func from fastapi import FastAPI, Depends, Request, Response from dependency_injector.wiring import inject, Provide from abstraction.di_container import DIContainer import logging import json from src.config.app_settings import AppSettings container = DIContainer() container.wire(modules=[__name__]) fast_app = FastAPI() @fast_app.exception_handler(Exception) async def handle_exception(request: Request, exc: Exception): return Response( status_code=400, content={"message": str(exc)}, ) @fast_app.get("/") @inject async def home(settings: AppSettings = Depends(Provide[DIContainer.app_config])): cont_name = settings.get("ContainerName", "No setting found") return { "info": f"Try to get values from local.settings using DI {cont_name}" } @fast_app.get("/v1/test/{test}") async def get_test(self, test: str): return { "test": test } app = func.AsgiFunctionApp(app=fast_app, http_auth_level=func.AuthLevel.ANONYMOUS)
di_container.py
from dependency_injector import containers, providers from src.config.app_settings import AppSettings class DIContainer(containers.DeclarativeContainer): app_config = providers.Singleton(AppSettings)
app_settings.py
import json import os from dependency_injector import containers, providers class AppSettings: def __init__(self, file_path="local.settings.json"): self.config_data = {} if os.path.exists(file_path): with open(file_path, "r", encoding="utf-8") as file: data = json.load(file) self.config_data = data.get("Values", {}) def get(self, key: str, default=None): return os.getenv(key,self.config_data.get(key, default))
解决方案
错误原因分析
- Response对象使用错误:FastAPI的
Response类直接接收dict类型的content时,会尝试调用encode方法编码,但字典没有该方法,触发AttributeError。 - 路径函数参数冗余:
get_test函数中的self参数多余,FastAPI普通路径操作函数无需该参数,会导致请求参数不匹配。
修改步骤
- 修正异常处理器的Response返回:将字典内容序列化为JSON字符串,并指定
media_type为application/json。 - 移除冗余的self参数:删除
get_test函数中的self参数。
修改后的关键代码片段
# 修正异常处理器 @fast_app.exception_handler(Exception) async def handle_exception(request: Request, exc: Exception): return Response( status_code=400, content=json.dumps({"message": str(exc)}), media_type="application/json" ) # 修正get_test函数 @fast_app.get("/v1/test/{test}") async def get_test(test: str): return { "test": test }
验证说明
修改后,依赖注入逻辑保持不变,AppSettings的读取和DIContainer的配置无需调整。运行Azure Functions后,访问相关接口即可正常返回JSON响应,不再触发AttributeError。
内容的提问来源于stack exchange,提问作者Rock
相关产品推荐
相关产品推荐

