lolu
lolu

Reputation: 370

tornado reverse url with post request

I have a report service in tornado application. I would like to re-use the function that creates reports from a report Json.

Meaning, in the new handler that "regenerate" existing report, I would like to reuse an existing handler that knows how to create reports from a Json.

server.py:

def create_server():
return tornado.web.Application([
    (r"/task", generator.GenHandler),
    (r"/task/(.+)", generator.GenHandler),

    url(r"/regenerate_task", generator.GenHandler, name="regenerate_task"),
    url(r"/regenerate_task/(.+)", generator.GenHandler, name="regenerate_task"),

    (r"/report_status/regenerate", report_status.Regenerate)

genHandler.class:

class GenHandler(tornado.web.RequestHandler):
    async def post(self):
        try:
            LOGGER.info(str(self.request.body))
            gen_args = self.parsed_body
           # create here report using the parsed body

and this is the handler I am trying to create. It will take a saved json from DB and create a completely new report with the original report logic.

class Regenerate(tornado.web.RequestHandler):
    async def post(self):
        rep_id = self.request.arguments.get('rep_id')[0].decode("utf-8") if self.request.arguments.get('rep_id') \
            else 0

        try:
            report = db_handler.get_report_by_id(rep_id)
            if *REPORT IS VALID*:
                return self.reverse_url("regenerate_task", report)
            else:
                report = dict(success=True, report_id=rep_id, report=[])

        except Exception as ex:
            report = dict(success=False, report_id=rep_id, report=[], error=str(ex))

        finally:
            self.write(report)

Right now, nothing happens. I just get the JSON I needed, but no entry for GenHandler and no report being regenerated

Upvotes: 0

Views: 587

Answers (1)

Fine
Fine

Reputation: 2154

  1. reverse_url returns a url for specified alias, but doesn't invoke it.
  2. You have such problem where you have to invoke another handler because you have poor code organisation. Storing a report generation code (i.e. business logic) in handler is a bad practice and you should move it to a separate class (which is usually called a Controller in a MVC pattern and handler is a View) or at least separate method and then reuse it in your Renegate handler.

Upvotes: 2

Related Questions