KnutAPI

class knut.apis.KnutAPI

Provide the base Knut API.

Note

This class must be subclassed by each service specific API.

The request_handler() builds the core for communicate to services handled by the API. It handles a request message and calls a callback function for each message type. The supported message types with their callback functions need to be registered in the supported dictionary.

Each callback function must take the message dictionary as argument and must return a tuple with the response message type and the response message dictionary.

For example, lets add the message type FOO_PRINT = 0x0001 with its callback function handle_foo(). The example message handler should print a text that is passed by the message and return a NULL message. Therefore, the message of type FOO_PRINT in this example shall contain the key 'text'. Lets first define a Foo object which inherits the KnutAPI:

from knut.apis import KnutAPI


class Foo(KnutAPI):
    apiid = 0x01
    FOO_PRINT = 0x0001

    def __init__(self):
        super(Foo, self).__init__()
        self.supported = {Foo.FOO_PRINT: self.handle_foo}

    def handle_foo(self, msg):
        print(msg['text'])
        return Foo.NULL, {}

With that class defined, our example message would be handled as following:

>>> foo = Foo()
>>> foo.request_handler(0x0001, {'text': 'bar'})
bar
(0, {})
NULL = 0

The null message indicates that no further action is going to happen.

apiid = 0

The API identifier.

request_handler(msg_id: int, msg: dict) → Tuple[int, dict]

Return the tuple (response_id, response) upon a request.

Handle the request msg of type msg_id and return a corresponding response of type response_id. If either no valid request msg was passed, or the request does not expect any response, the response (0x0000, {}) is returned.

This method checks the supported dictionary and calls the corresponding callback function if found.

supported = None

A dictionary with all supported message types as keys and their callback functions as values {msg_id: callback}.