簡體   English   中英

Tornado阻止異步請求

[英]Tornado blocking asynchronous requests

使用Tornado,我有一個Get請求需要很長時間,因為它向另一個Web服務發出許多請求並處理數據,可能需要幾分鍾才能完全完成。 我不希望這阻止整個Web服務器響應其當前所做的其他請求。

據我了解,Tornado是單線程並同步執行每個請求,即使它異步處理它們(仍然在那個位置上混淆)。 長進程的某些部分可能是暫停點,以允許服務器處理其他請求(可能的解決方案?)。 我在Heroku上運行它只有一個工作者,所以不確定如何轉換為產生一個新的線程或多處理,我沒有使用python的經驗。

這是我正在嘗試做的事情:客戶端進行get調用以啟動進程,然后我每5秒循環一次另一個get調用以檢查狀態並使用新信息更新頁面(長輪詢也可以運行但運行進入同一問題)。 問題是啟動長進程會阻止所有新的get請求(或新的長輪詢會話),直到它完成為止。

是否有一種簡單的方法可以啟動這個長時間的呼叫,而不是讓它在整個過程中阻止整個Web服務器? 有沒有什么我可以在代碼中說..“暫停,處理待處理的請求然后繼續”?

我需要在ProcessHandler上發起get請求。 然后我需要繼續能夠在ProcessHandler運行時查詢StatusHandler。

例:

class StatusHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
       self.render("status.html")

class ProcessHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
       self.updateStatus("0")
       result1 = self.function1()
       self.updateStatus("1")
       result2 = self.function2(result1)
       self.updateStatus("2")
       result3 = self.function3(result2)
       self.updateStatus("3")
       self.finish()

這是一個完整的樣本Tornado應用程序,它使用Async HTTP客戶端和gen.Task模塊來簡化操作。

如果您在文檔中閱讀有關gen.Task更多信息,您會看到您實際上可以同時分派多個請求。 這是使用Tornado的核心理念,其中一切都沒有阻塞,仍然保持一個單一的過程。

更新:我添加了一個Thread處理程序來演示如何將工作分配到第二個線程並在完成后接收callback()

import os
import threading
import tornado.options
import tornado.ioloop
import tornado.httpserver
import tornado.httpclient
import tornado.web
from tornado import gen
from tornado.web import asynchronous

tornado.options.define('port', type=int, default=9000, help='server port number (default: 9000)')
tornado.options.define('debug', type=bool, default=False, help='run in debug mode with autoreload (default: False)')

class Worker(threading.Thread):
   def __init__(self, callback=None, *args, **kwargs):
        super(Worker, self).__init__(*args, **kwargs)
        self.callback = callback

   def run(self):
        import time
        time.sleep(10)
        self.callback('DONE')

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", IndexHandler),
            (r"/thread", ThreadHandler),
        ]
        settings = dict(
            static_path = os.path.join(os.path.dirname(__file__), "static"),
            template_path = os.path.join(os.path.dirname(__file__), "templates"),
            debug = tornado.options.options.debug,
        )
        tornado.web.Application.__init__(self, handlers, **settings)

class IndexHandler(tornado.web.RequestHandler):
    client = tornado.httpclient.AsyncHTTPClient()

    @asynchronous
    @gen.engine
    def get(self):
        response = yield gen.Task(self.client.fetch, "http://google.com")

        self.finish("Google's homepage is %d bytes long" % len(response.body))

class ThreadHandler(tornado.web.RequestHandler):
    @asynchronous
    def get(self):
        Worker(self.worker_done).start()

    def worker_done(self, value):
        self.finish(value)

def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(tornado.options.options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

科布拉斯的解決方案很棒。 這是一個利用tornado.gen的替代方案

import tornado.ioloop
import tornado.web
import tornado.gen
import tornado.concurrent
import time
from threading import Thread
from functools import wraps

def run_async(func):
  @wraps(func)
  def async_func(*args, **kwargs):
    func_hl = Thread(target = func, args = args, kwargs = kwargs)
    func_hl.start()
    return func_hl

  return async_func

@run_async
def sleeper(callback):
  i = 0
  while i <= 10:
    print i
    time.sleep(1)
    i += 1
  callback('DONE')


class MainHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def get(self):
        response = yield tornado.gen.Task(sleeper)
        self.write(response)
        self.finish()

class OtherHandler(tornado.web.RequestHandler):
    def get(self):
        self.write('hello world')
        print 'in other'
        self.finish()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM