1

I have a cherrypy api that is intended to run for a long time on the server.

I have an unreliable client that can die or close connection for various reasons that are out of my control.

During the time my server api runs, I want to periodically check the status of the connection, making sure the client is still listening and abort my operation if the client has gone away.

I could not find any good place describing how to poll the connection status while serving a cherrypy request.

One example of such a long run is computing md5 of multiple big files (of tens of GBs) in chunks of small buffer (limited memory).

I don't need any solutions that shorten the runtime since that is not my goal here. I want to keep this connection open for as long as I can, but abort if it is closed.

Here is the simple sample of my code:

@cherrypy.expose
def foo(self):
    cherrypy.response.headers['Content-Type'] = 'text/plain'
    def run():
        for result in get_results(): # get_results() is a heavy method mentioned
            yield json.dumps(result)
    return run()
foo._cp_config = {'response.stream': True}
vtlinh
  • 1,427
  • 3
  • 11
  • 16

2 Answers2

2

The only reliable way to know that the client has died is to try to write some data to the socket, which for CherryPy can be done with yield. You must yield non-empty strings, so you'd have to be returning a Content-Type that can handle some filler text, like some extra spaces after the opening <head> tag of an HTML document. If the client closes the connection, the CherryPy server will stop requesting additional yielded data from the handler (and call any close method on the generator so you can clean up).

fumanchu
  • 14,419
  • 6
  • 31
  • 36
  • I have updated my question with the sample code. I am not sure where I need to have the close method so that I can cleanup. – vtlinh Jan 23 '13 at 19:30
  • just finished reading about yield functions. fumanchu@ was right and cherrypy does call close on generator when the connection is closed, that's all I needed. – vtlinh Jan 23 '13 at 20:14
0

As far as I know, CherryPy doesn't provide you with any mechanism to detect that a client died. It will only tell you if a response took too long to complete (and therefore be sent out).

You may refer to this SO thread for more information.

Community
  • 1
  • 1