tornado web http request blocks other requests, ho

2019-07-07 06:11发布

问题:

import tornado.web
import Queue

QUEUE = Queue.Queue()

class HandlerA( tornado.web.RequestHandler ):
    def get(self):
        global QUEUE
        self.finish(QUEUE.get_nowait())

class HandlerB( tornado.web.RequestHandler ):
    def get(self):
        global QUEUE
        QUEUE.put('Hello')
        self.finish('In queue.')

Problem: HandlerA blocks HandlerB for 10 seconds.

  1. Browser A handled by HandlerA and waits...
  2. Browser B handled by HandlerB and waits.... till timeout exceptions

Goal

  1. Browser A handled by HandlerA and waits...
  2. Browser B handled by HandlerB and returns
  3. HandlerA returns after dequeuing

Is this an issue with Non-blocking, async, epoll or sockets?

Thanks!

UPDATE:

I updated this code with a new thread to handle the Queue.get_nowait() request. Which I fear is a HORRIBLE solution considering I'm going to have thousands of requests at once and would therefore have thousands of threads at once. I'm considering moving to a epoll style in the near future.

class HandlerA( tornado.web.RequestHandler ):
    @tornado.web.asynchronous
    def get(self):
       thread.start_new_thread(self.get_next)

    def get_next(self):
        global QUEUE
        self.finish(QUEUE.get_nowait())

Now this is not the best way to handle it... but at least its a start.

SOLUTION

Found here Running blocking code in Tornado

回答1:

This is Python. So, time.sleep will always block the flow! In order to call action after 10 seconds with Tornado, you need to use tornado.ioloop.add_timeout function and pass callback as param. Docs for more information.