林公
Tornado使用motor异步连接mongodb:
import os
import tornado.ioloop
from tornado import gen
import tornado.web
import motor
class Index(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
res = yield self.application.db.coll.find_one() # 异步连接主要看这句
self.write( str(res) )
class Application(tornado.web.Application):
def __init__(self):
handlers = ([
("/index", Index),
])
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
cookie_secret='zhuanfou.com_lin_gong',
debug=False,
)
super(Application, self).__init__(handlers, **settings)
conn = motor.motor_tornado.MotorClient("127.0.0.1", 27017) # mongodb服务的地址和端口
self.db = conn.testdb # 比如连接testdb
if __name__ == "__main__":
app = Application()
app.listen(80)
tornado.ioloop.IOLoop.current().start()
其实,用一种白话文的思路来说,其实类似mongodb、elasticsearch等这些数据库,它们本身就有提供rest api这种形式的访问接口,所以,可以把各种数据库连接器想象成帮助你把你的数据库操作转化成符合rest api的各种url,然后异步访问能力,还是来源于tornado等异步服务器自身。