Tornado - 将RequestHandler传递给一个带回调的方法,以异步调用RequestHanlder.write

时间:2012-03-07 17:54:08

标签: python mongodb asynchronous tornado elasticsearch

我正在努力让Tornado-Elasticsearch-Mongodb设置正常运行。 Tornado.web.RequestHandler收到搜索请求后,查询将通过REST API使用Tornado.curl_httpclient.CurlAsyncHTTPClient.fetch()发送到elasticsearch服务器。 fetch使用结果调用回调,因此此时RequestHandler超出范围,因此我无法再写入HTTPResponse。我想我可以在RequestHandler子类中嵌套回调,但我的印象是这不是异步编程中的最佳选择。是否有一种神奇的python方式将我的方法结合在一起?以下是我想加入的部分:

from pymongo import Connection
from pymongo.objectID import ObjectId
from tornado.curl_httpclient import CurlAsyncHTTPClient
from tornado.httpclient import HTTPRequest
from tornado.web import RequestHandler, Application
from tornado.ioloop import IOLoop

import json


mongo_conn = Connection()
db = 'a_db'
collection = 'a_collection'
es_conn = CurlAsyncHTTPClient()

def get_mongo_data(id_list):
    print list(mongo_conn[db][collection].find({"_id":{"$in":id_list}}))
    # want to RequestHandler.write() here

def handle_search(response):
    if response.error:
        print "Error", response.error
    else:
        body = json.loads(response.body)
        id_list = []
        results = body['hits']['hits']
        if len(results) > 0:
            collection = results[0]['_type']
            for r in results:
                id_list.append(ObjectId(r['_id']))
            if len(id_list) > 0:
                get_mongo_data(id_list)
            else:
                # want RequestHandler.write("no matches found")
        else:
            # RequestHandler.write("no matches found")

def search(query):
    url = '127.0.0.1:9250/%s/%s/_search' % (db, collection)
    content = '{"query":{"term":{"field":"%s"}}}' % query 
    request = HTTPRequest(url, body=content, allow_nonstandard_methods=True)
    es_conn.fetch(request, handle_search)

class SearchHandler(RequestHandler):
    def get(self):
        search('foo') # hack for now

if __name__=='__main__':
    application = Application([
        (r'/', SearchHandler),
    ])
    application.listen(8888)
    IOLoop.instance().start()

0 个答案:

没有答案