From 64cf14ed92db8bb75b0b029fb28828bb23774af7 Mon Sep 17 00:00:00 2001 From: Anand Chitipothu Date: Fri, 7 May 2021 18:29:50 +0530 Subject: [PATCH] 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. --- community/lms/doctype/lms_sketch/livecode.py | 40 ++++++++++--------- .../lms/doctype/lms_sketch/lms_sketch.py | 10 ++++- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/community/lms/doctype/lms_sketch/livecode.py b/community/lms/doctype/lms_sketch/livecode.py index e0cf2312..8ea05ddd 100644 --- a/community/lms/doctype/lms_sketch/livecode.py +++ b/community/lms/doctype/lms_sketch/livecode.py @@ -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 = [] diff --git a/community/lms/doctype/lms_sketch/lms_sketch.py b/community/lms/doctype/lms_sketch/lms_sketch.py index 474ccf5d..008bc024 100644 --- a/community/lms/doctype/lms_sketch/lms_sketch.py +++ b/community/lms/doctype/lms_sketch/lms_sketch.py @@ -9,6 +9,11 @@ import frappe from frappe.model.document import Document from . import livecode +DEFAULT_IMAGE = """ + + +""" + 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):