Login

QSerializer with default to JSON input and output

Author:
asfaltboy
Posted:
November 9, 2013
Language:
Python
Version:
1.5
Score:
0 (after 0 ratings)

A module to serializers/deserializes Django Q (query) object

 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
68
69
70
71
72
73
74
75
76
77
78
79
import base64
from time import mktime
from datetime import datetime, date

from django.db.models import Q
from django.core.serializers.base import SerializationError

import simplejson as json


dt2ts = lambda obj: mktime(obj.timetuple()) if isinstance(obj, date) else obj


class QSerializer(object):
    """
    A Q object serializer base class. Pass base64=True when initalizing
    to base64 encode/decode the returned/passed string.

    By default the class provides loads/dumps methods that wrap around
    json serialization, but they may be easily overwritten to serialize
    into other formats (i.e xml, yaml, etc...)
    """
    b64_enabled = False

    def __init__(self, base64=False):
        if base64:
            self.b64_enabled = True

    def prepare_value(self, qtuple):
        if qtuple[0].endswith("__range") and len(qtuple[1]) == 2:
            qtuple[1] = (datetime.fromtimestamp(qtuple[1][0]),
                         datetime.fromtimestamp(qtuple[1][1]))
        return qtuple

    def serialize(self, q):
        """
        Serialize a Q object.
        """
        children = []
        for child in q.children:
            if isinstance(child, Q):
                children.append(self.serialize(child))
            else:
                children.append(child)
        serialized = q.__dict__
        serialized['children'] = children
        return serialized

    def deserialize(self, d):
        """
        Serialize a Q object.
        """
        children = []
        for child in d.pop('children'):
            if isinstance(child, dict):
                children.append(self.deserialize(child))
            else:
                children.append(self.prepare_value(child))
        query = Q()
        query.children = children
        query.connector = d['connector']
        query.negated = d['negated']
        query.subtree_parents = d['subtree_parents']
        return query

    def dumps(self, obj):
        if not isinstance(obj, Q):
            raise SerializationError
        string = json.dumps(self.serialize(obj), default=dt2ts)
        if self.b64_enabled:
            return base64.b64encode(string)
        return string

    def loads(self, string):
        if self.b64_enabled:
            d = json.loads(base64.b64decode(string))
        else:
            d = json.loads(string)
        return self.deserialize(d)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.