I am currently using Tornado and asyncmongo to create a website that accesses a mongodb. Everything is working great except when I need to make multiple requests to mongodb within in a single request to my handler. I would like to keep all my database call asynchronous so that there is no blocking on the server.
How can I accomplish this? There are several cases in which I need to retrieve different documents from multi开发者_StackOverflowple collections. I also sometimes need to use data that I retrieved from my first query in the second such as a foreign key. I will also need the data from both requests when I render my template.
Thanks!
Have each request trigger a different callback?
e.g. (I didn't test this, and I'm not familiar with asyncmongo, so it probably contains errors):
import asyncmongo
import tornado.web
class Handler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self, id):
self.id = id
self.db = asyncmongo.Client(pool_id='mypool', host='localhost',
port=27107, dbname='mydb')
self.db.users.find_one({'username': self.current_user},
callback=self.on_user)
def on_user(self, response, error):
if error:
raise tornado.web.HTTPError(500)
self.user = response
self.db.documents.find_one({'id': self.id, 'user': self.user},
callback=self.on_document)
def on_document(self, response, error):
if error:
raise tornado.web.HTTPError(500)
self.render('template', first_name=self.user['first_name'],
document=response)
精彩评论