How do you call function after client finishes dow

2019-08-05 07:27发布

问题:

I would like to be able to run some cleanup functions if and only if the client successfully completes the download of a file I'm serving using Tornado.

I installed the firefox throttle tool and had it slow the connection down to dialup speed and installed this handler to generate a bunch of rubbish random text:

class CrapHandler(BaseHandler):
    def get(self, token):
        crap = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(100000))
        self.write(crap)
        print "done"

I get the following output from tornado immediately after making the request:

done
I 100524 19:45:45 web:772] 200 GET /123 (192.168.45.108) 195.10ms

The client then plods along downloading for about 20 seconds. I expected that it would print "done" after the client was done.

Also, if I do the following I get pretty much the same result:

class CrapHandler(BaseHandler):
    @tornado.web.asynchronous
    def get(self, token):
        crap = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(100000))
        self.write(crap)
        self.finish()
        print "done"

Am I missing something fundamental here? Can tornado even support what I'm trying to do? If not, is there an alternative that does?

回答1:

I believe you are looking for something that runs in the on_connection_close request handler method which you can override.

Keep in mind that if you are running behind nginx, tornado will respond to nginx immediately, and nginx will slowly respond to the client.

Also, keep in mind that adding @tornado.web.asynchronous doesn't actually make a request asynchronous. It only set's up the request to use tornado.http.AsyncHTTPClient.