[英]Python futures : How do I get the json from a future object in Tornado?
This is a post
handler : 这是一个
post
处理程序:
handler.py 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)
The logic
object is imported from imports.py where it is instantiated from an imported class Logic
logic
对象是从imports.py导入的,该对象是从导入的Logic
类实例化的
imports.py : 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)
the get_model
method uses Models
which makes a DB query and returns the future object : get_model
方法使用Models
进行数据库查询并返回get_model
对象:
model.py : 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()
This prints a future object in console : 这将在控制台中打印将来的对象:
<tornado.concurrent.Future object at 0x7fbb147047b8>
How can I convert it to json ? 如何将其转换为json?
To resolve a Future
into an actual value, yield
it inside a coroutine: 要将
Future
解析为实际值,请在协程中yield
它:
@gen.coroutine
def begin(self, model_id):
model = yield self._persist.get_model(model_id)
print ("Model from persist : ")
print (model)
Any function that calls a coroutine must be a coroutine, and it must yield
the return value of the coroutine to get its return value: 任何调用协程的函数都必须是协程,并且必须
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)
More advanced coding patterns don't need to follow these rules, but to begin with, follow these basic rules. 更高级的编码模式不需要遵循这些规则,但是首先要遵循这些基本规则。
For more information about calling coroutines from coroutines, see Refactoring Tornado Coroutines . 有关从协程调用协程的更多信息,请参见重构龙卷风协程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.