Is there a way to use decorators to bind a route to azure WebPubSub events using azure functions using the V2 Python programming model?

428 views Asked by At

Azure functions recently changed their programming model for python as described here, https://techcommunity.microsoft.com/t5/azure-compute-blog/azure-functions-v2-python-programming-model/ba-p/3665168 and I am trying to port some code.

In v1 you use function.json to bind get the connection as an input, as well as to listen to messages from the hub.

{
"scriptFile": "__init__.py",
"bindings": [
    {
        "type": "webPubSubTrigger",
        "direction": "in",
        "name": "request",
        "hub": "simplechat",
        "eventName": "message",
        "eventType": "user"
    }
]
}

In C# and V2 for python, you should use decorators https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/azure-web-pubsub/reference-functions-bindings.md but as far as I can tell, there is no decorator for this in Python.

1

There are 1 answers

1
Suresh Chikkam On
  • I used Azure functions version(v3) and python version 3.10.9.

  • In v2 I tried using my python code but unable to reach so switched to v3 then Iam able to bind and connected. Please refer this doc for versions info

  • I used the below decorators to bind a route to Azure Web PubSub events using Azure Functions v2.

import azure.functions as func

def webpubsub_route(route: str):
    def decorator(func):
        def wrapper(req: func.WebPubSubEvent):
            return func(req)

        wrapper.route = route
        return wrapper

    return decorator

@webpubsub_route(route="myhub/mymessage")
def main(event: func.WebPubSubEvent):
    message = event.get_json()
    return func.HttpResponse(f"Received message: {message}", status_code=200)
  • webpubsub_eventdecorator logs the incoming event details and passes the event request to the main function for further processing.

enter image description here

  • Able to access the response from the hub by inputs given from userID.

enter image description here

enter image description here