使用rpyc更新远程对象的属性

时间:2016-01-17 21:47:31

标签: python rpyc

我在应用程序中使用rpyc并遇到了一个小小的打嗝。

我想知道是否可以更新远程属性?

我有一个测试服务器:

import rpyc
from rpyc.utils.server import ThreadedServer

class Test:
    def __init__(self):
        self._v = 0

    @property
    def V(self):
        return self._v

    @V.setter
    def V(self, value):
        self._v = value


class TestService(rpyc.Service):

    def exposed_Test(self):
        return Test()

if __name__ == '__main__':

    t = ThreadedServer(TestService, port = 2942,
                    protocol_config={"allow_all_attrs":True})
    t.start()

并在ipython控制台中:

In [1]: import rpyc

In [2]: conn = rpyc.connect('localhost', 2942, config={'allow_all_attrs':True})

In [3]: test = conn.root.Test()

In [4]: test.V
Out[4]: 0

In [5]: test.V = 2
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-d3ae0dcd1075> in <module>()
----> 1 test.V = 2
<blah blah traceback>
AttributeError: cannot access 'V'

是否可以更新远程属性?

1 个答案:

答案 0 :(得分:1)

是的,默认情况下会阻止设置远程属性,但如果设置allow_setattr=True,则允许设置。

(如果你设置allow_delattr=True,设置allow_setattr=True也是有意义的)

t = ThreadedServer(TestService, port = 2942,
                protocol_config={"allow_all_attrs":True,
                                 "allow_setattr": True,
                                 "allow_delattr": True,})

请参阅the docs

你也可以通过直接访问远程对象的__dict__来绕过setattr-protection(当然第一个解决方案要好得多):

test.__dict__['V'] = 2
相关问题