Pass Object class to server method using Message Pack RPC

565 Views Asked by At

I want to make a call from a client to a method in the server and I want to pass to the method an argument that is a class written by me. How can I do this using MsgPack RPC. I know how to pass an int a vector or a string.

1

There are 1 best solutions below

0
On

You can add to_msgpack attribute to your call and define a encoder for it. This will let you send an object to server. server will receive it as dictionary. if you want you can convert it to object. personally I would like msgpack-rpc to let you specify object_hook also in class say form_msgpack. just to show I have used mgpack in get_object.

Server Code:

#MSgpackRpcServer.py
import msgpackrpc
import msgpack
def encode_foo(obj):
    if isinstance(obj,Foo):
        return {'Foo':True,'id':obj.id,'name':obj.name,'email':obj.email}
def decode_foo(obj):
    if 'Foo' in obj:
        return Foo(obj['id'],obj['name'],obj['email'])
def get_object(inobj):
    return  msgpack.unpackb(msgpack.packb(inobj),object_hook=decode_foo)

class Foo(object):
    to_msgpack=encode_foo
    def __init__(self,a,b,c):
        self.id=a
        self.name=b
        self.email= c
    def something(self):
        return  self.id*100

class SomeService(object):

    def TestRPC(self,a):
        print a # prints dictionary
        setobject = get_object(a)
        print setobject # prints object instance
        return setobject.id +10 # do some thing

if __name__ == '__main__':
    server = msgpackrpc.Server(SomeService())
    server.listen(msgpackrpc.Address("localhost", 8001))
    server.start()

Client Code:

from MSgpackRpcServer import Foo
import msgpackrpc
c = msgpackrpc.Client(msgpackrpc.Address('127.0.0.1',8001))
foo= Foo(11,'Hello','hello@hello')
print  c.call('TestRPC',foo)