-2

给定这个简单的代码,我在其中声明了一个类和一个函数。我主要尝试调用该函数,但未进行调用。我没有收到任何错误,但是如果我打印以了解呼叫是否发生,则什么也没有发生。

楷模

class Balance(Document):
    gross_balance = FloatField(required=True, min_value=0, default=0)

    @classmethod
    def createBalance(cls, gross_balance):
        result = yield Balance.objects.create(gross_balance = gross_balance)
        result.save()
    @classmethod
    def sayHi(cls):
        print "Hi there"

主要的

from models import Balance

class CreateBalanceHandler(tornado.web.RequestHandler):

@tornado.gen.coroutine
def post(self):
    gross_balance = self.get_argument('gross_balance')
    Balance.createBalance(gross_balance)
    Balance.sayHi()
    self.redirect('/query/{}'.format(gross_balance))

我究竟做错了什么?sayHi 函数显示它的打印,但对 createBalance 没有反应。

4

1 回答 1

1

装饰createBalancegen.coroutine在 ioloop 上运行它。等到余额被创建调用它就像yield Balance.createBalance()RequestHandler

楷模

class Balance(Document):
    gross_balance = FloatField(required=True, min_value=0, default=0)

    # classmethod must be the most outter decorator (as well as staticmethod)

    @classmethod
    @tornado.gen.coroutine
    def createBalance(cls, gross_balance):
        result = yield Balance.objects.create(gross_balance = gross_balance)
        # AFAIR save returns future and also should be yielded
        # yield. result.save()
        result.save()

    @classmethod
    def sayHi(cls):
        print "Hi there"

主要的

from models import Balance

class CreateBalanceHandler(tornado.web.RequestHandler):

    @tornado.gen.coroutine
    def post(self):
        gross_balance = self.get_argument('gross_balance')
        yield Balance.createBalance(gross_balance)
        Balance.sayHi()
        self.redirect('/query/{}'.format(gross_balance))

注意:正如我在代码片段的评论中提到的,在 motorengine 中Document.save返回Future,可能你也想要yield它,等到它完成。

于 2016-05-10T01:05:24.897 回答