jarpc 0.4.0a0 Documentation

Welcome to jarpc’s documentation!

Welcome to jarpc’s documentation!

Introduction

This is the documentation for jarpc, a library for asynchronous RPC via Redis pubsub channels.

It supports 3 runmodes: Client, Server and Slient.

Prerequisites

jarpc requires a Python version of 3.6 or higher.

Installing

Installation from PyPi:

pip install jarpc

You’ll also need a working local installation of Redis.

Quick example

Setup a quick Redis instance via Docker:

docker run --rm --name redis -d -p 6379:6379 redis:5.0.6-alpine

Client example

import asyncio

from jarpc import Client

REDIS_HOST = "localhost"
REDIS_PORT = 6379

COMMAND_PING = 0
COMMAND_SLOW_PING = 1
COMMAND_FIX_BUGS = 42


async def main() -> None:
    client = Client("example", default_timeout=5, default_expect_responses=1)

    asyncio.create_task(client.start((REDIS_HOST, REDIS_PORT)))

    await client.wait_until_ready()

    ping_data = {"message": input("Enter message to send or leave blank: ")}

    print("PING      ->", await client.call(COMMAND_PING, ping_data))
    print("SLOW_PING ->", await client.call(COMMAND_SLOW_PING, timeout=1))
    print("FIX_BUGS  ->", await client.call(COMMAND_FIX_BUGS))

    # exit
    client.close()


if __name__ == "__main__":
    asyncio.run(main())

Server example

import asyncio
import os

from jarpc import Request, Server

REDIS_HOST = "localhost"
REDIS_PORT = 6379

COMMAND_PING = 0
COMMAND_SLOW_PING = 1

server = Server("example", node=f"example-{os.getpid()}")


@server.command(COMMAND_PING)
async def ping(req: Request, message: str = "") -> str:
    """Responds with provided message argument or 'pong'."""

    print("Received PING command")

    return message or "pong"


@server.command(COMMAND_SLOW_PING)
async def slow_ping(req: Request) -> str:
    """Responds with 'pong' after 2 seconds, too slow..."""

    print("Received SLOW_PING command")

    await asyncio.sleep(2)

    return "pong"


if __name__ == "__main__":
    server.run((REDIS_HOST, REDIS_PORT))

Slient example

import asyncio
import os

from jarpc import Request, Slient

REDIS_HOST = "localhost"
REDIS_PORT = 6379

COMMAND_PING = 0

slient = Slient(
    "example",
    node=f"example-{os.getpid()}",
    default_timeout=5,
    default_expect_responses=1,
)


@slient.command(COMMAND_PING)
async def ping(req: Request, message: str = "") -> str:
    """Responds with provided message argument or 'pong'."""

    print("Received PING command")

    return message or "pong"


async def call_ping(slient: Slient) -> None:
    await slient.wait_until_ready()

    print("PING ->", await slient.call(COMMAND_PING))


if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    loop.create_task(slient.start((REDIS_HOST, REDIS_PORT)))
    loop.create_task(call_ping(slient))

    # continue listening for commands
    loop.run_forever()

Indices and tables

Free document hosting provided by Read the Docs.