Jump to content

Tutorial: Azure Web PubSub trigger for Azure Python Functions


Recommended Posts

Guest acorn20180214
Posted

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: Azure Web PubSub service FAQ

 

 

 

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 Reference - Azure Web PubSub trigger and bindings for Azure Functions, 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: GitHub - acorn20180214/WebPubSubTriggerPythonFunction

 

 

 

Step 1: Create an Azure Web PubSub service instance

 

largevv2px999.thumb.png.e9ba122a5d2d2121795145fccf553840.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.

 

mediumvv2px400.png.8a43abe386ca004166b395a83feed560.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>.

 

largevv2px999.png.4c34c14fe1828680654429d022402bc6.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.

 

largevv2px999.png.f05f861aea33fddfcfa26bf437632925.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.

 

largevv2px999.png.804f14ead98a795ba4e6bee3cadb6a01.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.

 

largevv2px999.png.f5d9b7a2c0309e8804ad9a241e053b52.png

 

 

 

 

 

Useful Links:

 

 

Continue reading...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...