-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
77 lines (61 loc) · 2.09 KB
/
server.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import asyncio
import json
import os
from pathlib import Path
import websockets
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
ch = logging.StreamHandler()
logger.addHandler(ch)
logger.info('Starting server')
DATA_DIR = Path(os.environ.get('PLOTLY_FIG_DIR', '/tmp/plotly'))
DATA_DIR.mkdir(parents=True, exist_ok=True)
client_files = set()
server_files = set()
async def file_diff_producer(websocket, path):
while True:
for sfile in server_files:
if sfile.name not in client_files:
with sfile.open('r') as f:
fig = json.load(f)
data = {}
data['fig'] = fig
data['id'] = str(sfile.name)
data_str = json.dumps(data)
await websocket.send(data_str)
logger.info(f'Sent {sfile}')
await asyncio.sleep(1)
async def file_updater():
while True:
files = set(DATA_DIR.glob('*.json'))
new_files = files.difference(server_files)
if new_files:
logger.info(f'new files {new_files}')
server_files.update(new_files)
await asyncio.sleep(1)
async def consumer(websocket, path):
while True:
async for message in websocket:
try:
files = json.loads(message)
except json.JSONDecodeError:
logger.warning(f'Invalid JSON {message}')
continue
if not isinstance(files, list):
logger.warning(f'Invalid data {files}')
continue
client_files.clear()
client_files.update(set(files))
logger.info(f'Current client files {client_files}')
await asyncio.sleep(1)
async def handler(websocket, path):
await asyncio.gather(
file_diff_producer(websocket, path),
consumer(websocket, path),
file_updater(),
)
if __name__ == '__main__':
start_server = websockets.serve(handler, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()