Skip to content
This repository was archived by the owner on Jun 11, 2024. It is now read-only.

Commit fa65f20

Browse files
committed
Automatically convert some python types to json and vice versa
- Model attributes that are dates get automatically converted to a python :mod:`datetime` - When saving a model, dates, sets and decimals get automatically converted to there json counterpart
1 parent 4db5091 commit fa65f20

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

CHANGES.txt

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,11 @@
33

44
- Add :meth:`atomx.Atomx.delete` to send a ``HTTP DELETE`` request to the api
55
- :meth:`atomx.Atomx.get` and :meth:`atomx.Atomx.delete` accept non-keyword arguments
6-
that are used to compute the final resource path
6+
that are used to compute the final resource path
77
- Add `emails` parameter to :meth:`atomx.Atomx.report`
8+
- Model attributes that are dates get automatically converted to a python :mod:`datetime`
9+
- When saving a model, dates, sets and decimals get automatically converted
10+
to there json counterpart
811

912

1013
1.2

atomx/models.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import csv
44
import pprint
5+
from decimal import Decimal
6+
from datetime import datetime, date
57
try: # py3
68
from io import StringIO
79
except ImportError: # py2
@@ -33,6 +35,18 @@ def __init__(self, session=None, **attributes):
3335
:param attributes: attributes
3436
:return: model.{model}
3537
"""
38+
for k, v in attributes.items():
39+
if k.endswith('_at'):
40+
try:
41+
attributes[k] = datetime.strptime(v, '%Y-%m-%dT%H:%M:%S')
42+
except (ValueError, TypeError):
43+
pass
44+
elif k == 'date':
45+
try:
46+
attributes[k] = datetime.strptime(v, '%Y-%m-%d')
47+
except (ValueError, TypeError):
48+
pass
49+
3650
super(AtomxModel, self).__setattr__('session', session)
3751
super(AtomxModel, self).__setattr__('_attributes', attributes)
3852
super(AtomxModel, self).__setattr__('_dirty', set()) # list of changed attributes
@@ -89,7 +103,19 @@ def _resource_name(self):
89103

90104
@property
91105
def _dirty_json(self):
92-
return {k: self._attributes[k] for k in self._dirty}
106+
dirty = {}
107+
for attr in self._dirty:
108+
val = self._attributes[attr]
109+
if isinstance(val, datetime) or isinstance(val, date):
110+
dirty[attr] = val.isoformat()
111+
elif isinstance(val, Decimal):
112+
dirty[attr] = float(val)
113+
elif isinstance(val, set):
114+
dirty[attr] = list(val)
115+
else:
116+
dirty[attr] = val
117+
118+
return dirty
93119

94120
@property
95121
def json(self):

0 commit comments

Comments
 (0)