Base64 Decode Unexpected Continuation Byte Remove
Python base64.decodebytes() Examples
The following are 30 code examples of base64.decodebytes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module base64 , or try the search function
.
Example #1
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 Example #2
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) Example #3
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) Example #4
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) Example #5
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 Example #6
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} Example #7
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)
Example #8
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) Example #9
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 Example #10
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) Example #11
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) Example #12
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()
Example #13
def decode(self, data): self.data = base64.decodebytes(data)
Example #14
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.
Example #15
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) Example #16
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) Example #17
def decode(self, data): self.data = base64.decodebytes(data)
Example #18
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.
Example #19
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) Example #20
def decode(self, data): self.data = base64.decodebytes(data)
Example #21
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.
Example #22
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)
Example #23
def decodebytes(self, text): aes = self.aes() return str(aes.decrypt(base64.decodebytes(bytes( text, encoding='utf8'))).rstrip(b'\0').decode("utf8")) # 解密 Example #24
def submit_file(self, file: dict, url_for_file: str) -> dict: type_number = "0" if url_for_file: type_number = "2" return self._make_login_request( "POST", "fileupload.php", json_data={'data': json.dumps({'data': {"url": url_for_file, "submitType": type_number}})}, files={'amas_filename': base64.decodebytes(file.get('content').encode('utf-8'))} ) Example #25
def _save_file(self, path, content, format): """Uploads content of a generic file to GCS. :param: path blob path. :param: content file contents string. :param: format the description of the input format, can be either "text" or "base64". :return: created :class:`google.cloud.storage.Blob`. """ bucket_name, bucket_path = self._parse_path(path) bucket = self._get_bucket(bucket_name, throw=True) if format not in {"text", "base64"}: raise web.HTTPError( 400, u"Must specify format of file contents as \"text\" or " u"\"base64\"", ) try: if format == "text": bcontent = content.encode("utf8") else: b64_bytes = content.encode("ascii") bcontent = base64.decodebytes(b64_bytes) except Exception as e: raise web.HTTPError( 400, u"Encoding error saving %s: %s" % (path, e) ) blob = bucket.blob(bucket_path) blob.upload_from_string(bcontent) return blob Example #26
def test_get_base64(self): bucket = self.bucket blob = bucket.blob("test.pickle") obj = {"one": 1, "two": [2, 3]} blob.upload_from_string(pickle.dumps(obj)) model = self.contents_manager.get( self.path("test.pickle"), format="base64") self.assertEqual(model["type"], "file") self.assertEqual(model["mimetype"], "application/octet-stream") self.assertEqual(model["format"], "base64") content = model["content"] self.assertIsInstance(content, unicode) bd = base64.decodebytes(content.encode()) self.assertEqual(obj, pickle.loads(bd)) Example #27
def decode_function(self, *args, **kwargs): """Decode b64 encoded data""" if self.is_python31_or_newer(): # pylint: disable=E1101 return base64.decodebytes(*args, **kwargs) # pylint: disable=W1505 return base64.decodestring(*args, **kwargs)
Example #28
def test_AUTH_CRAM_MD5_reject(self): """ Makes sure the server rejects all invalid login attempts that use the CRAM-MD5 Authentication method. """ def encode_cram_md5(challenge, user, password): challenge = base64.decodebytes(challenge) response = user + b' ' + bytes( hmac.HMAC(password, challenge, digestmod="md5").hexdigest(), 'utf-8') return str(base64.b64encode(response), 'utf-8') def smtp_auth_cram_md5(): smtp_ = smtplib.SMTP( '127.0.0.1', 8888, local_hostname='localhost', timeout=15) _, resp = smtp_.docmd('AUTH', 'CRAM-MD5') code, resp = smtp_.docmd(encode_cram_md5(resp, b'test', b'test')) smtp_.quit() # For now, the server's going to return a 535 code. self.assertEqual(code, 535) options = { 'enabled': 'True', 'port': 8888, 'protocol_specific_data': { 'banner': 'Test' }, 'users': { 'someguy': 'test' } } smtp_cap = smtp.smtp(options, self.loop) server_coro = asyncio.start_server( smtp_cap.handle_session, '0.0.0.0', 8888, loop=self.loop) self.server = self.loop.run_until_complete(server_coro) smtp_task = self.loop.run_in_executor(None, smtp_auth_cram_md5) self.loop.run_until_complete(smtp_task) Example #29
def b64decode(val): try: return base64.decodebytes(val.encode("utf-8")) except AttributeError: return base64.decodestring(val) Example #30
def b64decode(thing): return base64.decodebytes(bytes(thing, encoding='UTF-8'))
Source: https://www.programcreek.com/python/example/76386/base64.decodebytes
0 Response to "Base64 Decode Unexpected Continuation Byte Remove"
Postar um comentário