Tutorial: Azure Web PubSub trigger for Azure Python Functions
Published Oct 13 2022 01:42 AM 1,322 Views
Microsoft

This step-by-step blog explains how to use Web PubSub trigger in python functions.

 

What is Azure Web Pubsub:

Web PubSub is an Azure-managed service that helps developers easily build real-time web applications using websockets and publish-subscribe pattern. Any platform supporting WebSocket APIs can connect to the service easily, e.g. web pages, mobile applications, edge devices, etc. The service manages the WebSocket connections for you and allows up to 100K *concurrent connections. It provides powerful APIs for you to manage these clients and deliver real-time messages.

 

Web PubSub v.s. SignalR:   https://learn.microsoft.com/en-us/azure/azure-web-pubsub/resource-faq#how-do-i-choose-between-azure-...

 

Azure Web PubSub trigger and bindings for Azure functions:

The illustrations of the key concepts and trigger binding definitions are documented on the public doc at https://learn.microsoft.com/en-us/azure/azure-web-pubsub/reference-functions-bindings?tabs=csharp,  together with C# and Nodejs function code samples.  This blog is a supplement to the doc by adding python samples.

 

The python sample can be found at:  https://github.com/acorn20180214/WebPubSubTriggerPythonFunction

 

Step 1:  Create an Azure Web PubSub service instance

search-web-pubsub-in-portal.png

Step 2:  Create the python function

1.  Make sure you have Azure Functions Core Tools installed. And then create an empty directory for the project. Run command under this working directory.

 

func init --worker-runtime python

 

2.  Install Microsoft.Azure.WebJobs.Extensions.WebPubSub by updating host.json's extensionBundle to version 3.3.0 or later to get Web PubSub support.

 

{
    "version": "2.0",
    "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[3.3.*, 4.0.0)"
    }
}

 

Step 3:  In this step,  we will create a WebPubSubTrigger function,  however it is not integrated in function's template so we have to use HttpTrigger to initialize the function template and change trigger type in code and configuration.

 

3.1  Create an HttpTrigger function

 

func new -n webpubsubtrigger -t HttpTrigger

 

3.2  Update webpubsubtrigger/function.json as below,  in python,  name in function.json will be used to bind the trigger object regarding the mapping table described at:  Reference - Azure Web PubSub trigger and bindings for Azure Functions | Microsoft Learn.   For example,  you can set name to "data" to retrieve message data from client without any context information.  Or,  you can set name to "request" to retrieve the complete context information of the upstream request,  as this sample did.

 

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

 

Step 4:  Write your own business logic to handle requests from server side.  Update webpubsubtrigger/__init__.py as below:

 

import json
import logging

import azure.functions as func

def main(request):
    logging.info(request)
    logging.info(json.loads(request)["connectionContext"]["userId"])
    logging.info('Python HTTP trigger function processed a request.')
    

 

Step 5:  Create/deploy the Azure Function App to cloud and enable ApplicationInsights to monitor the application telemetries.  Then configure the WebPubSubConnectionString for the function app:  

 

Find the Web PubSub resource from Azure Portal and copy out the connection string under Keys. Then, navigate to Function App settings in Azure Portal -> Settings -> Configuration. And add a new item under Application settings, with name equals WebPubSubConnectionString and value is the Web PubSub resource connection string.

conn.png

Step 6:  Configure the Web PubSub service Event Handler:

In this sample, we're using WebPubSubTrigger to listen to service upstream requests. So Web PubSub need to know the function's endpoint information in order to send target client requests. And Azure Function App requires a system key for security regarding extension-specific webhook methods. In the previous step after we deployed the Function App with message functions, we're able to get the system key.

 

6.1:   Go to Azure portal -> Find the Function App resource -> App keys -> System keys -> webpubsub_extension. Copy out the value as <APP_KEY>.

syskeys.png

 

6.2:   Go to Azure portal -> Find your Web PubSub resource -> Settings. Add a new hub settings mapping to the one function in use as below. Replace the <FUNCTIONAPP_NAME> and <APP_KEY> to yours.

Step 7:   In this step,  we will verify if the setup is working.

7.1:  Get the client URL with a temp access token

Azure portal provides a simple client URL Generator to generate a temp URL for quick test/validation purpose. Let's use this tool to get a temp Client Access URL and connect to the instance.

  • Go to Azure portal and find out the Azure Web PubSub instance.
  • Go to the Client URL Generator in Key blade.
  • Set Hub name to simplechat and User ID to alice.
  • Generate and copy the Client Access URL.

clientKeygenerator.png

 

7.2  Install WebSocket Test Client tool in Chrome browser.   Set the URL to Client Access URL we copied in the previous step.  Open the connection and send a message.

testtool.png

 

Step 8:   Go to application insights live metrics to monitor the application logging,  the first logging entry should be the user name that we specified when we create the client access URL,  a.k.a. alice.   The second logging entry should be a json string object describing the upstream request.

AI.png

 

 

Useful Links:

 

Co-Authors
Version history
Last update:
‎Oct 11 2022 10:47 PM
Updated by: