Thanks to visit codestin.com
Credit goes to github.com

Skip to content

dmora/python-mixin-json-rpc2

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 

Repository files navigation

Python JSON-RPC v2.0 (mixin)

A Python Mixin approach for JSON-RPC v2.0

Why?

When building a solution, a framework is selected (django, tornado, web.py, etc). The main idea of having a Mixin approach is to leverage eveything that has to deal with the spec itself (decoding messages, encoding messages of invoked method results, invoking the method itself, etc.) without providing another WSGI handler or server implementation that needs to run part of the stack.

How?

Considering an approach of a MVC solution, you have a controller handling the requests, or another type of request handler which is dealing with the transport layer.

A good example of this is the websocket implementation by tornado. For instance:

class MyWebSocketHandler(tornado.websocket.WebSocketHandler, RequestHandlerMixin):
pass

Your handler is already providing the transport by extending the tornado websocket and is capable of RPC by mixin' in the RequestHandlerMixin from this library.

Basic Usage

from jsonrpc2.mixin import BaseJSONRPCException, RequestHandlerMixin

class MyException(BaseJSONRPCException):
    """
    Just a simple exception to test the extending capabilities or error handling.
    """
    code = 1
    message = "My Custom Exception"

class SimpleController(RequestHandlerMixin):
    """ A simple echo controller.

    Mimics what frameworks usually provides. E.g: in tornado you can extend
    the websocket handler and add the RPC capabilities by extending the mixin
    """
    def echo(self, message, **kwargs):
        return message

    def custom_exception(self, **kwargs):
        raise MyException()

    def internal_error(self, **kwargs):
        raise Exception()

And in the context of your handler (according to the framework)

handler = SimpleController()
response = str(handler.handle_request(data))

At this point, you need to pass the response back via the transport handler and you are set!

Testing

To run the tests: $ python -m unittest -v tests.parsing

About

A Python Mixin approach for JSON-RPC v2.0

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published