Skip to main content

JSON-RPC implementation for Django's channels library.

Project description

channels-rpc

`channels-rpc`` is aimed to enable JSON-RPC functionnality on top of the excellent django channels project and especially their Websockets functionality. It is aimed to be:

  • Fully integrated with Channels
  • Fully implement JSON-RPC 1 and 2 protocol
  • Support both WebSocket and HTTP transports
  • Easy integration

Installation

$ pip install git+ssh://git@github.com/quantivly/channels-rpc.git

Use

It is intended to be used as a WebSocket consumer:

from channels_rpc import JsonRpcWebsocketConsumer

class MyJsonRpcConsumer(JsonRpcConsumer):

    def connect(self, message, **kwargs):
        """Perform things on WebSocket connection start"""
        self.accept()
        print("connect")
        # Do stuff if needed

    def disconnect(self, message, **kwargs):
        """Perform things on WebSocket connection close"""
        print("disconnect")
        # Do stuff if needed

JsonRpcWebsocketConsumer derives from channels JsonWebsocketConsumer. Then, the last step is to create the RPC methos hooks using the rpc_method decorator:

@MyJsonRpcConsumer.rpc_method()
def ping():
    return "pong"

Or, with a custom name:

@MyJsonRpcConsumer.rpc_method("mymodule.rpc.ping")
def ping():
    return "pong"

Will now be callable with "method":"mymodule.rpc.ping" in the rpc call:

{
    "id":1,
    "jsonrpc":"2.0",
    "method":"mymodule.rpc.ping",
    "params":{}
}

RPC methods can obviously accept parameters. They also return "results" or "errors":

@MyJsonRpcConsumer.rpc_method("mymodule.rpc.ping")
def ping(fake_an_error):
    if fake_an_error:
        # Will return an error to the client
        #  --> {"id":1, "jsonrpc":"2.0","method":"mymodule.rpc.ping","params":{}} #  <-- {"id": 1, "jsonrpc": "2.0", "error": {"message": "fake_error", "code": -32000, "data": ["fake_error"]}}  raise Exception("fake_error")
    else:
        # Will return a result to the client
        #  --> {"id":1, "jsonrpc":"2.0","method":"mymodule.rpc.ping","params":{}} #  <-- {"id": 1, "jsonrpc": "2.0", "result": "pong"}  return "pong"

Async Use

Simply derive your customer from an asynchronous customer like AsyncJsonRpcWebsocketConsumer:

from channels_rpc import AsyncJsonRpcWebsocketConsumer

class MyAsyncJsonRpcConsumer(AsyncJsonRpcWebsocketConsumer):
	pass

@MyAsyncJsonRpcConsumer.rpc_method("mymodule.rpc.ping")
async def ping(fake_an_error):
    return "ping"

Sessions and other parameters from Consumer object

The original channel message - that can contain sessions (if activated with http_user) and other important info can be easily accessed by retrieving the **kwargs and get a parameter named consumer.

MyJsonRpcConsumerTest.rpc_method()
def json_rpc_method(param1, **kwargs):
    consumer = kwargs["consumer"]
    ##do something with consumer

Example:

class MyJsonRpcConsumerTest(JsonRpcConsumer):
    # Set to True to automatically port users from HTTP cookies
    # (you don't need channel_session_user, this implies it) # https://channels.readthedocs.io/en/stable/generics.html#websockets  http_user = True

....

@MyJsonRpcConsumerTest.rpc_method()
def ping(**kwargs):
    consumer = kwargs["consumer"]
    consumer.scope["session"]["test"] = True
    return "pong"

Testing

The JsonRpcConsumer class can be tested the same way Channels Consumers are tested. See here

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

channels_rpc-0.3.6.tar.gz (11.5 kB view details)

Uploaded Source

Built Distribution

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

channels_rpc-0.3.6-py3-none-any.whl (14.4 kB view details)

Uploaded Python 3

File details

Details for the file channels_rpc-0.3.6.tar.gz.

File metadata

  • Download URL: channels_rpc-0.3.6.tar.gz
  • Upload date:
  • Size: 11.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.9

File hashes

Hashes for channels_rpc-0.3.6.tar.gz
Algorithm Hash digest
SHA256 dc6d33f12ef1ea9fe580447a3e5b5bfcaec15bb3c654f12132e5e029e1e65a29
MD5 a707cf932fd08be9806545efe284a020
BLAKE2b-256 2a5b3aa4d1dea6933e57ea9e6303d334d495fed34a82305ac28b74505bc11dcf

See more details on using hashes here.

File details

Details for the file channels_rpc-0.3.6-py3-none-any.whl.

File metadata

  • Download URL: channels_rpc-0.3.6-py3-none-any.whl
  • Upload date:
  • Size: 14.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.9

File hashes

Hashes for channels_rpc-0.3.6-py3-none-any.whl
Algorithm Hash digest
SHA256 8ee1c18201ca2a8b63651968200b8cdd304f9b2f912a415543dae8fe0a95b1c4
MD5 fbfaf3c546ed6493b1f016b8ea310bec
BLAKE2b-256 bb31d5c037f0e9d0a46f810c6263090d37a4b8c589e22df739be80befc021b2b

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