Python 使用tornado.web.RequestHandler的简单多线程示例

Python 使用tornado.web.RequestHandler的简单多线程示例,python,asynchronous,tornado,Python,Asynchronous,Tornado,我有一个神秘的\u库,提供了一个长时间的同步功能查询\u资源 然后我有下面的代码,它应该异步获取资源: import tornado.ioloop import tornado.web import threading from mysterious_library import query_resource_for_a_long_time, ResourceNotFoundException def resource_fetcher(set_status, finish): try

我有一个
神秘的\u库
,提供了一个长时间的同步功能
查询\u资源

然后我有下面的代码,它应该异步获取资源:

import tornado.ioloop
import tornado.web

import threading
from mysterious_library import query_resource_for_a_long_time, ResourceNotFoundException

def resource_fetcher(set_status, finish):
    try:
        resource = query_resource_for_a_long_time()

    except ResourceNotFoundException:
        tornado.ioloop.IOLoop.instance().add_callback(set_status, 404)
        tornado.ioloop.IOLoop.instance().add_callback(finish, 'not found')

    else:
        tornado.ioloop.IOLoop.instance().add_callback(set_status, 200)
        tornado.ioloop.IOLoop.instance().add_callback(finish, str(resource))

class Handler(tornado.web.RequestHandler):

    @tornado.web.asynchronous
    def get(self):
        threading.Thread(
            target=resource_fetcher,
            args=[self.set_status, self.finish]
        ).start()


tornado.web.Application([
    (r'.*', Handler),
]).listen(8765)
tornado.ioloop.IOLoop.instance().start()
但是,在
query\u resource\u for\u a\u long\u time
返回之前,该过程似乎被阻塞,尽管该函数在单独的线程中运行


我是tornado新手,我想知道是否可以同时处理这些请求。

是的,请按照说明使用ThreadPoolExecutor:

请注意,在测试此功能时,您只能从浏览器一次运行两个查询:


。。。因此,如果您想向自己证明您可以从Tornado一次在多个线程中运行神秘的长时间运行函数,请尝试wget或curl。

是的,请按照说明使用ThreadPoolExecutor:

请注意,在测试此功能时,您只能从浏览器一次运行两个查询:

。。。因此,如果您想证明自己可以从Tornado一次在多个线程中运行神秘的长时间运行函数,请尝试wget或curl