fix: fail gracefully when livecode_to_svg crashes

That seems to be happening in some cases and couldn't really figure out
the reason. Handling the error to gracefully to show an empty image in
those cases.
This commit is contained in:
Anand Chitipothu
2021-05-07 18:29:50 +05:30
parent dbaa896fcc
commit 64cf14ed92
2 changed files with 30 additions and 20 deletions

View File

@@ -3,6 +3,7 @@
import websocket
import json
from .svg import SVG
import frappe
# Files to pass to livecode server
# The same code is part of livecode-canvas.js
@@ -62,26 +63,29 @@ clear()
def livecode_to_svg(livecode_ws_url, code, *, timeout=3):
"""Renders the code as svg.
"""
ws = websocket.WebSocket()
ws.settimeout(timeout)
ws.connect(livecode_ws_url)
try:
ws = websocket.WebSocket()
ws.settimeout(timeout)
ws.connect(livecode_ws_url)
msg = {
"msgtype": "exec",
"runtime": "python",
"code": code,
"files": [
{"filename": "start.py", "contents": START},
{"filename": "sketch.py", "contents": SKETCH},
],
"command": ["python", "start.py"]
}
ws.send(json.dumps(msg))
msg = {
"msgtype": "exec",
"runtime": "python",
"code": code,
"files": [
{"filename": "start.py", "contents": START},
{"filename": "sketch.py", "contents": SKETCH},
],
"command": ["python", "start.py"]
}
ws.send(json.dumps(msg))
messages = _read_messages(ws)
commands = [m for m in messages if m['msgtype'] == 'draw']
img = draw_image(commands)
return img.tostring()
messages = _read_messages(ws)
commands = [m for m in messages if m['msgtype'] == 'draw']
img = draw_image(commands)
return img.tostring()
except websocket.WebSocketException as e:
frappe.log_error(frappe.get_traceback(), 'livecode_to_svg failed')
def _read_messages(ws):
messages = []

View File

@@ -9,6 +9,11 @@ import frappe
from frappe.model.document import Document
from . import livecode
DEFAULT_IMAGE = """
<svg viewBox="0 0 300 300" width="300" xmlns="http://www.w3.org/2000/svg">
</svg>
"""
class LMSSketch(Document):
@property
def sketch_id(self):
@@ -48,8 +53,9 @@ class LMSSketch(Document):
else:
ws_url = self.get_livecode_ws_url()
value = livecode.livecode_to_svg(ws_url, self.code)
cache.set(key, value)
return value
if value:
cache.set(key, value)
return value or DEFAULT_IMAGE
@staticmethod
def get_recent_sketches(limit=100, owner=None):