本文整理汇总了Python中zlib.decompress方法的典型用法代码示例。如果您正苦于以下问题:Python zlib.decompress方法的具体用法?Python zlib.decompress怎么用?Python zlib.decompress使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类zlib
的用法示例。
在下文中一共展示了zlib.decompress方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def run(self):
print("VEDIO server starts...")
self.sock.bind(self.ADDR)
self.sock.listen(1)
conn, addr = self.sock.accept()
print("remote VEDIO client success connected...")
data = "".encode("utf-8")
payload_size = struct.calcsize("L")
cv2.namedWindow('Remote', cv2.WINDOW_AUTOSIZE)
while True:
while len(data) < payload_size:
data += conn.recv(81920)
packed_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("L", packed_size)[0]
while len(data) < msg_size:
data += conn.recv(81920)
zframe_data = data[:msg_size]
data = data[msg_size:]
frame_data = zlib.decompress(zframe_data)
frame = pickle.loads(frame_data)
cv2.imshow('Remote', frame)
if cv2.waitKey(1) & 0xFF == 27:
break
示例2: sortReads
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def sortReads(inReadsFile, outReadsFile, headerToNum=lambda x: int(x.split('_', 2)[1].strip('nr'))):
i = 0
seqName = None
tupleList = []
for line in csv.getColumnAsList(inReadsFile, sep='\n'):
if i % 2 == 0:
seqName = line
else:
seq = line
assert seqName is not None
tupleList.append((seqName, zlib.compress(seq), headerToNum(seqName)))
seqName = None
i += 1
tupleList.sort(key=lambda x: x[2])
out = csv.OutFileBuffer(outReadsFile)
for t in tupleList:
out.writeText(str(t[0]) + '\n' + str(zlib.decompress(t[1])) + '\n')
out.close()
示例3: _decompressContent
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get("content-encoding", None)
if encoding in ["gzip", "deflate"]:
if encoding == "gzip":
content = gzip.GzipFile(fileobj=io.BytesIO(new_content)).read()
if encoding == "deflate":
content = zlib.decompress(content, -zlib.MAX_WBITS)
response["content-length"] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response["-content-encoding"] = response["content-encoding"]
del response["content-encoding"]
except (IOError, zlib.error):
content = ""
raise FailedToDecompressContent(
_("Content purported to be compressed with %s but failed to decompress.")
% response.get("content-encoding"),
response,
content,
)
return content
示例4: _decompressContent
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get("content-encoding", None)
if encoding in ["gzip", "deflate"]:
if encoding == "gzip":
content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read()
if encoding == "deflate":
content = zlib.decompress(content, -zlib.MAX_WBITS)
response["content-length"] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response["-content-encoding"] = response["content-encoding"]
del response["content-encoding"]
except (IOError, zlib.error):
content = ""
raise FailedToDecompressContent(
_("Content purported to be compressed with %s but failed to decompress.")
% response.get("content-encoding"),
response,
content,
)
return content
示例5: reference_path
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def reference_path():
# download chr4 from ucsc if needed
reference_path = "data/chr4.fa"
if not os.path.exists(reference_path):
import urllib.request
import zlib
url = "http://hgdownload.cse.ucsc.edu/goldenPath/hg19/chromosomes/chr4.fa.gz"
resource = urllib.request.urlopen(url)
with open(reference_path, "w") as outf:
data = zlib.decompress(resource.read(), 16+zlib.MAX_WBITS).decode("utf-8")
outf.write(data)
return reference_path
示例6: _get_decompress_func
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def _get_decompress_func():
global _importing_zlib
if _importing_zlib:
# Someone has a zlib.py[co] in their Zip file
# let's avoid a stack overflow.
_bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')
raise ZipImportError("can't decompress data; zlib not available")
_importing_zlib = True
try:
from zlib import decompress
except Exception:
_bootstrap._verbose_message('zipimport: zlib UNAVAILABLE')
raise ZipImportError("can't decompress data; zlib not available")
finally:
_importing_zlib = False
_bootstrap._verbose_message('zipimport: zlib available')
return decompress
# Given a path to a Zip file and a toc_entry, return the (uncompressed) data.
示例7: load_payload
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def load_payload(self, payload, *args, **kwargs):
decompress = False
if payload.startswith(b"."):
payload = payload[1:]
decompress = True
try:
json = base64_decode(payload)
except Exception as e:
raise BadPayload(
"Could not base64 decode the payload because of an exception",
original_error=e,
)
if decompress:
try:
json = zlib.decompress(json)
except Exception as e:
raise BadPayload(
"Could not zlib decompress the payload before decoding the payload",
original_error=e,
)
return super(URLSafeSerializerMixin, self).load_payload(json, *args, **kwargs)
示例8: _loads_v2
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def _loads_v2(self, request, data):
try:
cached = json.loads(zlib.decompress(data).decode("utf8"))
except ValueError:
return
# We need to decode the items that we've base64 encoded
cached["response"]["body"] = _b64_decode_bytes(
cached["response"]["body"]
)
cached["response"]["headers"] = dict(
(_b64_decode_str(k), _b64_decode_str(v))
for k, v in cached["response"]["headers"].items()
)
cached["response"]["reason"] = _b64_decode_str(
cached["response"]["reason"],
)
cached["vary"] = dict(
(_b64_decode_str(k), _b64_decode_str(v) if v is not None else v)
for k, v in cached["vary"].items()
)
return self.prepare_response(request, cached)
示例9: add_payload
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def add_payload(self, payload):
"""Parses (annotations processing) and adds payload data to a received message."""
assert not self.data
if len(payload) != self.data_size + self.annotations_size:
raise errors.ProtocolError("payload length doesn't match message header")
if self.annotations_size:
payload = memoryview(payload) # avoid copying
self.annotations = {}
i = 0
while i < self.annotations_size:
annotation_id = bytes(payload[i:i+4]).decode("ascii")
length = int.from_bytes(payload[i+4:i+8], "big")
self.annotations[annotation_id] = payload[i+8:i+8+length] # note: it stores a memoryview!
i += 8 + length
assert i == self.annotations_size
self.data = payload[self.annotations_size:]
else:
self.data = payload
if self.flags & FLAGS_COMPRESSED:
self.data = zlib.decompress(self.data)
self.flags &= ~FLAGS_COMPRESSED
self.data_size = len(self.data)
示例10: parse_content_encoding
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def parse_content_encoding(self, response_headers, response_data):
"""
Parses a response that contains Content-Encoding to retrieve
response_data
"""
if response_headers['content-encoding'] == 'gzip':
buf = StringIO.StringIO(response_data)
zipbuf = gzip.GzipFile(fileobj=buf)
response_data = zipbuf.read()
elif response_headers['content-encoding'] == 'deflate':
data = StringIO.StringIO(zlib.decompress(response_data))
response_data = data.read()
else:
raise errors.TestError(
'Received unknown Content-Encoding',
{
'content-encoding':
str(response_headers['content-encoding']),
'function': 'http.HttpResponse.parse_content_encoding'
})
return response_data
示例11: load_payload
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def load_payload(self, payload):
decompress = False
if payload.startswith(b'.'):
payload = payload[1:]
decompress = True
try:
json = base64_decode(payload)
except Exception as e:
raise BadPayload('Could not base64 decode the payload because of '
'an exception', original_error=e)
if decompress:
try:
json = zlib.decompress(json)
except Exception as e:
raise BadPayload('Could not zlib decompress the payload before '
'decoding the payload', original_error=e)
return super(URLSafeSerializerMixin, self).load_payload(json)
示例12: handle_table
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def handle_table(self, section):
"""Parse the table and store it in our lookup table."""
table_header = self.profile.ewf_table_header_v1(
vm=self.address_space, offset=section.obj_end)
number_of_entries = table_header.number_of_entries
# This is an optimization which allows us to avoid small reads for each
# chunk. We just load the entire table into memory and read it on demand
# from there.
table = array.array("I")
table.fromstring(self.address_space.read(
table_header.entries.obj_offset,
4 * table_header.number_of_entries))
# We assume the last chunk is a full chunk. Feeding zlib.decompress()
# extra data does not matter so we just read the most we can.
table.append(table[-1] + self.chunk_size)
self.tables.insert(
# First chunk for this table, table header, table entry cache.
(self._chunk_offset, table_header, table))
# The next table starts at this chunk.
self._chunk_offset += number_of_entries
示例13: _decompressContent
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get('content-encoding', None)
if encoding in ['gzip', 'deflate']:
if encoding == 'gzip':
content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read()
if encoding == 'deflate':
content = zlib.decompress(content)
response['content-length'] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response['-content-encoding'] = response['content-encoding']
del response['content-encoding']
except IOError:
content = ""
raise FailedToDecompressContent(_("Content purported to be compressed with %s but failed to decompress.") % response.get('content-encoding'), response, content)
return content
示例14: deserialize_graph
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def deserialize_graph(ser_graph, graph_cls=None):
from google.protobuf.message import DecodeError
from .serialize.protos.graph_pb2 import GraphDef
from .graph import DirectedGraph
graph_cls = graph_cls or DirectedGraph
ser_graph_bin = to_binary(ser_graph)
g = GraphDef()
try:
ser_graph = ser_graph
g.ParseFromString(ser_graph_bin)
return graph_cls.from_pb(g)
except DecodeError:
pass
try:
ser_graph_bin = zlib.decompress(ser_graph_bin)
g.ParseFromString(ser_graph_bin)
return graph_cls.from_pb(g)
except (zlib.error, DecodeError):
pass
json_obj = json.loads(to_str(ser_graph))
return graph_cls.from_json(json_obj)
示例15: loads
# 需要导入模块: import zlib [as 别名]
# 或者: from zlib import decompress [as 别名]
def loads(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None):
"""
Reverse of dumps(), raises BadSignature if signature fails.
The serializer is expected to accept a bytestring.
"""
# TimestampSigner.unsign always returns unicode but base64 and zlib
# compression operate on bytes.
base64d = force_bytes(TimestampSigner(key, salt=salt).unsign(s, max_age=max_age))
decompress = False
if base64d[:1] == b'.':
# It's compressed; uncompress it first
base64d = base64d[1:]
decompress = True
data = b64_decode(base64d)
if decompress:
data = zlib.decompress(data)
return serializer().loads(data)