最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Implement Python dependency injector library in Azure Functions - Stack Overflow

programmeradmin0浏览0评论

Implement Python dependency injector library in Azure Functions

Description of Issue

I am trying to implement the dependency injector for Python Azure functions.

i tried to implement it using a Python library called Dependency Injector.
pip install dependency-injector /

However, I am getting below error.

Error: "unctions.http_app_func. System.Private.CoreLib: Result: Failure Exception: AttributeError: 'dict' object has no attribute 'encode'"

This is the code I am trying to implement. Could you please have someone guide me here?

function app file name: 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)

Dependency Injector file name: 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)

Application Setting to read local.settings.json file: 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))
        

Implement Python dependency injector library in Azure Functions

Description of Issue

I am trying to implement the dependency injector for Python Azure functions.

i tried to implement it using a Python library called Dependency Injector.
pip install dependency-injector https://python-dependency-injector.ets-labs./

However, I am getting below error.

Error: "unctions.http_app_func. System.Private.CoreLib: Result: Failure Exception: AttributeError: 'dict' object has no attribute 'encode'"

This is the code I am trying to implement. Could you please have someone guide me here?

function app file name: 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)

Dependency Injector file name: 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)

Application Setting to read local.settings.json file: 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))
        
Share Improve this question edited Mar 3 at 3:30 Pravallika KV 9,1442 gold badges5 silver badges15 bronze badges Recognized by Microsoft Azure Collective asked Mar 3 at 1:40 RockRock 212 silver badges5 bronze badges 1
  • Check if the steps provided in medium/@minfysui/… helps. – Pravallika KV Commented Mar 7 at 11:12
Add a comment  | 

1 Answer 1

Reset to default 0

Use below code to implement Python dependency injector to read app settings from local.settings.json in Azure Functions, refer the blog by @MinMinRam.

Code snippet:

import json
import logging
from dependency_injector import containers, providers
import azure.functions as func

# Loading app settings from local.settings.json

def load_settings():
    with open("local.settings.json", "r") as file:
        settings = json.load(file)
    return settings["Values"]

# Create a container for dependency injection
class Container(containers.DeclarativeContainer):
    settings = providers.Singleton(load_settings)

# Service class to use injected settings

class MyService:
    def __init__(self, settings: dict):
        # Access any value from the settings here
        self.my_setting = settings.get("MySetting", "Default Value")

    def run(self):
        return f"MySetting value is: {self.my_setting}"

container = Container()

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

@app.route(route="http_trigger")
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    my_service = MyService(container.settings())
    result = my_service.run()

    return func.HttpResponse(f"Result: {result}", status_code=200)

requirements.txt:

azure-functions
dependency-injector

Run the function locally :

Console output:

[2025-03-14T08:27:12.958Z] Worker process started and initialized.

Functions:

        http_trigger:  http://localhost:7071/api/http_trigger

For detailed output, run func with --verbose flag.
[2025-03-14T08:27:17.176Z] Executing 'Functions.http_trigger' (Reason='This function was programmatically called via the host APIs.', Id=0b4c0e56-9ec0-4d8b-91e1-452959c92902)
[2025-03-14T08:27:17.241Z] Python HTTP trigger function processed a request.
[2025-03-14T08:27:17.294Z] Executed 'Functions.http_trigger' (Succeeded, Id=0b4c0e56-9ec0-4d8b-91e1-452959c92902, Duration=145ms)

发布评论

评论列表(0)

  1. 暂无评论