本文整理匯總了Python中tempfile.SpooledTemporaryFile方法的典型用法代碼示例。如果您正苦於以下問題:Python tempfile.SpooledTemporaryFile方法的具體用法?Python tempfile.SpooledTemporaryFile怎麽用?Python tempfile.SpooledTemporaryFile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類tempfile
的用法示例。
在下文中一共展示了tempfile.SpooledTemporaryFile方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_basic
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def test_basic(): # type: () -> None
def fn(s):
f = File("Blah", s, mime_type="text/plain")
assert f.name == "Blah"
assert f._metadata["size"] == 14
assert f.size == 14
assert f._metadata["_checksum"] == "55e562bfee2bde4f9e71b8885eb5e303"
b = b"blah blah blah"
fn(io.BytesIO(b))
fn(memoryview(b))
import tempfile
f = tempfile.SpooledTemporaryFile()
f.write(b)
fn(f)
if six.PY2:
import StringIO
import cStringIO
fn(StringIO.StringIO(b))
fn(cStringIO.StringIO(b))
fn(buffer(b)) # noqa: F821
示例2: test_exports
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def test_exports(self):
# There are no surprising symbols in the tempfile module
dict = tempfile.__dict__
expected = {
"NamedTemporaryFile" : 1,
"TemporaryFile" : 1,
"mkstemp" : 1,
"mkdtemp" : 1,
"mktemp" : 1,
"TMP_MAX" : 1,
"gettempprefix" : 1,
"gettempdir" : 1,
"tempdir" : 1,
"template" : 1,
"SpooledTemporaryFile" : 1
}
unexp = []
for key in dict:
if key[0] != '_' and key not in expected:
unexp.append(key)
self.assertTrue(len(unexp) == 0,
"unexpected keys: %s" % unexp)
示例3: test_properties
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def test_properties(self):
f = tempfile.SpooledTemporaryFile(max_size=10)
f.write(b'x' * 10)
self.assertFalse(f._rolled)
self.assertEqual(f.mode, 'w+b')
self.assertIsNone(f.name)
with self.assertRaises(AttributeError):
f.newlines
with self.assertRaises(AttributeError):
f.encoding
f.write(b'x')
self.assertTrue(f._rolled)
self.assertEqual(f.mode, 'w+b')
self.assertIsNotNone(f.name)
with self.assertRaises(AttributeError):
f.newlines
with self.assertRaises(AttributeError):
f.encoding
示例4: _save_chunk
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def _save_chunk(self, data, chunk_info, executor=None):
# Keyname
key_name = f"{self.strax_unique_key}/{chunk_info['chunk_i']:06d}"
# Save chunk via temporary file
with tempfile.SpooledTemporaryFile() as f:
filesize = strax.save_file(f,
data=data,
compressor=self.md['compressor'])
f.seek(0)
self.s3.upload_fileobj(f,
BUCKET_NAME,
key_name,
Config=self.config)
return dict(key_name=key_name, filesize=filesize), None
示例5: mp3_to_wave
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def mp3_to_wave(self, filename):
mf = mad.MadFile(filename)
with tempfile.SpooledTemporaryFile() as f:
wav = wave.open(f, mode='wb')
wav.setframerate(mf.samplerate())
wav.setnchannels(1 if mf.mode() == mad.MODE_SINGLE_CHANNEL else 2)
# 4L is the sample width of 32 bit audio
wav.setsampwidth(4)
frame = mf.read()
while frame is not None:
wav.writeframes(frame)
frame = mf.read()
wav.close()
f.seek(0)
data = f.read()
return data
示例6: say
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def say(self, phrase):
if isinstance(phrase, unicode):
phrase = phrase.encode('utf8')
with tempfile.SpooledTemporaryFile() as out_f:
cmd = ['espeak', '-v', self.voice,
'-p', self.pitch_adjustment,
'-s', self.words_per_minute,
'--stdout',
phrase]
cmd = [str(x) for x in cmd]
self._logger.debug('Executing %s', ' '.join([pipes.quote(arg)
for arg in cmd]))
subprocess.call(cmd, stdout=out_f)
out_f.seek(0)
data = out_f.read()
return data
示例7: offer_fileobj
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def offer_fileobj(self, descriptor):
"""Opens a file-like temporary file spool and returns it.
If you use the return value in a `with` statement block then the file descriptor
auto-close.
NOTE: (!) This returns an ephemeral spool that is not attached to the caching mechanism
in save_credentials() and load_credentials()
Args:
descriptor (str): Descriptor of the current Output
Returns:
file object
"""
return tempfile.SpooledTemporaryFile(0, 'a+b')
示例8: pytest_configure
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def pytest_configure(config):
if config.option.verbose > 1:
root = logging.getLogger()
if not root.handlers:
root.addHandler(logging.NullHandler())
logging.getLogger("testinfra").setLevel(logging.DEBUG)
if config.option.nagios:
# disable & re-enable terminalreporter to write in a tempfile
reporter = config.pluginmanager.getplugin('terminalreporter')
if reporter:
out = SpooledTemporaryFile(encoding=sys.stdout.encoding)
config.pluginmanager.unregister(reporter)
reporter = reporter.__class__(config, out)
config.pluginmanager.register(reporter, 'terminalreporter')
config.pluginmanager.register(NagiosReporter(out),
'nagiosreporter')
示例9: plug_save
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def plug_save(Plug):
if hasattr(Plug, "loadingbar"):
# we have a loadingbar to attend to
loadcallback = Plug.loadingbar
else:
loadcallback = None
f = tempfile.SpooledTemporaryFile(10000000) # 10 megabyte ram file
set_header(f, Plug.header)
try:
Plug.tiles[0]
except:
Plug.tiles.seek(0)
f.write(Plug.tiles.read())
else:
set_tiles(f, Plug.tiles, Plug.header, True, loadcallback)
set_chests(f, Plug.chests)
set_signs(f, Plug.signs)
[set_npc(f, npc) for npc in Plug.npcs]
set_npc(f, None)
set_npc_names(f, Plug.names)
set_trail(f, (1, Plug.header["name"], Plug.header["ID"]))
with get_next_world(Plug.header["name"]).open("wb") as g:
f.seek(0)
g.write(f.read())
示例10: api_download
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def api_download(service, fileId, authorisation):
'''Given a Send url, download and return the encrypted data and metadata'''
data = tempfile.SpooledTemporaryFile(max_size=SPOOL_SIZE, mode='w+b')
headers = {'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode(authorisation)}
url = service + 'api/download/' + fileId
r = requests.get(url, headers=headers, stream=True)
r.raise_for_status()
content_length = int(r.headers['Content-length'])
pbar = progbar(content_length)
for chunk in r.iter_content(chunk_size=CHUNK_SIZE):
data.write(chunk)
pbar.update(len(chunk))
pbar.close()
data.seek(0)
return data
示例11: encrypt_file
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def encrypt_file(file, keys=secretKeys()):
'''Encrypt file data with the same method as the Send browser/js client'''
key = keys.encryptKey
iv = keys.encryptIV
encData = tempfile.SpooledTemporaryFile(max_size=SPOOL_SIZE, mode='w+b')
cipher = Cryptodome.Cipher.AES.new(key, Cryptodome.Cipher.AES.MODE_GCM, iv)
pbar = progbar(fileSize(file))
for chunk in iter(lambda: file.read(CHUNK_SIZE), b''):
encData.write(cipher.encrypt(chunk))
pbar.update(len(chunk))
pbar.close()
encData.write(cipher.digest())
file.close()
encData.seek(0)
return encData
示例12: default_stream_factory
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def default_stream_factory(
total_content_length, filename, content_type, content_length=None
):
"""The stream factory that is used per default."""
max_size = 1024 * 500
if SpooledTemporaryFile is not None:
return SpooledTemporaryFile(max_size=max_size, mode="wb+")
if total_content_length is None or total_content_length > max_size:
return TemporaryFile("wb+")
return BytesIO()
示例13: default_stream_factory
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def default_stream_factory(total_content_length, filename, content_type,
content_length=None):
"""The stream factory that is used per default."""
max_size = 1024 * 500
if SpooledTemporaryFile is not None:
return SpooledTemporaryFile(max_size=max_size, mode='wb+')
if total_content_length is None or total_content_length > max_size:
return TemporaryFile('wb+')
return BytesIO()
示例14: test_fileobj_without_name
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def test_fileobj_without_name(self):
# Issue #33038: GzipFile should not assume that file objects that have
# a .name attribute use a non-None value.
with tempfile.SpooledTemporaryFile() as f:
with gzip.GzipFile(fileobj=f, mode='wb') as archive:
archive.write(b'data')
self.assertEqual(archive.name, '')
示例15: do_create
# 需要導入模塊: import tempfile [as 別名]
# 或者: from tempfile import SpooledTemporaryFile [as 別名]
def do_create(self, max_size=0, dir=None, pre="", suf=""):
if dir is None:
dir = tempfile.gettempdir()
try:
file = tempfile.SpooledTemporaryFile(max_size=max_size, dir=dir, prefix=pre, suffix=suf)
except:
self.failOnException("SpooledTemporaryFile")
return file