Search code examples
pythonpython-2.7twisted

Protocols list in Twisted app


I would like to know which is best way to manage the protocols active in Twisted or if there is no concrete way.

In my current app I created a dictionary where there are two fields. At one I put the remote user and the local user to another. Both fields are lists so I can add several items.

The method I'm using is the following. First I check by a try-except if the dictionary exists. If there is no dictionary, I create it.

    try:
        if self.factory.active_protocols:
            log.msg('Active protocols dictionary already created')
    except Exception as e:
        log.err(e)
        self.factory.active_protocols = {}
        self.factory.active_protocols.setdefault('localUsr', [])
        self.factory.active_protocols.setdefault('remoteUsr', [])

Then I check if the local user is in the local users list. If there is no user I adds it to the list of local users. If the list exists, it throws an error.

    if sUsername in self.factory.active_protocols['localUsr']:
        log.err('Client already logged in')
        raise UnauthorizedLogin('Client already logged in')
    else:
        # Attach local user to active protocols list.
        self.sUsername = sUsername
        self.factory.active_protocols['localUsr'].append(self.sUsername)

If the conditions are right the remote user is also added to the list of remote users using the following code.

        # If time is correct, attach remote user to active_protocols
        self.factory.active_protocols['remoteUsr'].append(remoteUsr)

When I disconnect users, I delete the lists using the following code.

    if self.sUsername in self.factory.active_protocols['localUsr']:
        self.factory.active_protocols['localUsr'] = []
    if self.remoteUsr in self.factory.active_protocols['remoteUsr']:
        self.factory.active_protocols['remoteUsr'] = []

Is there a more correct way to do it? Should implement some special kind of dictionary? To Create a list? Does using a proprietary method of Twisted?

I have been looking for information about internet and I have not found anything conclusive about it.

Thank you!


Solution

  • No, there is no special type of list or dictionary in Twisted you can use for this.

    Twisted's job is turning network events into method calls on your objects. Once you you are implementing those methods on those objects, as much as possible, you want to use regular Python data structures. There are certain things in Twisted, like Deferreds, which are data structures you can use to implement certain asynchronous data-flow patterns, but for something as simple as a basic observer pattern with multiple entities in a list, regular lists and dictionaries and such are just fine.