import json
import tornado.web
from threading import Thread

#handler in a separate thread
class threaded_test_handler:

  #thread function
  @staticmethod
  def handle_request(Handler,Data):
    #do something with Data
    #...
    Handler.write(Some_Result)
    Handler.finish()
  #end of handle request
#end of threaded test handler

#tornado request handler
class test_handler(tornado.web.RequestHandler):
  
  #handle POST
  @tornado.web.asynchronous
  def post(this):
    Data = json.loads(this.request.body)
    Handler_Thread = Thread(
      target=threaded_test_handler.handle_request,
      args  =(this,Data)
    )
    Handler_Thread.start()
  #end of post  
#end of test handler

Notes:
The ‘post‘ method in test_handler must come with @tornado.web.asynchronous to tell Tornado not to finish request at the end of ‘post‘ method. The static method handle_request in threaded_test_handler will finish the request at the end of itself.

Advertisements