【问题标题】:Python futures : How do I get the json from a future object in Tornado?Python 期货:如何从 Tornado 中的未来对象获取 json?
【发布时间】:2015-08-16 20:32:47
【问题描述】:

这是一个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)

logic 对象是从 imports.py 导入的,它是从导入的类 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 ?

【问题讨论】:

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


    【解决方案1】:

    要将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

    【讨论】:

      猜你喜欢
      • 2013-03-23
      • 1970-01-01
      • 2017-03-29
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多