Common

Client and server common functions, types and classes that implements JSON-RPC protocol itself and agnostic to any transport protocol layer (http, socket, amqp) and server-side implementation.

class pjrpc.common.AbstractRequest

Bases: ABC

JSON-RPC version 2.0 abstract request.

class pjrpc.common.AbstractResponse

Bases: ABC

JSON-RPC version 2.0 abstract response.

class pjrpc.common.Request(method, params=None, id=None)

Bases: AbstractRequest

JSON-RPC version 2.0 request.

Parameters
  • method (str) – method name

  • params (Optional[JsonRpcParams]) – method parameters

  • id (Optional[JsonRpcRequestId]) – request identifier

classmethod from_json(json_data)

Deserializes a request from json data.

Parameters

json_data (pjrpc.common.typedefs.Json) – data the request to be deserialized from

Returns

request object

Raises

pjrpc.common.exceptions.DeserializationError if format is incorrect

Return type

Request

property id: Optional[JsonRpcRequestId]

Request identifier.

property method: str

Request method name.

property params: Optional[JsonRpcParams]

Request method parameters.

to_json()

Serializes the request to json data.

Returns

json data

Return type

pjrpc.common.typedefs.Json

property is_notification: bool

Returns True if the request is a notification e.g. id is None.

class pjrpc.common.Response(id, result=UNSET, error=UNSET)

Bases: AbstractResponse

JSON-RPC version 2.0 response.

Parameters
  • id (Optional[JsonRpcRequestId]) – response identifier

  • result (Union[UnsetType, Any]) – response result

  • error (Union[UnsetType, JsonRpcError]) – response error

classmethod from_json(json_data, error_cls=<class 'pjrpc.common.exceptions.JsonRpcError'>)

Deserializes a response from json data.

Parameters
  • json_data (pjrpc.common.typedefs.Json) – data the response to be deserialized from

  • error_cls (Type[JsonRpcError]) – error class

Returns

response object

Raises

pjrpc.common.exceptions.DeserializationError if format is incorrect

Return type

Response

property id: Optional[JsonRpcRequestId]

Response identifier.

property result: Any

Response result. If the response has not succeeded raises an exception deserialized from the error field.

property error: Union[pjrpc.common.common.UnsetType, pjrpc.common.exceptions.JsonRpcError]

Response error. If the response has succeeded returns pjrpc.common.common.UNSET.

property is_success: bool

Returns True if the response has succeeded.

property is_error: bool

Returns True if the response has not succeeded.

property related: Optional[pjrpc.common.v20.Request]

Returns the request related response object if the response has been received from the server otherwise returns None.

get_error()

Returns error. If error is not set raises and exception.

Return type

JsonRpcError

to_json()

Serializes the response to json data.

Returns

json data

Return type

pjrpc.common.typedefs.Json

class pjrpc.common.BatchRequest(*requests, strict=True)

Bases: AbstractRequest

JSON-RPC 2.0 batch request.

Parameters
  • requests (Request) – requests to be added to the batch

  • strict (bool) – if True checks response identifier uniqueness

classmethod from_json(data)

Deserializes a batch request from json data.

Parameters

data (pjrpc.common.typedefs.Json) – data the request to be deserialized from

Returns

batch request object

Return type

BatchRequest

append(request)

Appends a request to the batch.

Parameters

request (Request) –

Return type

None

extend(requests)

Extends a batch with requests.

Parameters

requests (Iterable[Request]) –

Return type

None

to_json()

Serializes the request to json data.

Returns

json data

Return type

pjrpc.common.typedefs.Json

property is_notification: bool

Returns True if all the request in the batch are notifications.

class pjrpc.common.BatchResponse(*responses, error=UNSET, strict=True)

Bases: AbstractResponse

JSON-RPC 2.0 batch response.

Parameters
  • responses (Response) – responses to be added to the batch

  • strict (bool) – if True checks response identifier uniqueness

  • error (Union[UnsetType, JsonRpcError]) –

classmethod from_json(json_data, error_cls=<class 'pjrpc.common.exceptions.JsonRpcError'>)

Deserializes a batch response from json data.

Parameters
  • json_data (pjrpc.common.typedefs.Json) – data the response to be deserialized from

  • error_cls (Type[JsonRpcError]) – error class

Returns

batch response object

Return type

BatchResponse

property error: Union[pjrpc.common.common.UnsetType, pjrpc.common.exceptions.JsonRpcError]

Response error. If the response has succeeded returns pjrpc.common.common.UNSET.

property is_success: bool

Returns True if the response has succeeded.

property is_error: bool

Returns True if the request has not succeeded. Note that it is not the same as pjrpc.common.BatchResponse.has_error. is_error indicates that the batch request failed at all, while has_error indicates that one of the requests in the batch failed.

property has_error: bool

Returns True if any response has an error.

property result: Tuple[Any, ...]

Returns the batch result as a tuple. If any response of the batch has an error raises an exception of the first errored response.

property related: Optional[pjrpc.common.v20.BatchRequest]

Returns the request related response object if the response has been received from the server otherwise returns None.

get_error()

Returns error. If error is not set raises and exception.

Return type

JsonRpcError

append(response)

Appends a response to the batch.

Parameters

response (Response) –

Return type

None

extend(responses)

Extends the batch with the responses.

Parameters

responses (Iterable[Response]) –

Return type

None

to_json()

