s3bw / scap-registry

Server side application for note storage
1 stars 1 forks source link

Implement the JSON Date encoder and decoder in foolscap #9

Open s3bw opened 6 years ago

s3bw commented 6 years ago

This issue needs to be completed here: https://github.com/GiantsLoveDeathMetal/foolscap

This is to ensure we are sending the server appropriate jsons that we can then decode in the application

s3bw commented 6 years ago

Encoder

class DateTimeEncoder(JSONEncoder):
    """Encode datetime objects as a dict with a key __type__.
    """
    def default(self, obj):
        if isinstance(obj, datetime):
            return {
                '__type__': 'datetime',
                'year': obj.year,
                'month': obj.month,
                'day': obj.day,
                'hour': obj.hour,
                'minute': obj.minute,
                'second': obj.second,
                'microsecond': obj.microsecond,
            }
        else:
            return JSONEncoder.default(self, obj)

Decoder

class DateTimeDecoder(json.JSONDecoder):
    def __init__(self, *args, **kargs):
        # Using JSONDecoder in two different ways
        JSONDecoder.__init__(self, object_hook=self.dict_to_object,
                             *args, **kargs)
    def dict_to_object(self, d):
        if '__type__' not in d:
            return d
        _type = d.pop('__type__')
        try:
            dateobj = datetime(**d)
            return dateobj
        except:
            d['__type__'] = _type
            return d

implementation

# Don't forget to decode!
meta_data = json.loads(get_json.content.decode(), cls=DateTimeDecoder)