def on_response(self, resp): body = json.loads(resp.body) if body == None: self.write(‘error‘) else: self.write(body) return
注意: 1. 只在每个响应处理的函数(如get, post, put,delete)前加修饰器@tornado.web.asynchronous 和 @tornado.gen.coroutine, 不要在初始函数 initialize(self)前加修饰器,不然会造成各种程序错误 2. 在 on_response(self, resp)函数中,如果使用了 self.wirte()或self.render()函数,就不要使用 self.finish()函数, 不然,会报异常: raise RuntimeError("finish() called twice. May be caused " RuntimeError: finish() called twice. May be caused by using async operations without the @asynchronous decorator. 如果没有用self.wirte()或self.render()函数,就要使用self.finish()函数
链接 https://github.com/bitly/asyncmongo AsyncMongo is an asynchronous library for accessing mongo which is built on the tornado ioloop. 1). Build Status Installation Installing: pip install asyncmongo
2). Usage asyncmongo syntax strives to be similar to pymongo.
import asyncmongo import tornado.web
class Handler(tornado.web.RequestHandler): @property def db(self): if not hasattr(self, ‘_db‘): self._db = asyncmongo.Client(pool_id=‘mydb‘, host=‘127.0.0.1‘, port=27017, maxcached=10, maxconnections=50, dbname=‘test‘) return self._db
@tornado.web.asynchronous def get(self): self.db.users.find({‘username‘: self.current_user}, limit=1, callback=self._on_response) # or # conn = self.db.connection(collectionname="...", dbname="...") # conn.find(..., callback=self._on_response) def _on_response(self, response, error): if error: raise tornado.web.HTTPError(500) self.render(‘template‘, full_name=response[‘full_name‘]) 3). About Some features are not currently implemented: directly interfacing with indexes, dropping collections retrieving results in batches instead of all at once (asyncmongo‘s nature means that no calls are blocking regardless of the number of results you are retrieving) tailable cursors #15
4). Requirements The following two python libraries are required pymongo version 1.9+ for bson library tornado
3. Motor
http://motor.readthedocs.org/en/stable/ Motor: Asynchronous Python driver for Tornado and MongoDB About Motor presents a Tornado callback- or Future-based API for non-blocking access to MongoDB. The source is on GitHub and the docs are on ReadTheDocs. “Motor uses a clever greenlet-based approach to fully support both synchronous and asynchronous interfaces from a single codebase. It’s great to see companies like MongoDB produce first-party asynchronous drivers for their products.” —Ben Darnell, Tornado maintainer
Install with: $ pip install motor Post questions about Motor to the mongodb-user list on Google Groups. For confirmed issues or feature requests, open a case in Jira in the “MOTOR” project.