简体   繁体   中英

tornado web http request blocks other requests, how to not block other requests

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM