在新客户端上聊天服务器mysql查询

时间:2012-09-22 18:50:11

标签: python twisted mysql-python

我有一个简单的聊天服务器,我想在新客户端连接时查询我的数据库。我尝试使用twistar CRUD接口但是我遇到了一个奇怪的错误:

exceptions.NameError:未定义全局名称“结果”

from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.enterprise import adbapi
from twisted.internet import reactor
from twistar.registry import Registry
from twistar.dbobject import DBObject

Registry.DBPOOL = adbapi.ConnectionPool('MySQLdb', host="localhost", db="testdb", user="test", passwd="test")
dbconfig = Registry.getConfig()

class Chat(LineReceiver):

    # Here is the callback
    def result(values):
        print values

    def __init__(self, users):
        self.users = users
        self.name = None
        self.state = "GETNAME"

    def connectionMade(self):
        self.sendLine("What's your name?")

    def connectionLost(self, reason):
        if self.users.has_key(self.name):
            del self.users[self.name]

    def lineReceived(self, line):
        if self.state == "GETNAME":
            self.handle_GETNAME(line)
        else:

    def handle_GETNAME(self, name):
        if self.users.has_key(name):
            self.sendLine("Name taken, please choose another.")
            return
        self.sendLine("Welcome, %s!" % (name,))
        # Here is the query
        d = dbconfig.select("testtable").addCallback(result)**

        self.name = name
        self.users[name] = self
        self.state = "CHAT"

    def handle_CHAT(self, message):
        message = "<%s> %s" % (self.name, message)
        for name, protocol in self.users.iteritems():
            if protocol != self:
                protocol.sendLine(message)

def result(var):
       print var

class ChatFactory(Factory):

    def __init__(self):
        self.users = {} # maps user names to Chat instances

    def buildProtocol(self, addr):
        return Chat(self.users)

reactor.listenTCP(8000, ChatFactory())
reactor.run()

在聊天服务器之外,CRUD数据库查询可以正常运行。

提前谢谢

1 个答案:

答案 0 :(得分:2)

如果结果是该类的成员,则必须以self开头。

 d = dbconfig.select("testtable").addCallback(self.result)**