简体   繁体   English

使用zerorpc维护会话

[英]Maintain sessions with zerorpc

How do I maintain different sessions or local state with my zerorpc server? 如何使用Zerorpc服务器维护不同的会话或本地状态?

For example (below), if I have a multiple clients, subsequent clients will overwrite the model state. 例如(如下),如果我有多个客户端,则后续的客户端将覆盖模型状态。 I thought about each client having an ID, and the RPC logic will try to separate the variables that way, but tbis seems messy and how would I clear out old states/variables once the clients disconnect? 我考虑过每个具有ID的客户端,RPC逻辑将尝试以这种方式分离变量,但是tbis看起来很混乱,一旦客户端断开连接,我将如何清除旧状态/变量?

Server 服务器

import zerorpc
import FileLoader

class MyRPC(object):
    def load(self, myFile):
        self.model = FileLoader.load(myFile)
    def getModelName(self):
        return self.model.name

s = zerorpc.Server(MyRPC())
s.bind("tcp://0.0.0.0:4242")
s.run()

Client 1 客户1

import zerorpc

c = zerorpc.Client()
c.connect("tcp://127.0.0.1:4242")
c.load("file1")
print c.getModelName()

Client 2 客户2

import zerorpc

c = zerorpc.Client()
c.connect("tcp://127.0.0.1:4242")
c.load("file2") # AAAHH! The previously loaded model gets overwritten here! 
print c.getModelName()

Not sure about sessions...but if you want to get back different models? 不确定会话...但是如果您想找回不同的型号? Maybe you could just have once function that instantiates a new Model()? 也许您只有一次实例化一个新Model()的函数?

import zerorpc
import FileLoader

models_dict ={}  # Keep track of our models

def get_model(file):
    if file in models_dict:
        return models_dict[file]
    models_dict[file] = MyModel(file)
    return model

class MyModel(object):

    def __init__(self, file):
        if file:
            self.load(file)

    def load(self, myFile):
        self.model = FileLoader.load(myFile)

    def getModelName(self):
        return self.model.name

s = zerorpc.Server(<mypackagename.mymodulename>)  # Supply the name of current package/module
s.bind("tcp://0.0.0.0:4242")
s.run()

Client: 客户:

import zerorpc

c = zerorpc.Client()
c.connect("tcp://127.0.0.1:4242")
print c.get_model("file1")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM