问题
I have DRF API consumed by a front-end application. I need to handle a special feature: the user clicks a button, he's being asked to scan a RFID card on an external device (he has 30 seconds to do so, he must not be able to do anything else during this time), then after the scan or timeout he gets the focus back. So far I've been able to deal with the scanning part, but troubles comes with the timeout. Here's my setup:
- The endpoint
/rfid/create/
is called by the front when the user clicks the button. It waits for athreading.Event
to be set and returns some data, or an error if it timed out. Post method of the view:
def post(self, request):
scanned = RFID_ASSIGN_EVENT.wait(timeout=RFID_ASSIGN_TIMEOUT)
if scanned:
RFID_ASSIGN_EVENT.clear()
return Response({
'some': data,
})
return Response(
{'code': 'timeout', 'message': 'no RFID card was scanned'},
status=status.HTTP_408_REQUEST_TIMEOUT
)
- On the other hand, the endpoint
/rfid/assign/
is called by the external device (a raspberry but doesnt really matter) attached to the RFID reader when a card is scanned, and set the event. Post method of the view:
def post(self, request):
RFID_ASSIGN_EVENT.set()
return Response({
'some': data
})
In reality there's some database calls in these views but nothing relevant for this problem, the general idea is here.
So this works great when I scan a card when asked, but if I wait for the event to timeout, something that I can't explain happen. It seems that after the timeout a new unwanted thread pop, re-handle the request with it's own timeout and then send the response to the client. Client side, it means that the request takes twice the configured time to timeout, and server side an unacceptable multiplication of threads resulting some times in a ConnectionResetError
.
Some logs:
Here, I just scan cards, as you can see everything's fine, only the django-main-thread
and a Thread-1
in execution.
Here I'm waiting for timeout, you can see that the request is made at 19:12:34, the Thread-1
respond with timeout error at 19:12:44, then Thread-4
(4 ? wtf ?) responds antoher 10 seconds later, at 19:12:54, and it's this response that the front end client receive.
I'm going crazy with this thing, any help will be much appreciated!
Thank's!
来源:https://stackoverflow.com/questions/61921394/threading-event-wait-in-django-application