如何返回 dict with tornado.gen.Return.



环境:python 2.7.13

法典

 # coding=utf-8
    from tornado import gen
    import tornado.web
    from tornado import escape
    from DataBase import mydata
    import re

    class Login_Handler(tornado.web.RequestHandler):
        @gen.coroutine
        def get(self, username, password):
            data = check_username_password(username, password)._result
            #get the response dict first two good,last two null!!!!!!!
            self.write(escape.json_encode(data))
            self.finish()
            #self.write(escape.json_encode(check_username_password(username, password)._result))

响应dict

(前两个正确,后两个空)

    # 检查用户名密码
    @gen.coroutine
    def check_username_password(username, password):
        data = {}
        if not re.findall("^w+$", username):
            data['state'] = 0
            data['message'] = '用户名必须是大小写字母、数字或下划线组成'
            raise tornado.gen.Return(data)
            return
            #here is return good!return the dict
        if not re.findall("^w+$", password):
            data['state'] = 0
            data['message'] = '密码必须是大小写字母、数组或下划线组成'
            raise tornado.gen.Return(data)
            return
            #here is return good!retrun the dict
        cur = yield mydata.POOL.execute(
            "SELECT account_table.id,account_table.account_user,account_table.account_password,account_table.cookie_secret FROM account_table WHERE account_table.account_user='%s' AND account_table.account_password='%s';" % (
                username,
                password))
        result_value =  cur.fetchall()
        print result_value
        if not result_value:
            print '查询结果为空'
            data['state'] = 0
            data['message'] = '没有查询到数据'
            raise tornado.gen.Return(data)
            return
            #here is return null,why?
        result_key = ['id', 'account_user', 'account_password', 'cookie_secret']
        result = map(lambda value: dict(zip(result_key, value)), result_value)
        data['state'] = 1
        data['meessage'] = 'ok'
        data['result'] = result
        print data
        print dir(gen.Return(data))
        raise tornado.gen.Return(result)
        #here is return null why?

问题

tornado.gen.Return返回4次,前两次做得很好,但后两次总是返回null,谁能帮我?

调用协程时,必须使用 yield(在用 @gen.coroutine 修饰的函数中)或await(在async def函数中)关键字:

data = yield check_username_password(username, password)

最新更新