开发者

Multiple Database calls in an asynchronous request with Tornado

开发者 https://www.devze.com 2023-03-15 13:30 出处:网络
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

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消