[英]In tornado, how can I use static_url() in a class without tornado.web.RequestHandler?
[英]simple multithreading example with tornado.web.RequestHandler
我有一個mysterious_library
,提供同步功能query_resource_for_a_long_time
。
然后,我有下面的代碼應該異步獲取資源:
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_resource_for_a_long_time
返回。
我是龍卷風的新手,我想知道是否可以同時處理這些請求。
是的,按照說明使用ThreadPoolExecutor:
http://www.tornadoweb.org/en/stable/guide/coroutines.html#calling-blocking-functions
請注意,在測試時,只能一次從瀏覽器運行幾個查詢:
...因此,如果您想證明自己可以從Tornado一次在多個線程中運行神秘的長期運行函數,請嘗試使用wget或curl。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.