gpt4 book ai didi

Python future : How do I get the json from a future object in Tornado?

转载 作者:行者123 更新时间:2023-11-30 21:49:47 25 4
gpt4 key购买 nike

这是一个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实例化的

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)

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

模型.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()

这会在控制台中打印 future 的对象:

<tornado.concurrent.Future object at 0x7fbb147047b8>

如何将其转换为 json ?

最佳答案

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

关于Python future : How do I get the json from a future object in Tornado?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32039646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com