This repository has been archived by the owner on Jul 18, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
run_websockets.py
67 lines (55 loc) · 2.11 KB
/
run_websockets.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
#!/usr/bin/env python
from gevent import monkey
monkey.patch_all()
from gevent import wsgi
from geventwebsocket.handler import WebSocketHandler
from flask import Flask
from flask_sockets import Sockets
import os
from bson import BSON
from bson.binary import Binary
import pymongo
import werkzeug.serving
from slideatlas import create_app
from slideatlas import models
from base64 import b64encode
app = create_app()
sockets = Sockets(app)
@sockets.route('/ws')
def tile_socket(ws):
tilestore = None
while True:
message = ws.receive()
# Wraps entire websocket response, any errors will be reported back
with app.app_context():
try:
req = BSON(message).decode()
if "init" in req:
"""
Initialization request
"""
tilestore = models.ImageStore.objects.get(id=req["init"]["db"])
if tilestore == None:
raise Exception("Tile Store %s not found"%(req["init"]["db"]))
resp = BSON.encode({"request" : req, "success" : True})
elif "tile" in req:
"""
Regular request
"""
if tilestore == None:
raise Exception("Tile Store not initialized")
imgdata = tilestore.get_tile(req["tile"]["image"], req["tile"]["name"])
resp = BSON.encode({"request" : req, "image" : Binary(imgdata), "success" : True})
# resp = BSON.encode({"request" : req, "image" : b64encode(imgdata), "success" : True})
else:
raise Exception("Unknown request")
ws.send(resp, True)
except Exception as e:
resp = BSON.encode({"request" : req, "error" : e.message})
ws.send(resp, True)
def run_server():
ws = wsgi.WSGIServer(listener=('0.0.0.0', 8080),
application=app, handler_class=WebSocketHandler)
ws.serve_forever()
if __name__ == "__main__":
run_server()