Usage

Quick Start

Connecting to a Diffusion server and listening to ping messages:

import asyncio
import logging
from datatime import datetime

import diffusion

server_url = "ws://your-diffusion-server:8080"
# you can also use your Diffusion Cloud service URL, e.g. ws://your-service.eu.diffusion.cloud:80
principal = "foo"
credentials = "bar"


async def my_main():

    creds = diffusion.Credentials(credentials)

    async with diffusion.Session(server_url, principal, creds) as session:
        connection = diffusion.Connection(session)

        def system_ping_handler():
            print(f"System ping received at {datetime.now()}")

        connection.add_ping_handler(system_ping_handler)

        await asyncio.sleep(10)


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    asyncio.run(my_main())

The output of the above script would look something like this (assuming that the server's ping interval was set to 3 seconds):

System ping received at 2020-08-20 16:32:34.665211
System ping received at 2020-08-20 16:32:37.665211
System ping received at 2020-08-20 16:32:40.665657

Notes on Usage

The Python SDK for Diffusion is built using the asynchronous programming paradigm, and concretely on top of the asyncio library.

In practice, it means that all the SDK code needs to be wrapped in a coroutine function (declared with async def) and executed using asyncio.run. For more detailed information about using asyncio, we recommend this overview.