DEV Community

Cover image for SignalR core python client (VII): Azure
Andrés Baamonde Lozano
Andrés Baamonde Lozano

Posted on

2 1

SignalR core python client (VII): Azure

Intro

These days i have been working on my library, mainly on improve log. But in adition i had work on integration with azure and and serverless functions. This will be a short post, because microsoft tutorials are really good and library integration has no breaking changes. So here is a how-to use both.

Local server with Azure signalr

Here you can read a guide of how to create a signalr resource on azure. On this option you only need to stablish a connection with our local server. It will log througth azure and return a url. With that url we can connect to azure signalr. This will occur automatically, user has nothing to do. local server and library do all work. Implementation is like a normal chat. This code can be checked here

import logging

from signalrcore.hub_connection_builder import HubConnectionBuilder

# Create custom handler
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# build connection ...
hub_connection = HubConnectionBuilder() \
        .with_url(server_url, options={
            "verify_ssl": False,
            "headers": {
            }
        }) \
        .configure_logging(logging.DEBUG, socket_trace=True, handler=handler) \
        .with_automatic_reconnect({
            "type": "interval",
            "keep_alive_interval": 10,
            "intervals": [1, 3, 5, 6, 7, 87, 3]
        }).build()

Enter fullscreen mode Exit fullscreen mode

Azure functions

Other implementation choice throught azure is a serverles function. With this Tutorial you can implement. Tutorial has also a tiny web code in html/javascript, with this you can verify that your serverless function is working properly.

Client is a bit different, messages are sended with an http post instead of of sending it through the socket.

import logging
import sys
import requests
from signalrcore.hub_connection_builder import HubConnectionBuilder


def input_with_default(input_text, default_value):
    value = input(input_text.format(default_value))
    return default_value if value is None or value.strip() == "" else value


server_url = input_with_default(
    'Enter your server url(default: {0}): ',
    "localhost:7071/api")
username = input_with_default('Enter your username (default: {0}): ', "mandrewcito")
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
hub_connection = HubConnectionBuilder() \
        .with_url("ws://"+server_url, options={
            "verify_ssl": False,
            "access_token_factory": lambda: "",
            "headers": {
            }
        }) \
        .configure_logging(logging.DEBUG, socket_trace=True, handler=handler) \
        .build()

hub_connection.on_open(lambda: print("connection opened and handshake received ready to send messages"))
hub_connection.on_close(lambda: print("connection closed"))

hub_connection.on("newMessage", print)
hub_connection.start()
message = None

# Do login

while message != "exit()":
    message = input(">> ")
    if message is not None and message is not "" and message is not "exit()":
        # hub_connection.send("sendMessage", [username, message])
        requests.post("http://localhost:7071/api/messages", json={"sender": username, "text": message})

hub_connection.stop()

sys.exit(0)
Enter fullscreen mode Exit fullscreen mode

this changes will be realsed on the new version of library 0.8.4

Links

Github
Pypi

Thank you for reading, and write any thought below :D

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
wrightgd profile image
George

Is it possible to connect a locally running Python script to an Azure SignalR instance so that the Python script is just behaving as a client? If I use the Azure SignalR connection string as a server_url value, it causes errors in the requests module. Azure SignalR connection strings are in the following structure: Endpoint=https://xxx.service.signalr.net;AccessKey=yyy=;Version=1.0;

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs