从Tornado发送JSON到客户端

时间:2014-08-06 19:56:31

标签: python json tornado

我已收到并处理从客户端收到的数据,并希望以JSON格式发回回复,但客户端尚未收到回复。我的代码是:

def do_find_one(self,live):
    Info = {} 
    isAvailable = str
    count=db.userInfo.find( {'Username': live}).count()
    if  count > 0:
        isAvailable = False
        Info['valid']=isAvailable
        print False, count
        print Info
    else:
        isAvailable = True
        print True, count
    self.write(json.dumps(Info, default=json_util.default)) 

class CheckerHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def post(self):
        pi1 = self.get_argument('display')        
        do_find_one(self,pi1)

self.write(json.dumps(Info, default=json_util.default))是否有问题?

1 个答案:

答案 0 :(得分:7)

当您使用tornado.web.asynchronous装饰器时,您需要在处理程序末尾调用self.finish()并将响应发送到客户端:

class CheckerHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def post(self):
        pi1 = self.get_argument('display')        
        do_find_one(self,pi1)
        self.finish()  # Without this the client's request will hang

    def do_find_one(self,live):
        Info = {} 
        isAvailable = str
        count=db.userInfo.find( {'Username': live}).count()
        if  count > 0:
            isAvailable = False
            Info['valid']=isAvailable
            print False, count
            print Info
        else:
            isAvailable = True
            print True, count
        self.write(json.dumps(Info, default=json_util.default))