Skip to content

Commit

Permalink
Merge pull request #8 from den4uk/dev
Browse files Browse the repository at this point in the history
Disable data classed
  • Loading branch information
den4uk committed Aug 31, 2019
2 parents 0d14723 + bc0e4de commit c90ebfe
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
18 changes: 13 additions & 5 deletions jsonextra/json_extra.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@
BYTES_PREFIX = 'base64:'
bytes_rex = re.compile(BYTES_PREFIX + r'([\w\d\+/]*?\={,2}?)$', re.DOTALL)

_all_rex = ['uuid_rex', 'datetime_rex', 'date_rex', 'time_rex', 'bytes_rex']


def disable_rex(rex):
"""Disables a regulax expresseion for matching"""
assert rex in _all_rex, f'Cannot disable rex which is not allowed! Available: {_all_rex}'
globals()[rex] = None


class ExtraEncoder(json.JSONEncoder):

Expand All @@ -38,15 +46,15 @@ def __init__(self, *args, **kwargs):
@staticmethod
def _apply_extras(value: str):
with contextlib.suppress(ValueError):
if uuid_rex.match(value):
if uuid_rex and uuid_rex.match(value):
return uuid.UUID(value)
elif date_rex.match(value):
elif date_rex and date_rex.match(value):
return dateutil.parser.parse(value).date()
elif datetime_rex.match(value):
elif datetime_rex and datetime_rex.match(value):
return dateutil.parser.parse(value)
elif time_rex.match(value):
elif time_rex and time_rex.match(value):
return dateutil.parser.parse(value).time()
else:
elif bytes_rex:
try_bytes = bytes_rex.match(value)
if try_bytes:
return base64.b64decode(try_bytes.groups()[0])
Expand Down
2 changes: 0 additions & 2 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ files = jsonextra/__init__.py
tag = True
tag_name = {new_version}

[wheel]
universal = 1

[metadata]
license_file = LICENSE
Expand Down
6 changes: 6 additions & 0 deletions tests/test_jsonextra.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,9 @@ def test_random_bytes():
my_obj = {'x': secrets.token_bytes(n)}
serialized = jsonextra.dumps(my_obj)
assert jsonextra.loads(serialized) == my_obj


def test_disable_rex():
assert jsonextra.loads('{"x": "1991-02-16"}') == {'x': datetime.date(1991, 2, 16)}
jsonextra.disable_rex('date_rex')
assert jsonextra.loads('{"x": "1991-02-16"}') == {'x': '1991-02-16'}

0 comments on commit c90ebfe

Please sign in to comment.