forked from plotly/dash-recipes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dash-asynchronous.py
71 lines (49 loc) · 1.48 KB
/
dash-asynchronous.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
import dash
from dash.dependencies import Input, Output, Event
import dash_core_components as dcc
import dash_html_components as html
import datetime
import time
class Semaphore:
def __init__(self, filename='semaphore.txt'):
self.filename = filename
with open(self.filename, 'w') as f:
f.write('done')
def lock(self):
with open(self.filename, 'w') as f:
f.write('working')
def unlock(self):
with open(self.filename, 'w') as f:
f.write('done')
def is_locked(self):
return open(self.filename, 'r').read() == 'working'
semaphore = Semaphore()
def long_process():
if semaphore.is_locked():
raise Exception('Resource is locked')
semaphore.lock()
time.sleep(7)
semaphore.unlock()
return datetime.datetime.now()
app = dash.Dash()
server = app.server
def layout():
return html.Div([
html.Button('Run Process', id='button'),
dcc.Interval(id='interval', interval=500),
html.Div(id='lock'),
html.Div(id='output'),
])
app.layout = layout
@app.callback(
Output('lock', 'children'),
events=[Event('interval', 'interval')])
def display_status():
return 'Running...' if semaphore.is_locked() else 'Free'
@app.callback(
Output('output', 'children'),
events=[Event('button', 'click')])
def run_process():
return 'Finished at {}'.format(long_process())
if __name__ == '__main__':
app.run_server(debug=True, processes=5)