當前位置: 首頁>>代碼示例>>Python>>正文


Python base64.decodebytes方法代碼示例

本文整理匯總了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 
開發者ID:BasioMeusPuga,項目名稱:Lector,代碼行數:19,代碼來源:read_fb2.py

示例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 
開發者ID:bomquote,項目名稱:transistor,代碼行數:19,代碼來源:utils.py

示例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} 
開發者ID:yizt,項目名稱:crnn.pytorch,代碼行數:18,代碼來源:rest.py

示例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) 
開發者ID:lukaabra,項目名稱:SubCrawl,代碼行數:24,代碼來源:subtitles.py

示例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) 
開發者ID:Tribler,項目名稱:py-ipv8,代碼行數:23,代碼來源:community.py

示例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 
開發者ID:IMYR666,項目名稱:any-captcha,代碼行數:24,代碼來源:utils.py

示例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) 
開發者ID:jpmorganchase,項目名稱:jupyter-fs,代碼行數:24,代碼來源:fsmanager.py

示例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) 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:20,代碼來源:test_base64.py

示例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() 
開發者ID:Microvellum,項目名稱:Fluid-Designer,代碼行數:18,代碼來源:test_gettext.py

示例10: decode

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import decodebytes [as 別名]
def decode(self, data):
        self.data = base64.decodebytes(data) 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:4,代碼來源:client.py

示例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. 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:40,代碼來源:client.py

示例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) 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:42,代碼來源:request.py

示例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) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:17,代碼來源:constructor.py

示例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) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:17,代碼來源:constructor.py

示例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) 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:8,代碼來源:dictcli.py


注:本文中的base64.decodebytes方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。