|
- import base64
- import datetime
- import pasn1
- import sys
- import uuid
-
- _real_stderr = sys.stderr
-
- DEBUG = True
-
- def enable_debug():
- global DEBUG
-
- DEBUG = True
-
- def disable_debug():
- global DEBUG
-
- DEBUG = False
-
- def _debprint(*args): # pragma: no cover
- if not DEBUG:
- return
-
- import traceback, sys, os.path
- st = traceback.extract_stack(limit=2)[0]
-
- sep = ''
- if args:
- sep = ':'
-
- print('%s:%d%s' % (os.path.basename(st.filename), st.lineno, sep),
- *args, file=_real_stderr)
- sys.stderr.flush()
-
- def _makeuuid(s):
- if isinstance(s, uuid.UUID):
- return s
-
- if isinstance(s, bytes):
- return uuid.UUID(bytes=s)
- else:
- return uuid.UUID(s)
-
- def _makedatetime(s):
- if isinstance(s, datetime.datetime):
- return s
-
- return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%fZ').replace(
- tzinfo=datetime.timezone.utc)
-
- def _makebytes(s):
- if isinstance(s, bytes):
- return s
-
- return base64.urlsafe_b64decode(s)
-
- def _trytodict(o):
- if isinstance(o, uuid.UUID):
- return 'bytes', o.bytes
- if isinstance(o, tuple):
- return 'list', o
- try:
- return 'dict', o.__to_dict__()
- except Exception: # pragma: no cover
- raise TypeError('unable to find __to_dict__ on %s: %s' %
- (type(o), repr(o)))
-
- class CanonicalCoder(pasn1.ASN1DictCoder):
- def enc_dict(self, obj, **kwargs):
- class FakeIter:
- def items(self):
- return iter(sorted(obj.items()))
-
- return pasn1.ASN1DictCoder.enc_dict(self, FakeIter(), **kwargs)
-
- _asn1coder = CanonicalCoder(coerce=_trytodict)
|