2014-11-06 2 views
1

가능한 구성 변경을 위해 데이터베이스를 폴링해야하는 응용 프로그램이 있습니다. 응용 프로그램은 Twisted를 사용하는 간단한 xmlrpc 서버입니다. Twisted의 LoopingCall을 사용하여 폴링을 실험했지만 LoopingCall이 주 스레드에서 실행되기 때문에 db에 대한 호출이 차단됩니다. 그래서 어떤 이유로 DB 호출이 느린 경우 xmlrpc 서버에 대한 요청을 기다려야합니다. 그래서 LoopingCall을 하나의 스레드에서 실행하려고 시도했지만 실제로 작동시키지 못했습니다. 내 질문은 스레드에서 실행해야합니까? 그렇다면 어떻게?차단 기능이있는 꼬인 LoopingCall

from twisted.web import xmlrpc, server 
from twisted.internet.threads import deferToThread 
from twisted.internet import reactor, task 
import platform 
from time import sleep 

r = reactor 

class Agent(xmlrpc.XMLRPC): 
    self.routine() 
    xmlrpc.XMLRPC.__init__(self) 

    def xmlrpc_echo(self, x): 
     """ 
     Return arg as a simple test that the server is running 
     """ 
     return x 

    def register(self): 
     """ 
     Register Agent with db and pick up config 
     """ 
     sleep(3) # simulate slow db call 
     print 'registered with db' 

    def routine(self): 
     looping_register = task.LoopingCall(self.register) 
     looping_register.start(7.0, True) 

if __name__ == '__main__': 
    r.listenTCP(7081, server.Site(Agent())) 
    print 'Agent is running on "%s"' % platform.node() 
    r.run() 
+1

을 당신은 안 이것을 지원하는 것으로 문서화되어 있지 않다면 다른 스레드에서 Twisted API를 실행하십시오. 거의 아무 트위스트 API도 이것을 지원하지 않습니다. 당신이 이런 식으로 사용하려고하면, 디버깅하기가 어렵습니다. –

+0

그래, 그게 어려운 길을 배우고있어. 좋은 조언을 주셔서 감사합니다 – MFB

답변

1

twisted.enterprise.adbapi 모듈을 사용해야합니다. 방문하시기 바랍니다 자세한 내용과 예제

from twisted.enterprise import adbapi 


dbpool = adbapi.ConnectionPool('psycopg2', 'mydb', 'andrew', 'password') # replace psycopg2 with your db client name. 

def getAge(user): 
    return dbpool.runQuery('SELECT age FROM users WHERE name = ?', user) 

def printResult(l): 
    if l: 
     print l[0][0], "years old" 
    else: 
     print "No such user" 

getAge("joe").addCallback(printResult) 

공식 문서 : 그것은 스레드 풀에서 그들을 실행하고 당신에게 이연 기준을 반환하여 당신에게 모든 DBAPI 2.0 호환 클라이언트 블로킹 API를 제공합니다 https://twistedmatrix.com/documents/14.0.0/core/howto/rdbms.html

+0

또는 아마 더 나은, twblue의 일부인 adbapi2 모듈 - https://pypi.python.org/pypi/twextpy/0.1a12469 –

+0

twextpy.enterprise.adbapi2는 좋아 보이지만 작동하지 않았습니다. 그것 –

+0

흠 나는 그 문서들로부터 많은 것을 배웠고 기술적으로 당신의 대답이 옳다. 그러나 필자의 경우 db는 비 관계형 데이터베이스 (MongoDB)입니다. 나는 그것이 그것이 적절하다는 것을 몰랐기 때문에 언급하지 않았다. – MFB