-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
51 lines (41 loc) · 1.43 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import asyncio
import random
import fastapi.logger as logger
from starlette.requests import Request
'''
Get status as an event generator
'''
status_stream_delay = 5 # second
status_stream_retry_timeout = 30000 # milisecond
logger = logger.logger
async def compute_status(param1: str):
number = random.randint(0, 100)
if number < 96:
return dict(number=number, param=param1)
else:
return dict(some_end_condition=True, param=param1)
async def status_event_generator(request: Request, param1: str):
previous_status = None
while True:
if await request.is_disconnected():
logger.debug('Request disconnected')
break
if previous_status and 'some_end_condition' in previous_status and previous_status['some_end_condition']:
logger.debug('Request completed. Disconnecting now')
yield {
"event": "end",
"data": ''
}
break
current_status = await compute_status(param1)
if previous_status != current_status:
yield {
"event": "update",
"retry": status_stream_retry_timeout,
"data": current_status
}
previous_status = current_status
logger.debug('Current status :%s', current_status)
else:
logger.debug('No change in status...')
await asyncio.sleep(status_stream_delay)