二:连接mongodb
db = motor.MotorClient('10.28.0.163').open_sync().project_test
相同情况下使用pymongo的命令为:
db = pymongo.Connection('10.28.0.163').project_test
#这样是blocking的
#原来的pymongo操作
find = db.test.find_one({'key':'value'})
new = db.test.update({'spec':'spec'},{'$set':{'key':'value'}})
#motor操作
find = db.test.find_one({'key':'value'},callback=_on_result1)
new = db.test.update({'spec':'spec'},{'$set':{'key':'value'}},callback = _on_result2)
@tornado.web.asynchronous
def _on_result1(result,error):
if error:
do something
do something
def _on_result1(result,error):
if error:
do something
do something
关于某些mongodb操作的回调函数的使用,motor有特别的规定,如find()需要调用motor的to_list(),具体情况需要用时请查询motor文档http://motor.readthedocs.org/en/stable/index.html
#motor操作
import tornado
import motor
class someHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def post(self):
......do something....
self.operation(db)
....do something ....
@tornado.gen.engine
def operation():
find = yield motor.Op(db.test.find_one,{'key':'value'})
new =yield motor.Op(db.test.update,{'spec':'spec'},{'$set':{'key':'value'}})