user800133 user800133 - 8 months ago 78
Ajax Question

Flask broken pipe when redirecting after AJAX call

I have an JQuery AJAX call:

$.getJSON($SCRIPT_ROOT + '/_click_btn?btnId='+$(this).attr("id"),
function(data) {
// return to send_messages page
window.location = 'send_messages';

It doesn't do anything fancy. It just saves some form data to a database (using SQLAlchemy). I put a break point on the window.location statement and the broken pipe won't happen if I delay the redirection by 1-2 seconds. What's the best practice for handling this?

One other item of note is the DB session remains open after the AJAX call is complete.

The error message is below.

Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib64/python2.7/", line 813, in __bootstrap_inner
File "/usr/lib64/python2.7/", line 766, in run self.__target(*self.__args, **self.__kwargs)
File "/gui/venv/lib/python2.7/site-packages/werkzeug/", line 656, in inner srv.serve_forever()
File "/gui/venv/lib/python2.7/site-packages/werkzeug/", line 496, in serve_forever HTTPServer.serve_forever(self)
File "/usr/lib64/python2.7/", line 238, in serve_forever
File "/usr/lib64/python2.7/", line 297, in _handle_request_noblock
self.handle_error(request, client_address)
File "/usr/lib64/python2.7/", line 295, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib64/python2.7/", line 321, in process_request
self.finish_request(request, client_address)
File "/usr/lib64/python2.7/", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib64/python2.7/", line 655, in __init__
File "/gui/venv/lib/python2.7/site-packages/werkzeug/", line 216, in handle rv = BaseHTTPRequestHandler.handle(self)
File "/usr/lib64/python2.7/", line 340, in handle
File "/gui/venv/lib/python2.7/site-packages/werkzeug/", line 251, in handle_one_request
return self.run_wsgi()
File "/gui/venv/lib/python2.7/site-packages/werkzeug/", line 193, in run_wsgi
File "/gui/venv/lib/python2.7/site-packages/werkzeug/", line 184, in execute
File "/gui/venv/lib/python2.7/site-packages/werkzeug/", line 152, in write
self.send_header(key, value)
File "/usr/lib64/python2.7/", line 401, in send_header
self.wfile.write("%s: %s\r\n" % (keyword, value))
IOError: [Errno 32] Broken pipe

Answer Source

As a temporary solution, I've added a 500 ms delay before redirecting. Seems like there must be a better way, but this works for now.