【问题标题】:Pass Object class to server method using Message Pack RPC使用 Message Pack RPC 将 Object 类传递给服务器方法
【发布时间】:2013-07-16 12:41:08
【问题描述】:

我想从客户端调用服务器中的一个方法,并且我想向该方法传递一个由我编写的类的参数。如何使用 MsgPack RPC 执行此操作。 我知道如何将 int 传递给向量或字符串。

【问题讨论】:

    标签: rpc msgpack messagepack


    【解决方案1】:

    您可以在调用中添加 to_msgpack 属性并为其定义编码器。 这将允许您将对象发送到服务器。服务器将其作为字典接收。 如果需要,可以将其转换为对象。 我个人希望 msgpack-rpc 让你在类中指定 object_hook,比如 form_msgpack。只是为了表明我在 get_object 中使用了 mgpack。

    服务器代码:

    #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()
    

    客户代码:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 2012-05-13
      相关资源
      最近更新 更多