1

这是一个post处理程序:

处理程序.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)

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

进口.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)

逻辑.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它进行数据库查询并返回未来对象:

模型.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 ?

4

1 回答 1

4

要将 a 解析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)

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

有关从协程调用协程的更多信息,请参阅重构 Tornado协程。

于 2015-08-17T02:53:32.973 回答