Python / Tornado - 调用classmethod

时间:2016-05-09 15:29:21

标签: python python-2.7 tornado class-method motorengine

鉴于这个简单的代码,我在其中声明了一个类和一个函数。在主要我尝试调用该函数,但没有进行调用。我没有收到任何错误,但如果我打印一个打印件,以便知道调用是否发生了什么。

模型

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没有任何反应。

1 个答案:

答案 0 :(得分:1)

createBalance装饰gen.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,等待它完成。