Skip to main content

Modern, reliable and async-ready client for SignalR protocol

Project description

pysignalr

GitHub stars Latest stable release PyPI - Python Version License: MIT
PyPI monthly downloads GitHub issues GitHub pull requests

pysignalr is a modern, reliable, and async-ready client for the SignalR protocol. This project started as an asyncio fork of mandrewcito's signalrcore library and ended up as a complete rewrite.

Table of Contents

  1. Installation
  2. Basic Usage
  3. Usage with Token Authentication
  4. API Reference
  5. License

Installation

To install pysignalr, simply use pip:

pip install pysignalr

Basic Usage

Let's connect to TzKT, an API and block explorer of Tezos blockchain, and subscribe to all operations:

import asyncio
from contextlib import suppress
from typing import Any
from typing import Dict
from typing import List

from pysignalr.client import SignalRClient
from pysignalr.messages import CompletionMessage

async def on_open() -> None:
    print('Connected to the server')

async def on_close() -> None:
    print('Disconnected from the server')

async def on_message(message: List[Dict[str, Any]]) -> None:
    print(f'Received message: {message}')

async def on_client_result(message: list[dict[str, Any]]) -> str:
    """
    The server can request a result from a client.
    This requires the server to use ISingleClientProxy.InvokeAsync and the client to return a result from its .On handler.
    https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-9.0#client-results
    """
    print(f'Received message: {message}')
    return 'reply'

async def on_error(message: CompletionMessage) -> None:
    print(f'Received error: {message.error}')

async def main() -> None:
    client = SignalRClient('https://api.tzkt.io/v1/ws')

    client.on_open(on_open)
    client.on_close(on_close)
    client.on_error(on_error)
    client.on('operations', on_message)
    client.on('client_result', on_client_result)

    await asyncio.gather(
        client.run(),
        client.send('SubscribeToOperations', [{}]),
    )


with suppress(KeyboardInterrupt, asyncio.CancelledError):
    asyncio.run(main())

Usage with Token Authentication

To connect to the SignalR server using token authentication:

import asyncio
from contextlib import suppress
from typing import Any, Dict, List

from pysignalr.client import SignalRClient
from pysignalr.messages import CompletionMessage

async def on_open() -> None:
    print('Connected to the server')

async def on_close() -> None:
    print('Disconnected from the server')

async def on_message(message: List[Dict[str, Any]]) -> None:
    print(f'Received message: {message}')
    
async def on_client_result(message: list[dict[str, Any]]) -> str:
    """
    The server can request a result from a client.
    This requires the server to use ISingleClientProxy.InvokeAsync and the client to return a result from its .On handler.
    https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-9.0#client-results
    """
    print(f'Received message: {message}')
    return 'reply'

async def on_error(message: CompletionMessage) -> None:
    print(f'Received error: {message.error}')

def token_factory() -> str:
    # Replace with logic to fetch or generate the token
    return "your_access_token_here"

async def main() -> None:
    client = SignalRClient(
        url='https://api.tzkt.io/v1/ws',
        access_token_factory=token_factory,
        headers={"mycustomheader": "mycustomheadervalue"},
    )

    client.on_open(on_open)
    client.on_close(on_close)
    client.on_error(on_error)
    client.on('operations', on_message)
    client.on('client_result', on_client_result)

    await asyncio.gather(
        client.run(),
        client.send('SubscribeToOperations', [{}]),
    )

with suppress(KeyboardInterrupt, asyncio.CancelledError):
    asyncio.run(main())

API Reference

SignalRClient

Parameters

  • url (str): The SignalR server URL.
  • access_token_factory (Callable[[], str], optional): A function that returns the access token.
  • headers (Dict[str, str], optional): Additional headers to include in the WebSocket handshake.

Methods

  • on_open(callback: Callable[[], Awaitable[None]]): Set the callback for connection open event.
  • on_close(callback: Callable[[], Awaitable[None]]): Set the callback for connection close event.
  • on_error(callback: Callable[[CompletionMessage], Awaitable[None]]): Set the callback for error events.
  • on(event: str, callback: Callable[[List[Dict[str, Any]]], Awaitable[Any | None]]): Set the callback for a specific event.
  • send(method: str, args: List[Any]): Send a message to the server.

CompletionMessage

A message received from the server upon completion of a method invocation.

Attributes

  • error (str): The error message, if any.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pysignalr-1.3.0.tar.gz (16.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pysignalr-1.3.0-py3-none-any.whl (20.0 kB view details)

Uploaded Python 3

File details

Details for the file pysignalr-1.3.0.tar.gz.

File metadata

  • Download URL: pysignalr-1.3.0.tar.gz
  • Upload date:
  • Size: 16.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.2 CPython/3.13.3 Linux/6.8.0-1026-azure

File hashes

Hashes for pysignalr-1.3.0.tar.gz
Algorithm Hash digest
SHA256 ca2e4372f213d82148fa2f060f0fefd096f1f66fca1107ac05e76ec6abd4cf52
MD5 cda285a52824d1117a75a1e79fae9bad
BLAKE2b-256 93a6ac80bd4972604c6930050e8b0eba41d6fde41cb3286087be0188a8865f55

See more details on using hashes here.

File details

Details for the file pysignalr-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: pysignalr-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 20.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.2 CPython/3.13.3 Linux/6.8.0-1026-azure

File hashes

Hashes for pysignalr-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 423c91b0d1dc8387f37118ac2d1dc87ed6b9e01993a04612eab8452193f40344
MD5 5db02911c955106998d60967eef6a0cb
BLAKE2b-256 2f5474e35563927ab8538e1bd1404b35027861434aecf2bcc945ff30c188e56d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page