python-socketio
python-socketio copied to clipboard
Listening for events in main thread
I'm trying to implement SocketIO to unlock vehicles. However my users are communicating to my API over HTTP. I'm trying to implement a mechanism that waits for a confirmation on the SocketIO connection before responding to the user.
Example (not working):
sio = socketio.Client()
sio.connect('https://mysocketio.server')
# my view/handler
# POST: /vehicle/<uuid>/unlock
def unlock_vehicle(request):
vin = request.matchdict['vehicle_id']
sio.emit('unlock' data={'vin': vin})
def handle_status(data):
if data['vin'] == vin:
return Response('unlocking succeeded!')
# I want to listen for updates here and apply some logic e.g.:
sio.listen_for('status', callback=handle_status, timeout=10)
return Response("didn't work")
Is there a way to accomplish just that? I can't seem to come up with a working setup.
You can use the call() method instead of emit():
def unlock_vehicle(request):
vin = request.matchdict['vehicle_id']
data = sio.call('unlock' data={'vin': vin}, timeout=10)
if data['vin'] == vin:
return Response('unlocking succeeded!')
else:
return Response("didn't work")
But to use this you will need to change your Socket.IO server to send the response as an "ACK" packet and not as a separate status event.
Thanks @miguelgrinberg I'll close the issue.