Flask server sent events socket exception

2024/11/15 9:42:59

I am thinking of using SSE to push new data to the client and using Flot(javascript charting library) display "live" updates. My server runs on python Flask framework and I have figured out how to push the data to the client, but the problem occurs as soon as I leave the page:

Exception happened during processing of request from ('127.0.0.1', 38814)
Traceback (most recent call last):File "/usr/lib/python2.7/SocketServer.py", line 582, in process_request_threadself.finish_request(request, client_address)File "/usr/lib/python2.7/SocketServer.py", line 323, in finish_requestself.RequestHandlerClass(request, client_address, self)File "/usr/lib/python2.7/SocketServer.py", line 640, in __init__self.finish()File "/usr/lib/python2.7/SocketServer.py", line 693, in finishself.wfile.flush()File "/usr/lib/python2.7/socket.py", line 303, in flushself._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe

I understand why the error occurs - the socket is never closed due the infinite loop serving up "live" data. Question is how do I detect the page change and cleanly close the socket? Can I close the connection on the client side? How do I detect the page change then?

This is the server code skeleton, I would of course replace the text message with json containing the list of objects to display:

def event_stream():import timewhile True:time.sleep(1)yield "data: This is a message number X.\n\n"@app.route('/stream')
def stream():return Response(event_stream(), mimetype="text/event-stream")
Answer

You could use either onBeforeUnload or jQuery's window.unload() to make an Ajax call to some tear down method that closes the handle. Something like:

$(window).unload(function() {$.ajax(type: 'POST',async: false,url: 'foo.com/client_teardown')}
}

There are some inconsistencies with how the unload()/onBeforeUnload() are handled, so you may have some more work to do in something like Chrome.

https://en.xdnf.cn/q/72457.html

Related Q&A

Pandas adding scalar value to numeric column?

Given a dataframe like thisImageId | Width | Height | lb0 | x0 | y0 | lb1 | x1 | y1 | lb2 | x2 | y2 0 abc | 200 | 500 | ijk | 115| 8 | zyx | 15 | 16 | www | 23 | 42 1 def | 300 | 800 …

Sklearn Pipeline all the input array dimensions for the concatenation axis must match exactly

import pandas as pd from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC from sklearn.preprocessing impo…

Python Pandas read_excel returns empty Dataframe

Reading a simple xls returning empty dataframe, cant figure it out for the life of me:path = (c:/Users/Desktop/Stuff/Ready) files = os.listdir(path) print(files)files_xlsx = [f for f in files if f[-3:]…

Fill matrix with transposed version

I have a pairwise matrix:>>> ma b c d a 1.0 NaN NaN NaN b 0.5 1.0 NaN NaN c 0.6 0.0 1.0 NaN d 0.5 0.4 0.3 1.0I want to replace the NaN in the the top right with the same va…

Subclass of numpy ndarray doesnt work as expected

`Hello, everyone.I found there is a strange behavior when subclassing a ndarray.import numpy as npclass fooarray(np.ndarray):def __new__(cls, input_array, *args, **kwargs):obj = np.asarray(input_array)…

How to correctly load images asynchronously in PyQt5?

Im trying to figure out how to accomplish an async image load correctly, in PyQt Qlistview.My main widget consists of a Qlistview and a QLineEdit textbox. I have a database of actors which I query usin…

How to print results of Python ThreadPoolExecutor.map immediately?

I am running a function for several sets of iterables, returning a list of all results as soon as all processes are finished.def fct(variable1, variable2):# do an operation that does not necessarily ta…

Python dir equivalent in perl?

The dir command in Python 2.7.x lists all accessible symbols from a module. Is there an equivalent in Perl 5.x to list all accessible symbols from a package?

Entire JSON into One SQLite Field with Python

I have what is likely an easy question. Im trying to pull a JSON from an online source, and store it in a SQLite table. In addition to storing the data in a rich table, corresponding to the many fiel…

Python scipy module import error due to missing ._ufuncs dll

I have some troubles with sub-module integrate from scipy in python. I have a 64 bits architecture, and it seems, according to the first lines of the python interpreter (see below) that I am also using…