def _apply(self, value):
value = self._filter(value, Type(binary_type)) # type: binary_type
if self._has_errors:
return None
# Strip out whitespace.
# Technically, whitespace is not part of the Base64 alphabet,
# but virtually every implementation allows it.
value = self.whitespace_re.sub(b'', value)
# Check for invalid characters.
# Note that Python 3's b64decode does this for us, but we also
# have to support Python 2.
# https://docs.python.org/3/library/base64.html#base64.b64decode
if not self.base64_re.match(value):
return self._invalid_value(
value = value,
reason = self.CODE_INVALID,
)
# Check to see if we are working with a URL-safe dialect.
# https://en.wikipedia.org/wiki/Base64#URL_applications
if (b'_' in value) or (b'-' in value):
# You can't mix dialects, silly!
if (b'+' in value) or (b'/' in value):
return self._invalid_value(
value = value,
reason = self.CODE_INVALID,
)
url_safe = True
else:
url_safe = False
# Normalize padding.
# http://stackoverflow.com/a/9807138/
value = value.rstrip(b'=')
value += (b'=' * (4 - (len(value) % 4)))
try:
return (
urlsafe_b64decode(value)
if url_safe
else standard_b64decode(value)
)
except TypeError:
return self._invalid_value(value, self.CODE_INVALID, exc_info=True)
# noinspection SpellCheckingInspection
评论列表
文章目录