Rock
Rock

Reputation: 21

Implement Python dependency injector library in Azure Functions

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.org/

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))
        

Upvotes: 0

Views: 29

Answers (0)

Related Questions