I'm having trouble saving MotorEngine instance using Tornado handler. Below are excerpts of code which I shortened for brevity.
if I replace motorengine
imports with mongoengine
the instance gets saved properly.
# model
from motorengine.document import Document
from motorengine.fields import *
class Test(Document):
nameTest = StringField(required=True)
numberTest = DecimalField(required=True)
boolTest = BooleanField(required=True)
# handler
class TestHandler(BaseHandler):
@tornado.gen.coroutine
def post(self, *args, **kwargs):
response = self._service.save_test()
print(response)
self.write('')
self.finish()
# save method
from models import Test
def save_test(self):
yield Test.objects.create(nameTest="foobar", boolTest=False, numberTest=123)
Are there any apparent errors in my code? Async programming is not my strong side.
:EDIT:
As per Ben's answer, this is the code that works
# handler
@tornado.gen.coroutine
def post(self, *args, **kwargs):
yield self._service.save_test()
# save method
@tornado.gen.coroutine
def save_test(self):
yield Test.objects.create(nameTest="foobar", boolTest=False, numberTest=123)
save_test
(and any function which uses yield
in this way) must have the @gen.coroutine
decorator, and when you call it (or any other coroutine) in post()
you must use yield save_test()