Serializes the batch response to json data.

Returns

json data

Return type

pjrpc.common.typedefs.Json

class pjrpc.common.UnsetType

Bases: object

Sentinel object. Used to distinct unset (missing) values from None ones.

class pjrpc.common.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: JSONEncoder

Library default JSON encoder. Encodes request, response and error objects to be json serializable. All custom encoders should be inherited from it.

default(o)

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
Parameters

o (Any) –

Return type

Any

pjrpc.common.DEFAULT_CONTENT_TYPE = 'application/json'

default JSON-RPC client/server content type

pjrpc.common.REQUEST_CONTENT_TYPES = ('application/json', 'application/json-rpc', 'application/jsonrequest')

allowed JSON-RPC server requests content types

pjrpc.common.RESPONSE_CONTENT_TYPES = ('application/json', 'application/json-rpc')

allowed JSON-RPC client responses content types

pjrpc.common.set_default_content_type(content_type)

Sets default json-rpc client request / json-rpc server response content type.

Parameters

content_type (str) –

Return type

None

Types

pjrpc.common.typedefs.JsonRpcParams

JSON-RPC params type

alias of Union[List[Any], Tuple[Any, …], Dict[str, Any]]

pjrpc.common.typedefs.JsonRpcRequestId

JSON-RPC identifier type

alias of Union[str, int]

pjrpc.common.typedefs.Json

JSON type

alias of Optional[Union[List[Any], Tuple[Any, …], Set[Any], Dict[str, Any]]]

pjrpc.common.typedefs.MethodType

Method type

alias of Callable[[…], Any]

pjrpc.common.typedefs.Func

Function type

alias of TypeVar(‘Func’, bound=Callable[[…], Any])

Exceptions

Definition of package exceptions and JSON-RPC protocol errors.

exception pjrpc.common.exceptions.BaseError

Bases: Exception

Base package error. All package errors are inherited from it.

exception pjrpc.common.exceptions.IdentityError

Bases: BaseError

Raised when a batch requests/responses identifiers are not unique or missing.

exception pjrpc.common.exceptions.DeserializationError

Bases: BaseError, ValueError

Request/response deserializatoin error. Raised when request/response json has incorrect format.

class pjrpc.common.exceptions.JsonRpcErrorMeta(name, bases, dct)

Bases: type

pjrpc.common.exceptions.JsonRpcError metaclass. Builds a mapping from an error code number to an error class inherited from a pjrpc.common.exceptions.JsonRpcError.

Parameters
Return type

Type[JsonRpcError]

exception pjrpc.common.exceptions.JsonRpcError(code=None, message=None, data=UNSET)

Bases: BaseError

JSON-RPC protocol error. For more information see Error object. All JSON-RPC protocol errors are inherited from it.

Parameters
  • code (int) – number that indicates the error type

  • message (str) – short description of the error

  • data (Union[UnsetType, Any]) – value that contains additional information about the error. May be omitted.

classmethod from_json(json_data)

Deserializes an error from json data. If data format is not correct ValueError is raised.

Parameters

json_data (pjrpc.common.typedefs.Json) – json data the error to be deserialized from

Returns

deserialized error

Raises

pjrpc.common.exceptions.DeserializationError if format is incorrect

Return type

JsonRpcError

to_json()

Serializes the error to a dict.

Returns

serialized error

Return type

pjrpc.common.typedefs.Json

exception pjrpc.common.exceptions.ClientError(code=None, message=None, data=UNSET)

Bases: JsonRpcError

Raised when a client sent an incorrect request.

Parameters
exception pjrpc.common.exceptions.ParseError(code=None, message=None, data=UNSET)

Bases: ClientError

Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.

Parameters
exception pjrpc.common.exceptions.InvalidRequestError(code=None, message=None, data=UNSET)

Bases: ClientError

The JSON sent is not a valid request object.

Parameters
exception pjrpc.common.exceptions.MethodNotFoundError(code=None, message=None, data=UNSET)

Bases: ClientError

The method does not exist / is not available.

Parameters
exception pjrpc.common.exceptions.InvalidParamsError(code=None, message=None, data=UNSET)

Bases: ClientError

Invalid method parameter(s).

Parameters
exception pjrpc.common.exceptions.InternalError(code=None, message=None, data=UNSET)

Bases: JsonRpcError

Internal JSON-RPC error.

Parameters
exception pjrpc.common.exceptions.ServerError(code=None, message=None, data=UNSET)

Bases: JsonRpcError

Reserved for implementation-defined server-errors. Codes from -32000 to -32099.

Parameters

Identifier generators

Builtin request id generators. Implements several identifier types and generation strategies.

pjrpc.common.generators.sequential(start=1, step=1)

Sequential id generator. Returns consecutive values starting from start with step step.

Parameters
  • start (int) –

  • step (int) –

Return type

Generator[int, None, None]

pjrpc.common.generators.randint(a, b)

Random integer id generator. Returns random integers between a and b.

Parameters
Return type

Generator[int, None, None]

pjrpc.common.generators.random(length=8, chars='0123456789abcdefghijklmnopqrstuvwxyz')

Random string id generator. Returns random strings of length length using alphabet chars.

Parameters
  • length (int) –

  • chars (str) –

Return type

Generator[str, None, None]

pjrpc.common.generators.uuid()

UUID id generator. Returns random UUIDs.

Return type

Generator[UUID, None, None]