Python futures : How do I get the json from a future object in Tornado? -
this post
handler :
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 imported imports.py instantiated imported class 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 persist : ") print (model)
the get_model
method uses models
makes db query , returns future object :
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 future object in console :
<tornado.concurrent.future object @ 0x7fbb147047b8>
how can convert json ?
to resolve future
actual value, yield
inside coroutine:
@gen.coroutine def begin(self, model_id): model = yield self._persist.get_model(model_id) print ("model persist : ") print (model)
any function calls coroutine must coroutine, , must yield
return value of coroutine return value:
@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 follow these rules, begin with, follow these basic rules.
for more information calling coroutines coroutines, see refactoring tornado coroutines.
Comments
Post a Comment