File: pyqt-reduce-handler.py

package info (click to toggle)
jsonpickle 3.0.0%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,184 kB
  • sloc: python: 6,088; javascript: 654; makefile: 90; sh: 17
file content (58 lines) | stat: -rw-r--r-- 1,467 bytes parent folder | download
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
"""
This example demonstrates how to add a custom handler to serialize
Qt's QPointF class jsonpickle using PyQt4.

"""
import sys
import unittest

from PyQt4 import QtCore

import jsonpickle
from jsonpickle import handlers

text_type = eval('unicode') if str is bytes else str


class QReduceHandler(handlers.BaseHandler):
    def flatten(self, obj, data):
        pickler = self.context
        if not pickler.unpicklable:
            return text_type(obj)
        flatten = pickler.flatten
        data['__reduce__'] = [flatten(i, reset=False) for i in obj.__reduce__()[1]]
        return data

    def restore(self, data):
        unpickler = self.context
        restore = unpickler.restore
        reduced = [restore(i, reset=False) for i in data['__reduce__']]
        modulename = reduced[0]
        classname = reduced[1]
        args = reduced[2]
        __import__(modulename)
        module = sys.modules[modulename]
        factory = getattr(module, classname)

        return factory(*args)


handlers.register(QtCore.QPointF, QReduceHandler)


class QtTestCase(unittest.TestCase):
    def test_QPointF_roundtrip(self):
        expect = QtCore.QPointF(1.0, 2.0)
        json = jsonpickle.encode(expect)
        actual = jsonpickle.decode(json)
        self.assertEqual(expect, actual)


def suite(self):
    suite = unittest.TestSuite()
    suite.addSuite(unittest.makeSuite(QtTestCase))
    return suite


if __name__ == '__main__':
    unittest.main()