python - Twisted - 将factory.clients中的当前连接与唯一ID相匹配

标签 python database twisted

我正在尝试使用 Twisted 实现聊天服务器,但在将唯一用户 ID(存储在数据库中)与存储在factory.clients 中的当前 session 配对时遇到困难。在下面的代码中,我假设新连接的用户在加入服务器后将立即发送其用户 ID。有了这个假设,我将factory.clients中的最后一个条目作为其连接的索引并将其存储在数据库中。这种方法有很多缺陷,我正在尝试确定一种更好的方法。

我的主要问题:将唯一用户 ID 与连接配对的最佳方式是什么?

class ChatPlace(Protocol):
def connectionMade(self):
    self.factory.clients.append(self)
    print "clients are ", self.factory.clients
    print "connection from", self.transport.getPeer().host

def connectionLost(self, reason):
    self.factory.clients.remove(self)

    def dataReceived(self, data):

        #Variables and data parsing logic removed for brevity

        #The cur_connect_idx should be mapped to factory.clients but I'm not sure of the best way
        cur_connect_idx = len(self.factory.clients)-1

        #Once the client_id can be properly accessed, I want to store info as follows so that a connection can be paired with a user_id
        sql = "INSERT INTO user_db(user_id, user_name,cur_connect_idx) VALUES('%s','%s', '%d')" % (self.name, self.transport.getPeer().host,'',client_id)

    #Remaining code omitted for brevity 

最佳答案

为什么需要将连接 ID 放入数据库?

数据库是您保持持久状态的地方。连接和连接 ID 是 transient 的。

当您确定连接代表哪个用户时,将该信息放入工厂(或其他一些长期存在的对象)的数据结构中。

例如:

def dataReceived(self, data):
    username = self._parseAndExtractUsername(data)
    if username is not None:
        self.factory.users[username] = self

现在您在工厂中有一个字典,在所有协议(protocol)实例之间共享,它将用户名映射到协议(protocol)实例。

关于python - Twisted - 将factory.clients中的当前连接与唯一ID相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641967/

相关文章:

python - 关闭 QWidget 窗口

PHP5数据库密码能被盗吗?

database - 与实体关联的描述性标签是否应该存储在单独的数据库表中?

python - Twisted 中的 TCP 服务器问题

python - 在 Django 管理更改列表中,如何显示空格而不是默认的 "(None)"?

python - tox/conda/travis-ci 引发 ImportError : _PyErr_ReplaceException

python - 递归函数(带移位)

database - 如何读取 WhatsApp Messengers SQLite3 数据库中的 thumb_image 列?

python - 无法在 Twisted 中获取上传的文件

python - 扭曲的task.loop和pb auth