Python期货:如何从Tornado中的未来对象中获取json?

时间:2015-08-16 20:32:48

标签: python tornado python-3.4 concurrent.futures motorengine

这是post处理程序:

handler.py

from imports import logic

@gen.coroutine
def post(self):
    data = self.request.body.decode('utf-8')
    params = json.loads(data)
    model_id= params['model_id']
    logic.begin(model_id)

从imports.py导入logic对象,从导入的类Logic实例化

imports.py:

import Models
import Logic

class Persist(object):
    def getModel(self, model_id):
        model = Models.findByModelId(model_id)
        return model


persist = Persist()
logic = Logic(persist)

logic.py

class Logic(object):
    def __init__(self, persist):
        self._persist = persist

    def begin(self, model_id):
         model = self._persist.get_model(model_id)
         print ("Model from persist : ")
         print (model)

get_model方法使用Models进行数据库查询并返回未来对象:

model.py

from motorengine.document import Document

class Models(Document):
    name = StringField(required=True)

def findByModelId(model_id):
    return Models.objects.filter(_id=ObjectId(model_id)).find_all()

这将在控制台中打印未来对象:

<tornado.concurrent.Future object at 0x7fbb147047b8>

如何将其转换为json?

1 个答案:

答案 0 :(得分:3)

要将Future解析为实际值,请在协程中yield

@gen.coroutine
def begin(self, model_id):
     model = yield self._persist.get_model(model_id)
     print ("Model from persist : ")
     print (model)

任何调用协同程序的函数都必须是一个协程,并且必须yield协程的返回值才能获得其返回值:

@gen.coroutine
def post(self):
    data = self.request.body.decode('utf-8')
    params = json.loads(data)
    model_id = params['model_id']
    model = yield logic.begin(model_id)
    print(model)

更高级的编码模式不需要遵循这些规则,但首先,请遵循这些基本规则。

有关从协同程序调用协同程序的更多信息,请参阅Refactoring Tornado Coroutines