如何用tornado.gen.Return返回dict

时间:2017-10-10 02:32:20

标签: python dictionary tornado

环境: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,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

调用协同程序时,您必须使用yield(在@gen.coroutine)或await(在async def函数中)关键字中设置的功能:

data = yield check_username_password(username, password)