Python / Websockets : Opening file in socket callback reset the connection
I'm making a website with a python server. I'm using the websockets library.
I would like to add log files to monitor my site activity during it is running.
But if I open a file in the socket callback, the socket connection is always reset on the opening.
import asyncio
import websockets
async def handler(websocket):
while True:
try:
testFile = open("log", "w") # This line reset socket connection
testFile.write('anything')
testFile.close()
message = await websocket.recv()
await websocket.send('{"cmd" : "ERROR", "msg" : "This is a test"}')
except websockets.ConnectionClosedOK:
break
async def main():
async with websockets.serve(handler, "", 50000):
await asyncio.Future() # run forever
if __name__ == "__main__":
asyncio.run(main())
EDIT : If I remove the try except block, I got the following error :
connection handler failed
Traceback (most recent call last):
File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py", line 231, in handler
await self.ws_handler(self)
File "server2.py", line 52, in handler
message = await websocket.recv()
File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 552, in recv
await self.ensure_open()
File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 929, in ensure_open
raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: received 1001 (going away); then sent 1001 (going away)
(I have also tried with another socket library (simple_websocket_server) and the issue was the same)
Is there a way to avoid this behavior ? If not, Is there another way to get logs during server execution ?
Not sure if this might help but you could create a logger using the logging library: https://docs.python.org/3/howto/logging.html