线程内的龙卷风回调

时间:2018-11-28 15:25:06

标签: python callback threadpool tornado

在下面的示例代码中,我试图创建一个带有线程池的Web服务器来处理get请求。在send_result()(由线程调用)中,我使用了tornado回调,正如文档所说的那样使用主线程触发完成或在请求上写。

线程安全文档链接:http://www.tornadoweb.org/en/stable/web.html#thread-safety-notes

如果我调用API localhost:4400 / ,它将停止。我没有收到服务器的任何响应

请帮助我,我在做什么错了?

提前谢谢!

import tornado.httpserver
import tornado.web
from tornado.ioloop import IOLoop
from tornado.web import asynchronous
from multiprocessing.dummy import Pool as ThreadPool

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/', DataHandler)
        ]
        tornado.web.Application.__init__(self, handlers)

class BaseHandler(tornado.web.RequestHandler):

    def handle_error(self, ex):
        def to_do():
            self.set_status(500)
            self.finish(str(ex))
        IOLoop.instance().add_callback(callback=to_do)

    def send_result(self, ret_val):
        def to_do():
            self.set_status(200)
            self.finish(ret_val)
        IOLoop.instance().add_callback(callback=to_do)

class DataHandler(BaseHandler):
    @asynchronous
    def get(self):
        def to_do():
            try:
                self.send_result("hi")
            except Exception as ex:
                self.handle_error(ex)
        pool.apply_async(to_do)

pool = None

def main():
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(4400)
    global pool
    pool = ThreadPool(10)
    print("Server started and listening on 4400")
    IOLoop.instance().start()

if __name__ == "__main__":
    main()

0 个答案:

没有答案