0
votes

Using Tornado, I have a POST request that takes a long time as it makes many requests to another API service and processes the data. This can take minutes to fully complete. I don't want this to block the entire web server from responding to other requests, which it currently does.

I looked at multiple threads here on SO, but they are often 8 years old and the code does not work anylonger as tornado removed the "engine" component from tornado.gen.

Is there an easy way to kick off this long get call and not have it block the entire web server in the process? Is there anything I can put in the code to say.. "submit the POST response and work on this one function without blocking any concurrent server requests from getting an immediate response"?

Example: main.py

def make_app():
        return tornado.web.Application([
                (r"/v1", MainHandler),
                (r"/v1/addfile", AddHandler, dict(folderpaths = folderpaths)),
                (r"/v1/getfiles", GetHandler, dict(folderpaths = folderpaths)),
                (r"/v1/getfile", GetFileHandler, dict(folderpaths = folderpaths)),
                ])




if __name__ == "__main__":
        
        app = make_app()
        sockets = tornado.netutil.bind_sockets(8888)
        tornado.process.fork_processes(0)
        tornado.process.task_id()
        server = tornado.httpserver.HTTPServer(app)
        server.add_sockets(sockets)
        tornado.ioloop.IOLoop.current().start()

addHandler.py



class AddHandler(tornado.web.RequestHandler):
    
    def initialize(self, folderpaths):
        self.folderpaths = folderpaths


    def blockingFunction(self):
        time.sleep(320)
        post("AWAKE")

    def post(self):

        user = self.get_argument('user')
        folderpath = self.get_argument('inpath')
        outpath = self.get_argument('outpath')
        workflow_value = self.get_argument('workflow')

        status_code, status_text = validateInFolder(folderpath)

        
        if (status_code == 200):
            logging.info("Status Code 200")
            result = self.folderpaths.add_file(user, folderpath, outpath, workflow_value)
            self.write(result)
            self.finish()

            #At this point the path is validated.
            #POST response should be send out. Internal process should continue, new 
            #requests should not be blocked
            
            self.blockingFunction()

Idea is that if input-parameters are validated the POST response should be sent out. Then internal process (blockingFunction()) should be started, that should not block the Tornado Server from processing another API POST request.

I tried defining the (blockingFunction()) as async, which allows me to process multiple concurrent user requests - however there was a warning about missing "await" with async method.

Any help welcome. Thank you

1
Run the blocking func in a separate thread using run_in_executor. If you're just sending out http requests (and not doing any cpu blocking task), you'll get better performance using AsyncHTTPClient than threads. - xyres
Hello @xyres Thank you for your response. I looked into 'run_in_executor' I tried calling the function like so: await loop.run_in_executor(None, self.blockingFunction()) while declaring the def post(self) as 'async' - and initializing the loop like this in def post(self): loop = asyncio.get_running_loop() - however I am still running into the same problem. Any idea what should be changed? --- (P.S.: Im Writing values int a DB later, so I think run_in_executor looks more promising than using AsynchHTTPClient) - DeltaFi
EDIT: tornadoweb.org/en/stable/faq.html My original live blockingFunction() has parameters, which need to be called like this: await loop.run_in_executor(None, self.blockingFunction, param1, param2) With this changed it seems to be working. Thank you @xyres - DeltaFi
the method,xyres say, may be better.run_in_executor is a better way when you do any cpu blocking task(You say , just may request,not cpu blocking).It use Thread Pool or Process pool inside, it will use more resources. - bigpangl

1 Answers

0
votes
class AddHandler(tornado.web.RequestHandler):
    
    def initialize(self, folderpaths):
        self.folderpaths = folderpaths


    def blockingFunction(self):
        time.sleep(320)
        post("AWAKE")

    async def post(self):

        user = self.get_argument('user')
        folderpath = self.get_argument('inpath')
        outpath = self.get_argument('outpath')
        workflow_value = self.get_argument('workflow')

        status_code, status_text = validateInFolder(folderpath)

        
        if (status_code == 200):
            logging.info("Status Code 200")
            result = self.folderpaths.add_file(user, folderpath, outpath, workflow_value)
            self.write(result)
            self.finish()

            #At this point the path is validated.
            #POST response should be send out. Internal process should continue, new 
            #requests should not be blocked

            await loop.run_in_executor(None, self.blockingFunction)

            #if this had multiple parameters it would be 
            #await loop.run_in_executor(None, self.blockingFunction, param1, param2)

Thank you @xyres

Further read: https://www.tornadoweb.org/en/stable/faq.html