本文整理汇总了Python中base64.decodebytes方法的典型用法代码示例。如果您正苦于以下问题:Python base64.decodebytes方法的具体用法?Python base64.decodebytes怎么用?Python base64.decodebytes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类base64
的用法示例。
在下文中一共展示了base64.decodebytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_book_cover
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def generate_book_cover(self):
cover = None
try:
cover_image_xml = self.xml.find('coverpage')
for i in cover_image_xml:
cover_image_name = i.get('l:href')
cover_image_data = self.xml.find_all('binary')
for i in cover_image_data:
if cover_image_name.endswith(i.get('id')):
cover = base64.decodebytes(i.text.encode())
except (AttributeError, TypeError):
# Catch TypeError in case no images exist in the book
logger.warning('Cover not found: ' + self.filename)
return cover
示例2: png_to_file
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def png_to_file(self, filename):
"""
Write the png to a file for viewing.
:param filename: str(): a name to give the saved file
:return: a saved filename.png in the img folder for viewing.
"""
path = Path().cwd()
data_folder = path / u'img'
filepath = data_folder / filename
if self.png:
png_data = self.png.encode('utf-8')
with open(str(filepath), 'wb') as fh:
fh.write(base64.decodebytes(png_data))
print(f'Saved to {filepath}')
print(f'self.png is None')
return None
示例3: ocr_rest
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def ocr_rest():
"""
:return:
"""
img = base64.decodebytes(request.form.get('img').encode())
img = np.frombuffer(img, dtype=np.uint8)
h, w = request.form.getlist('shape', type=int)
img = img.reshape((h, w))
# 预处理
img = pre_process_image(img, h, w)
# 预测
text = inference(img, h, w)
text = ''.join(text)
print("text:{}".format(text))
return {'text': text}
示例4: _write_file
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def _write_file(self, byte_data: str, subtitle_path: str):
"""
Encode the byte_data string to bytes (since it's not in byte format by default) and write it to a .gzip
file. Unzip the content of the .gzip file and write it outside (unzipped).
:param byte_data: (string) string containing bytecode information
ATTENTION: variable is not byte encoded, which is why it is done in this method
:param subtitle_path: (string) absolute path where to write the subtitle
"""
with open(subtitle_path, "wb") as subtitle_file:
subtitle_file.write(base64.decodebytes(byte_data.encode()))
# Open and read the compressed file and write it outside
with gzip.open(subtitle_path, 'rb') as gzip_file:
content = gzip_file.read()
# Removes the ".gzip" extension
with open(subtitle_path[:-4], 'wb') as srt_file:
srt_file.write(content)
self.downloaded_files += 1
# Remove the .gzip file
os.remove(subtitle_path)
示例5: on_request_attestation
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def on_request_attestation(self, peer, dist, payload):
"""
Someone wants us to attest their attribute.
"""
metadata = json.loads(payload.metadata)
attribute = metadata.pop('attribute')
pubkey_b64 = cast_to_bin(metadata.pop('public_key'))
id_format = metadata.pop('id_format')
id_algorithm = self.get_id_algorithm(id_format)
value = await maybe_coroutine(self.attestation_request_callback, peer, attribute, metadata)
if value is None:
return
PK = id_algorithm.load_public_key(decodebytes(pubkey_b64))
attestation_blob = id_algorithm.attest(PK, value)
attestation = id_algorithm.get_attestation_class().unserialize(attestation_blob, id_format)
self.attestation_request_complete_callback(peer, attribute, attestation.get_hash(), id_format)
self.send_attestation(peer.address, attestation_blob, dist.global_time)
示例6: convert_gif_2_jpg
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def convert_gif_2_jpg(gif_base64):
bas = base64.decodebytes(bytes(gif_base64, "utf-8"))
im = Image.open(BytesIO(bas))
i = 0
mypalette = im.getpalette()
base64_jpgs = []
try:
while 1:
im.putpalette(mypalette)
new_im = Image.new("RGB", im.size)
new_im.paste(im)
buffered = BytesIO()
new_im.save(buffered, format="JPEG")
img_data_base64 = base64.b64encode(buffered.getvalue())
base64_jpgs.append(img_data_base64)
i += 1
im.seek(im.tell() + 1)
except EOFError:
pass
return base64_jpgs
示例7: _save_file
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def _save_file(self, path, content, format):
"""Save content of a generic file."""
if format not in {'text', 'base64'}:
raise web.HTTPError(
400,
"Must specify format of file contents as 'text' or 'base64'",
)
try:
if format == 'text':
bcontent = content.encode('utf8')
else:
b64_bytes = content.encode('ascii')
bcontent = decodebytes(b64_bytes)
except Exception as e:
raise web.HTTPError(
400, u'Encoding error saving %s: %s' % (path, e)
)
if format == 'text':
self._pyfilesystem_instance.writebytes(path, bcontent)
else:
self._pyfilesystem_instance.writebytes(path, bcontent)
示例8: test_decodebytes
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def test_decodebytes(self):
eq = self.assertEqual
eq(base64.decodebytes(b"d3d3LnB5dGhvbi5vcmc=\n"), b"www.python.org")
eq(base64.decodebytes(b"YQ==\n"), b"a")
eq(base64.decodebytes(b"YWI=\n"), b"ab")
eq(base64.decodebytes(b"YWJj\n"), b"abc")
eq(base64.decodebytes(b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNT"
b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==\n"),
b"abcdefghijklmnopqrstuvwxyz"
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
b"0123456789!@#0^&*();:<>,. []{}")
eq(base64.decodebytes(b''), b'')
# Non-bytes
eq(base64.decodebytes(bytearray(b'YWJj\n')), b'abc')
eq(base64.decodebytes(memoryview(b'YWJj\n')), b'abc')
eq(base64.decodebytes(array('B', b'YWJj\n')), b'abc')
self.check_type_errors(base64.decodebytes)
示例9: setUp
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def setUp(self):
if not os.path.isdir(LOCALEDIR):
os.makedirs(LOCALEDIR)
with open(MOFILE, 'wb') as fp:
fp.write(base64.decodebytes(GNU_MO_DATA))
with open(MOFILE_BAD_MAJOR_VERSION, 'wb') as fp:
fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MAJOR_VERSION))
with open(MOFILE_BAD_MINOR_VERSION, 'wb') as fp:
fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MINOR_VERSION))
with open(UMOFILE, 'wb') as fp:
fp.write(base64.decodebytes(UMO_DATA))
with open(MMOFILE, 'wb') as fp:
fp.write(base64.decodebytes(MMO_DATA))
self.env = support.EnvironmentVarGuard()
self.env['LANGUAGE'] = 'xx'
gettext._translations.clear()
示例10: decode
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def decode(self, data):
self.data = base64.decodebytes(data)
示例11: getparser
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def getparser(use_datetime=False, use_builtin_types=False):
"""getparser() -> parser, unmarshaller
Create an instance of the fastest available parser, and attach it
to an unmarshalling object. Return both objects.
"""
if FastParser and FastUnmarshaller:
if use_builtin_types:
mkdatetime = _datetime_type
mkbytes = base64.decodebytes
elif use_datetime:
mkdatetime = _datetime_type
mkbytes = _binary
else:
mkdatetime = _datetime
mkbytes = _binary
target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault)
parser = FastParser(target)
else:
target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types)
if FastParser:
parser = FastParser(target)
else:
parser = ExpatParser(target)
return parser, target
##
# Convert a Python tuple or a Fault instance to an XML-RPC packet.
#
# @def dumps(params, **options)
# @param params A tuple or Fault instance.
# @keyparam methodname If given, create a methodCall request for
# this method name.
# @keyparam methodresponse If given, create a methodResponse packet.
# If used with a tuple, the tuple must be a singleton (that is,
# it must contain exactly one element).
# @keyparam encoding The packet encoding.
# @return A string containing marshalled data.
示例12: open_data
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def open_data(self, url, data=None):
"""Use "data" URL."""
if not isinstance(url, str):
raise URLError('data error: proxy support for data protocol currently not implemented')
# ignore POSTed data
#
# syntax of data URLs:
# dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
# mediatype := [ type "/" subtype ] *( ";" parameter )
# data := *urlchar
# parameter := attribute "=" value
try:
[type, data] = url.split(',', 1)
except ValueError:
raise IOError('data error', 'bad data URL')
if not type:
type = 'text/plain;charset=US-ASCII'
semi = type.rfind(';')
if semi >= 0 and '=' not in type[semi:]:
encoding = type[semi+1:]
type = type[:semi]
else:
encoding = ''
msg = []
msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
time.gmtime(time.time())))
msg.append('Content-type: %s' % type)
if encoding == 'base64':
# XXX is this encoding/decoding ok?
data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
else:
data = unquote(data)
msg.append('Content-Length: %d' % len(data))
msg.append('')
msg.append(data)
msg = '\n'.join(msg)
headers = email.message_from_string(msg)
f = io.StringIO(msg)
#f.fileno = None # needed for addinfourl
return addinfourl(f, headers, url)
示例13: construct_yaml_binary
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def construct_yaml_binary(self, node):
try:
value = self.construct_scalar(node).encode('ascii')
except UnicodeEncodeError as exc:
raise ConstructorError(None, None,
"failed to convert base64 data into ascii: %s" % exc,
node.start_mark)
try:
if hasattr(base64, 'decodebytes'):
return base64.decodebytes(value)
else:
return base64.decodestring(value)
except binascii.Error as exc:
raise ConstructorError(None, None,
"failed to decode base64 data: %s" % exc, node.start_mark)
示例14: construct_python_bytes
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def construct_python_bytes(self, node):
try:
value = self.construct_scalar(node).encode('ascii')
except UnicodeEncodeError as exc:
raise ConstructorError(None, None,
"failed to convert base64 data into ascii: %s" % exc,
node.start_mark)
try:
if hasattr(base64, 'decodebytes'):
return base64.decodebytes(value)
else:
return base64.decodestring(value)
except binascii.Error as exc:
raise ConstructorError(None, None,
"failed to decode base64 data: %s" % exc, node.start_mark)
示例15: download_dictionary
# 需要导入模块: import base64 [as 别名]
# 或者: from base64 import decodebytes [as 别名]
def download_dictionary(url, dest):
"""Download a decoded dictionary file."""
response = urllib.request.urlopen(url)
decoded = base64.decodebytes(response.read())
with open(dest, 'bw') as dict_file:
dict_file.write(decoded)