我讀過,我不應該在扭曲的項目中使用pymongo,因爲pymongo不是異步的。我在理解這個整個想法時遇到了問題......據我所知,我應該把我的代碼延遲以避免阻止我的應用程序。我對嗎?所以所有的數據庫操作都應該在Deferred方法中?看看這個:在Twisted中使用MongoDB。爲什麼我不應該使用pymongo?
class Tracker(protocol.Protocol):
def __init__(self, factory):
self.db = factory.db
def dataReceived(self, data):
deferred = threads.deferToThread(self.handle, data)
deferred.addCallback(self.on_success)
deferred.addErrback(self.on_error)
def on_success(self, _None, response):
self.transport.write(response)
def on_error(self, failure):
logging.error('Error in deferred: %s' % failure.getErrorMessage())
def handle(self, tracker, input):
self.db.buffer.insert({ }) # writing data to database
return 'success'
class Server(protocol.Factory):
def __init__(self):
self.client = pymongo.MongoClient()
self.db = self.client.my_database
def buildProtocol(self, addr):
return Client(self)
reactor.listenTCP(6969, Server())
我做得對嗎?