Я разработчик .net, недавно начал использовать Python. Я пытаюсь создать функцию Azure v2 с использованием Python и ищу помощь о том, как внедрить зависимости в мою функцию. Я рассмотрел различные примеры внедрения зависимостей Python и в целом смог это сделать. Но я не мог понять, где вызвать загрузку.
В .net это можно сделать, просто расширив класс FunctionStarup, я не могу найти такую вещь в пакете Python azure-functions. В документации Microsoft также ничего не упоминается о внедрении зависимостей в руководстве по программированию функции Python v2. Руководство разработчика Python для функции Azure v2.
Это частичный фрагмент кода примера I попробовал, но не получилось. В примере ниже я использовал kink для DI
Класс, который я пытаюсь внедрить
Код: Выделить всё
class IocService:
def __init__(self, message: str):
self.message = message
def say_hello(self, name: str) -> str:
return f"{self.message}, {name}!"
Код: Выделить всё
from kink import inject
import logging
from IocService import IocService
import azure.functions as func
bp = func.Blueprint()
@inject
@bp.route(route="default_template")
def default_template(req: func.HttpRequest, context: func.Context, service: IocService) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
#ioc_service = context.get_service(IocService)
name = req.params.get('name')
if not name:
try:
req_body = req.get_json()
except ValueError:
pass
else:
name = req_body.get('name')
if name:
return func.HttpResponse(
f"Hello, {name}. This HTTP-triggered function "
f"executed successfully.")
else:
return func.HttpResponse(
"This HTTP-triggered function executed successfully. "
"Pass a name in the query string or in the request body for a"
" personalized response.",
status_code=200
)
Код: Выделить всё
import azure.functions as func
from http_blueprint import bp
from bootstrap import start_up
print("before start up")
start_up()
print("After start up")
app = func.FunctionApp()
app.register_functions(bp)
Код: Выделить всё
> File "\function_app.py", line 2, in
> from http_blueprint import bp File "\http_blueprint.py", line 9, in
> @inject
> ^^^^^^ File "\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kink\inject.py",
> line 203, in inject
> return _decorator(_service)
> ^^^^^^^^^^^^^^^^^^^^ File "\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kink\inject.py",
> line 193, in _decorator
> service_function = _decorate(bind or {}, _service, container)
> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File
> "\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\kink\inject.py",
> line 105, in _decorate
> service in [ABC.__init__, _no_init] or service.__name__ == "_no_init"
>
>
When i run the function by removing injection from httptrigger method, the logs are showing very interesting things:
- It printed the logs in the function
- Then printed the logs in function_app.py
Источник: https://stackoverflow.com/questions/774 ... -python-v2