일단, Query를 실행하는 방법은 크게 두 가지를 쓸 수 있겠다. runQuery()를 사용하는 방법과, runInteraction()을 사용하는 방법이다. 주어진 table에서 10개의 row를 가져오고자 한다고 했을때, 1) runQuery() 사용하기 def getCount(): return dbpool.runQuery("select * from test") def printResult(l): if l: result = l[0][0] print l[0][0], " records" else: print "no rows fetched" dbpool = adbapi.ConnectionPool('MySQLdb', db='abcd', user='abcd', passwd='abcd') getCount().a..
Twsited Matrix Framework 상에서 DB에 접속하려면, 해당 DB의 python 모듈이 설치되어 있어야 한다. 예) mysql용 : mySQl for python 모듈 (sourceforge.net에서 다운받는다) 1. 필요한 라이브러리 import from twisted.enterprise import adbapi from twisted.internet import reactor 2. DB에 접속하기 dbpool = adbapi.ConnectionPool('dbmodule', 'mydb', 'id', 'password')의 형식으로 기록한다. 따라서, 다음의 두 방법과 같이 접속 정보를 기록할 수 있다. 1) 방법 #1 dbpool = adbapi.ConnectionPool('MySQL..
Optik (aka optarse) 를 사용하면, pytthon 애플리케이션 개발시 커맨드라인 옵션/ 파라미터를 파싱하기 쉬워진다. 예를 들어서, "실행파일명 --config 파일명" 으로 구성되는 형태의 옵션을 만들고 싶다면, 다음과 같이 간단하게 구성할 수 있다. from optik import OptionParser def main(): usage = "usage: %prog [options] arg" parser = OptionParser(usage) parser.add_option("-c", "--config", action="store", type="string", dest="filename" ) (options, args) = parser.parse_args() if options.filen..
java에서의 System.currentTimeMillis()에 해당 하는 것이 Python에서는 어떤 것이 있을까 궁금했다. 현재, 확인한 바로는 time 패키지의 time.clock()이 유용할 듯 하다. 이것의 특징은 애플리케이션이 실행된 시점으로부터 계산되는 count라는 점이다. 즉, 상대적인 stop watch라는 점. begin = time.clock() ... do something ... end = time.clock() elapsed = end - begin 과 같이, 소요된 시간을 구할 수 있다. 기본 단위가 seconds로 리턴이 되기 때문에 milliseconds는 0.xxx로 표현되는 값으로부터 얻을 수 있다. 반면, datetime.now()을 사용하게 되면, HH:MM:SS:..
ㅋ 앞서 간단히 만든 서버에 접속할 클라이언트를 만들어 봤다. # 프로토콜 class TestClient(LineReceiver): def connectionMade(self): self.sendLine("A new connection has been made!") self.factory.clientReady(self) def lineReeived(self, line): print "$ got msg [%s]\r\n" % line def connectionLost(self, reason): reactor.stop() # 팩토리 class TestFactory(ClientFactory): protocol = TestClient def __init__(self): self.startFactory() def ..
에서 Twisted Matrix 패키지를 다운로드 받아 설치하는데는 별다른 복잡한 과정이 필요하지 않다. 그냥 다운받아서 실행하면 끝. Blocking IO 방식의 통신 모듈만 썼었는데, 이번 기회에 Non-blocking IO를 파이썬으로 시도하게 되었다. 파이썬의 기본 모듈만 써서 비동기 통신을 구현할 수도 있으나, 편의성을 제공하는 유명한 framework이 존재하여, 이를 써보게 되었다. 나 말고, 다른 사람들은 이미 Twisted를 쓰고 있기 때문이기도 하다. 공식 사이트의 reference에 나와 있는 예제를 통해, TCP 서버를 순식간에 만들어 낼 수 있다. Factory 패턴과 Reactor 패턴을 써서, 하라는 대로만 하면 순식간에 간단한 서버를 만들어 준다. 세션 유지를 위한 Alive..