Custom json encoding for flask & sockjs
That will allow us to support encoding non-built in types by simply adding them through octoprint.util.json.JsonEncoding.add_encoder
This commit is contained in:
1 parent
3c8d2f2df5
commit
90aa5ed3d4
4 files changed
+58
-1
No files matched your search
@@ -793,12 +793,14 @@ class Server(object):
|
||||
return Locale.parse(request.accept_languages.best_match(LANGUAGES))
|
||||
|
||||
def _setup_app(self, app):
|
||||
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse
|
||||
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse, OctoPrintJsonEncoder
|
||||
|
||||
s = settings()
|
||||
|
||||
app.debug = self._debug
|
||||
|
||||
app.json_encoder = OctoPrintJsonEncoder
|
||||
|
||||
secret_key = s.get(["server", "secretKey"])
|
||||
if not secret_key:
|
||||
import string
|
||||
|
||||
@@ -8,6 +8,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
|
||||
|
||||
import tornado.web
|
||||
import flask
|
||||
import flask.json
|
||||
import flask.ext.login
|
||||
import flask.ext.principal
|
||||
import flask.ext.assets
|
||||
@@ -29,6 +30,7 @@ import octoprint.users
|
||||
import octoprint.plugin
|
||||
|
||||
from octoprint.util import DefaultOrderedDict
|
||||
from octoprint.util.json import JsonEncoding
|
||||
|
||||
from werkzeug.contrib.cache import BaseCache
|
||||
|
||||
@@ -1399,3 +1401,9 @@ def collect_plugin_assets(enable_gcodeviewer=True, preferred_stylesheet="css"):
|
||||
break
|
||||
|
||||
return assets
|
||||
|
||||
##~~ JSON encoding
|
||||
|
||||
class OctoPrintJsonEncoder(flask.json.JSONEncoder):
|
||||
def default(self, obj):
|
||||
return JsonEncoding.encode(obj)
|
||||
@@ -9,6 +9,8 @@ import logging
|
||||
import threading
|
||||
import sockjs.tornado
|
||||
import sockjs.tornado.session
|
||||
import sockjs.tornado.proto
|
||||
import sockjs.tornado.util
|
||||
import time
|
||||
|
||||
import octoprint.timelapse
|
||||
@@ -18,9 +20,13 @@ import octoprint.plugin
|
||||
|
||||
from octoprint.events import Events
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util.json import JsonEncoding
|
||||
|
||||
import octoprint.printer
|
||||
|
||||
import wrapt
|
||||
import json
|
||||
|
||||
|
||||
class ThreadSafeSession(sockjs.tornado.session.Session):
|
||||
def __init__(self, conn, server, session_id, expiry=None):
|
||||
@@ -50,8 +56,26 @@ class ThreadSafeSession(sockjs.tornado.session.Session):
|
||||
return result
|
||||
|
||||
|
||||
class JsonEncodingSessionWrapper(wrapt.ObjectProxy):
|
||||
|
||||
def send_message(self, msg, stats=True, binary=False):
|
||||
"""Send or queue outgoing message
|
||||
|
||||
`msg`
|
||||
Message to send
|
||||
`stats`
|
||||
If set to True, will update statistics after operation completes
|
||||
"""
|
||||
self.send_jsonified(json.dumps(sockjs.tornado.util.bytes_to_str(msg),
|
||||
separators=(',', ':'),
|
||||
default=JsonEncoding.encode),
|
||||
stats)
|
||||
|
||||
|
||||
class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
|
||||
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
|
||||
session = JsonEncodingSessionWrapper(session)
|
||||
|
||||
sockjs.tornado.SockJSConnection.__init__(self, session)
|
||||
|
||||
self._logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, division, print_function
|
||||
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import collections
|
||||
|
||||
class JsonEncoding(object):
|
||||
|
||||
encoders = collections.OrderedDict()
|
||||
|
||||
@classmethod
|
||||
def add_encoder(cls, type, encoder):
|
||||
cls.encoders[type] = encoder
|
||||
|
||||
@classmethod
|
||||
def encode(cls, obj):
|
||||
for type, encoder in cls.encoders.items():
|
||||
if isinstance(obj, type):
|
||||
return encoder(obj)
|
||||
raise TypeError
|
||||
Reference in new issue
Block a user