-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
executable file
·78 lines (57 loc) · 1.99 KB
/
run.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
78
# encoding: utf-8
import json
import asyncio
from aiohttp import web
from concurrent.futures import ThreadPoolExecutor
import market
import analyze
SHARED_EXECUTOR = ThreadPoolExecutor(max_workers=1)
def log_future_exception(future):
exc = future.exception()
if exc is not None:
print("Critical exception occured: %r" % exc)
@asyncio.coroutine
def update_market(loop=None):
if loop is None:
loop = asyncio.get_event_loop()
while True:
try:
trades = yield from asyncio.wait_for(
loop.run_in_executor(SHARED_EXECUTOR, market.get_trades, True),
timeout=120
)
trades.write(latest=True)
yield from asyncio.sleep(120, loop=loop)
except asyncio.TimeoutError:
print("TimeoutError occured. Try again!")
except Exception as exc:
print("Unhandled exception occured: %r" % exc)
print("Sleep...")
yield from asyncio.sleep(10, loop=loop)
print("Wake up!")
@asyncio.coroutine
def dupe(request):
post_data = yield from request.post()
ignore = post_data.get('ignore') or None
if ignore is not None:
ignore = json.loads(ignore)
dupes, ignored = analyze.get_dupes(ignore_trades=ignore)
result = [d.to_dict() for d in dupes]
if post_data:
result = {'dupes': result, 'ignored': ignored}
body = json.dumps(result).encode()
return web.Response(body=body)
if __name__ == '__main__':
app = web.Application()
app.router.add_route('GET', '/api/dupe', dupe)
app.router.add_route('POST', '/api/dupe', dupe)
loop = asyncio.get_event_loop()
upd_task = asyncio.async(update_market())
upd_task.add_done_callback(log_future_exception)
f = loop.create_server(app.make_handler(), '0.0.0.0', 8080)
srv = loop.run_until_complete(f)
print('serving on', srv.sockets[0].getsockname())
try:
loop.run_forever()
except (KeyboardInterrupt, SystemExit):
pass