Search code examples
pythonmongodbsortingtornadopymongo

Tornado python - how to sort queries to mongoDB using pymongo?


Would like to sort a simple query, but not sure how this works with "gen.task", as it takes a method as arg1 and param as arg2.

This works more than fine :

response, error = yield gen.Task(db.client().collection.find, {"user_id":user_id})
if response:
    #blablabla

But then how do I give it the sort()?

UPDATE : This now throws a 'callback must be callable' error. Which seems to be some other issue with Tornado now.

def findsort(self, find, callback):
    return callback(db.client().collection.find(find).sort({"myfield":1}))

@gen.engine
def anotherfunction(self):
    response, error = yield gen.Task(self.findsort, {"user_id":user_id})

Solution

  • Use asyncmongo, it works perfectly with gen.

    After juggling you will get something like this:

    DB = asyncmongo.Client()
    
    class MainHandler(tornado.web.RequestHandler):
        @tornado.web.asynchronous
        @gen.engine
        def get(self):
            result, error = yield gen.Task(DB.collection.find, {}, limit=50, sort=[('myfield', 1)])
    

    And about 'callback must be callable'.. When working with gen - always describe +1 argument in functions, which is called by gen.Task.

    def findsort(self, find, params, callback): #here we recieve self + 3 args, if we remove params - callback will contain {"user_id":user_id} 
        return callback(db.client().collection.find(find).sort({"myfield":1}))
    
    @gen.engine
    def anotherfunction(self):
        response, error = yield gen.Task(self.findsort, {"user_id":user_id}) #we see 2 args, but it passes 3 args to findsort