I'm trying to have a general broadcast message sent out to all clients when files change in the file system.
What works:
broadcasting a general message works fine.
socketio.emit('refresh_request', "A broadcasted message received by all clients", callback=messageReceived, broadcast=True)
getting notifications about file system changes in with the watchdog library in the console.
event type: modified path : C:\appFilesToMonitor\afile_Copy.py
The problem:
I have to send the broadcast message from within the file monitor handler. If I do a socketio.emit() in this class, I get an error message in the console:
File "C:\Tools\Programming\Python37-32\lib\site-packages\flask\globals.py", line 38, in _lookup_req_object raise RuntimeError(_request_ctx_err_msg) RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.
I thought that I have to somehow provide the socketio object to the class. I tried a callback function and tried passing along the socketio object. But to no avail. I'm running out of inspiration here, and clearly I'm not understanding something.
Relevant part of the program:
Let me know if more is required
app = Flask(__name__)
socketio = SocketIO(app)
def file_change_broadcast_callback(msg):
app.logger.warning("*********testing broadcast************")
socketio.emit('refresh_request', msg, callback=messageReceived, broadcast=True)
class MyHandler(FileSystemEventHandler):
def __init__(self, sio, callback_function):
self.sio = sio
self.callback_function = callback_function
def on_modified(self, event):
print(f'--------------------------file change event type: {event.event_type} path : {event.src_path}')
# not working
# emit_arguments = {"status": "refresh_request", "msg":"yooo de mannen"}
# socketio.emit('refresh_request', emit_arguments, callback=messageReceived, broadcast=True)
# not working (nothing received by clients) (error: RuntimeError: Working outside of request context.)
# self.sio.emit('refresh_request', "msg", callback=messageReceived, broadcast=True)
# not working (error: RuntimeError: Working outside of request context.)
# self.callback_function("The filesystem has been changed.")
if __name__ == "__main__":
...
event_handler = MyHandler(socketio,file_change_broadcast_callback)
observer = Observer()
observer.schedule(event_handler, path=str(Path( app.config['webapp']['base_folder'])), recursive=True)
observer.start()
...
The Question:
How can I have a broadcast message sent out to all clients from within another class. (in this case: if a file changes in the filesystem)