Search code examples
pythontornado

How to drop request in tornado?


In order to test my client, I want to make some of the HTTP request sent by my client doesn't get any response.

For example, I want every request should have cookie topsession, if not, no response.

class EchoHandler(tornado.web.RequestHandler):
    def get(self):
        if not self.get_cookie("topsession"):
            ###TODO
        else:
            self.write("0")

Solution

  • Decorate your method with asynchronous and never call finish:

    class EchoHandler(tornado.web.RequestHandler):
        @tornado.web.asynchronous
        def get(self):
            if not self.get_cookie("topsession"):
                pass
            else:
                self.finish("0")
    

    As the docs for asynchronous say:

    If this decorator is given, the response is not finished when the method returns. It is up to the request handler to call self.finish() to finish the HTTP request.

    So, if you simply return without calling finish, the client waits forever (or until its client-side socket timeout) for a response without receiving one. If you do this, however, you must call finish in the other branch of the if statement.

    On the other hand if by "no response" you mean an error, you could do instead:

    class EchoHandler(tornado.web.RequestHandler):
        def get(self):
            if not self.get_cookie("topsession"):
                raise tornado.web.HTTPError(401)  # Unauthorized.
            else:
                self.write("0")