[Twisted-Python] Why does this not work?

Valentino Volonghi aka Dialtone dialtone at aruba.it
Thu Dec 11 12:03:05 EST 2003


I don't get why this version of my software does not work...  The
previous version did not use service.Service but directly
protocol.ServerFactory and it worked right.

Basically this software is a server to which you can connect and
manage some database, actually now it only supports sqlite but it will
support more and more soon I hope.

######################################## CODE HERE ################
VERSION = 0.1

from twisted.application import internet, service
from twisted.internet import protocol, reactor, defer
from twisted.protocols import basic

import sqlite

def catchError(err):
    return "Internal Server"

class DBUniversalProtocol(basic.LineReceiver):
    def send_results(self, q_results):
        if q_results:
            print "Sending data...",
            self.transport.write(str(q_results) +'\r\n')
            print "OK"

    def connectionMade(self):
        self.factory.connect_to_DB()

    def connectionLost(self, reason):
        print "Connection closed by client... ",
        self.factory.conn.commit()
        self.factory.cursor.close()
        self.factory.conn.close()
        print "Reset done."

    def lineReceived(self, line):
        d = self.factory.dispatch_function(line)
        d.addErrback(catchError)
        d.addCallback(self.send_results)        

class DBUniversalService(service.Service):
    def __init__(self):
        print "DB Universal Server, v.", VERSION, "(c) Valentino Volonghi"
        print "Licensed under the Lesser General Public License v2.1"
        print "Written by Valentino Volonghi and released without any warranties"
        
        self.dispatcher = {'set_query':self.set_query,
                           'get_many':self.get_many,
                           'get_all':self.get_all,
                           'get_one':self.get_one
                          }
        self.conn = None
        self.cursor = None

    def getDBUniversalFactory(self):
        f = protocol.ServerFactory()
        f.protocol = DBUniversalProtocol
        f.dispatch_function = self.dispatch_function
        f.conn = self.conn
        f.cursor = self.cursor
        f.connect_to_DB = self.connect_to_DB
        return f

    def dispatch_function(self, line):
        # Every line sent to this server is made of some parts:
        # "FUN_TO_CALL:ARGS_IF_ANY\r\n"
        # Be sure to always use this format standard otherwise
        # You won't have the expected behaviour
        
        fun = line.split(":")[0]
        callable = self.dispatcher.get(fun.strip(), None)
        if not callable:
            return defer.succeed(self.error())
        else:
            return defer.succeed(callable(line))

    def set_query(self, line):
        arg = line.split(":")[1]
        self.SQL = arg
        return self.run_query()

    def get_many(self, line):
        arg = line.split(":")[1]
        try:
            NUM = int(arg)
        except:
            return defer.succeed(self.error())
        return defer.succeed(self.cursor.fetchmany(NUM))

    def get_all(self, line):
        return defer.succeed(self.cursor.fetchall())

    def get_one(self, line):
        return defer.succeed(self.cursor.fetchone())

    def error(self):
        return "Operation Failed!"

    def allOK(self):
        return "OK"
    
    def run_query(self):
        print "Checking the query (%s)... " %(self.SQL.strip()),
        isCorrect = self.check_query(self.SQL)        
        if isCorrect:
            print " OK"
            self.cursor.execute(self.SQL)
            return defer.succeed(self.allOK())
        else:
            print " Failed"
            return defer.succeed(self.error())

    def check_query(self, to_check):
        res = to_check.split("\r\n")
        if len(res) > 2: return 0
        if res[0][-1] != ";": return 0
        return 1

    def connect_to_DB(self):
        print "Connecting to DB... ",
        self.conn = sqlite.connect("test.db")
        self.cursor = self.conn.cursor()
        print "OK"

#############################################
MYPORT = 6000
application = service.Application('dbi_face', uid=1000, gid=1000)
f = DBUniversalService()
serviceCollection = service.IServiceCollection(application)
internet.TCPServer(MYPORT, f.getDBUniversalFactory()
                   ).setServiceParent(serviceCollection)
#############################################
Are these last lines right or are they wrong?

I've not really understood the meaning of the last lines,
while I understand the meaning of:

reactor.listenTCP(MYPORT, DBUniversalServer())
reactor.run()

I must say I based my "upgrade" to finger listings.

Thanks for your help

-- 
Valentino Volonghi, Regia SpA, Milan
Linux User #310274, Gentoo Proud User




More information about the Twisted-Python mailing list