Python 3.12 分块暂存实战:用 SpooledTemporaryFile 分开转存阈值与总量上限
分块下载、导出报表或接收生成器输出时,下游有时需要一个能够回读的文件对象,而不是一串只能遍历一次的数据块。把所有块先放进列表再拼接很直接,却容易让缓存策略和业务大小限制混在一起。本文用 Python 3.12 的 SpooledTemporaryFile 做一个小型采集器:先收集,再回到开头供下游读取,离开作用域就关闭。

一、阈值不是容量配额
二进制模式下,数据最初在内存中暂存;顺序写入使大小超过 max_size 后,会转入 TemporaryFile 支持的临时文件。刚好等于阈值不触发这次转换。显式调用 rollover() 或调用 fileno() 也会触发转存,因此获取文件描述符不是无副作用的状态查询。参见 Python 3.12 官方说明。
另一个容易误读的地方是 max_size=0。在本次核验的 CPython 3.12.14 顺序 write() 路径中,它关闭按写入大小自动转存的判断,并不表示“内存最多使用零字节”。这一点对照了 对应版本官方源码,并在下方测试中验证。这里不把该结论扩展成所有方法的通用规则,例如 truncate() 有自己的处理路径。
所以示例使用两个独立参数:memory_threshold 必须为正整数,控制何时转换暂存方式;total_limit 是非负整数,控制本次采集允许写入的累计字节数。前者设置成 8 字节,并不妨碍收集 11 字节;只有后者才负责拒绝超量。布尔值虽然属于整数的子类,本接口仍拒绝它,避免把开关误传成额度。
二、先定义输入与资源所有权
采集器只接受可迭代的数据块,每块必须恰好是 bytes 类型。字符串、bytearray、memoryview 和 bytes 子类都明确拒绝;这是本文接口的收紧约定,不是说标准库二进制流只能接收 bytes。需要文本编码或可变缓冲区转换时,请在生产端显式处理,别让采集器猜编码或悄悄复制。
单独传入 b'abc' 也会报错,因为遍历它得到的是整数,不是三块字节串。调用者应传入 [b'abc'] 或真正逐块产生 bytes 的迭代器。每块在写入前检查累计大小,一旦超量便抛出 ValueError,不静默截断,不继续消费后续块,也不会把半份结果交给使用者。
下面保存为 spooled_chunks.py。它借助 contextmanager 把临时流的生命周期包在 with 内:采集失败、下游抛错与正常结束都走关闭路径。原始迭代器及其网络连接仍由调用者管理,本函数只拥有自己创建的临时流。
from collections.abc import Iterable, Iterator
from contextlib import contextmanager
import tempfile
from typing import BinaryIO
@contextmanager
def gather_chunks(
chunks: Iterable[bytes],
*,
memory_threshold: int = 1024 * 1024,
total_limit: int = 8 * 1024 * 1024,
) -> Iterator[BinaryIO]:
"""Gather exact bytes chunks; lend a rewound stream inside with only."""
if type(memory_threshold) is not int:
raise TypeError('memory_threshold must be an int')
if memory_threshold <= 0:
raise ValueError('memory_threshold must be positive')
if type(total_limit) is not int:
raise TypeError('total_limit must be an int')
if total_limit < 0:
raise ValueError('total_limit must be nonnegative')
if isinstance(chunks, (str, bytes, bytearray, memoryview)):
raise TypeError('pass an iterable of bytes chunks, not one value')
with tempfile.SpooledTemporaryFile(
max_size=memory_threshold, mode='w+b'
) as stream:
total = 0
for chunk in chunks:
if type(chunk) is not bytes:
raise TypeError('each chunk must be an exact bytes object')
next_total = total + len(chunk)
if next_total > total_limit:
raise ValueError('total byte limit exceeded')
stream.write(chunk)
total = next_total
stream.seek(0)
yield stream
if __name__ == '__main__':
with gather_chunks(
[b'alpha,', b'beta\n'], memory_threshold=8, total_limit=32
) as result:
print(result.read())三、读之前回到起点,退出后不要再使用
写入结束时游标通常在末尾,直接 read() 会读到空结果,并不代表数据丢了。采集器在交出流之前执行 seek(0),使用者可直接读取;需要第二次完整读取时,仍应自行回到开头。游标接口见 官方 seek() 文档。
这里交出的是可读写流,并没有包装成只读对象。total_limit 只约束交出流之前的采集阶段,不限制调用者随后自行 write() 的行为。因此下游应按“借用来读取”的约定使用它,不能把对象保存起来等 with 结束后再读。对需要文件描述符的库,可以让它调用 fileno(),但要接受这会改变暂存状态。
四、完整测试与复现命令
将下面文件保存为 test_spooled_chunks.py,与实现放在同一目录。测试覆盖顺序拼接、空块、精确总量、超量停止、严格类型、游标以及各类异常后的关闭;转存测试用 unittest.mock 包装公开的 TemporaryFile 构造入口,观察是否创建临时文件,不读取私有状态,也不据此推断物理存储介质。
import tempfile
import unittest
from unittest.mock import patch
from spooled_chunks import gather_chunks
class GatherTests(unittest.TestCase):
def assert_rejected(self, error, chunks=(), **options):
with self.assertRaises(error):
with gather_chunks(chunks, **options):
self.fail('invalid input reached the consumer')
def test_empty_zero_limit(self):
with gather_chunks([], total_limit=0) as stream:
self.assertEqual(stream.read(), b'')
def test_join_order(self):
with gather_chunks([b'ab', b'cd']) as stream:
self.assertEqual(stream.read(), b'abcd')
def test_empty_chunks(self):
with gather_chunks([b'', b'a', b'']) as stream:
self.assertEqual(stream.read(), b'a')
def test_generator(self):
with gather_chunks(bytes([i]) for i in range(3)) as stream:
self.assertEqual(stream.read(), b'\x00\x01\x02')
def test_binary_preserved(self):
with gather_chunks([b'\xff\x00\r\n']) as stream:
self.assertEqual(stream.read(), b'\xff\x00\r\n')
def test_rewound_and_seekable(self):
with gather_chunks([b'abcd']) as stream:
self.assertEqual(stream.tell(), 0)
self.assertEqual(stream.read(2), b'ab')
stream.seek(1)
self.assertEqual(stream.read(), b'bcd')
def test_exact_total_limit(self):
with gather_chunks([b'ab', b'cd'], total_limit=4) as stream:
self.assertEqual(stream.read(), b'abcd')
def test_first_chunk_too_large(self):
self.assert_rejected(ValueError, [b'abc'], total_limit=2)
def test_later_chunk_too_large(self):
self.assert_rejected(ValueError, [b'ab', b'cd'], total_limit=3)
def test_stops_at_offending_chunk(self):
consumed = []
def chunks():
for item in [b'ab', b'cd', b'ef']:
consumed.append(item)
yield item
self.assert_rejected(ValueError, chunks(), total_limit=3)
self.assertEqual(consumed, [b'ab', b'cd'])
def test_zero_limit_rejects_nonempty(self):
self.assert_rejected(ValueError, [b'a'], total_limit=0)
def test_text_chunk_rejected(self):
self.assert_rejected(TypeError, ['abc'])
def test_mutable_and_view_chunks_rejected(self):
for item in [bytearray(b'a'), memoryview(b'a')]:
with self.subTest(type=type(item).__name__):
self.assert_rejected(TypeError, [item])
def test_number_and_none_chunks_rejected(self):
for item in [1, None]:
with self.subTest(item=item):
self.assert_rejected(TypeError, [item])
def test_bytes_subclass_rejected(self):
class CustomBytes(bytes):
pass
self.assert_rejected(TypeError, [CustomBytes(b'a')])
def test_single_value_container_rejected(self):
for value in [b'a', 'a', bytearray(b'a'), memoryview(b'a')]:
with self.subTest(type=type(value).__name__):
self.assert_rejected(TypeError, value)
def test_noniterable_rejected(self):
self.assert_rejected(TypeError, 123)
def test_threshold_type_rejected(self):
for value in [True, 1.5, '8']:
with self.subTest(value=value):
self.assert_rejected(TypeError, memory_threshold=value)
def test_threshold_range_rejected(self):
for value in [0, -1]:
with self.subTest(value=value):
self.assert_rejected(ValueError, memory_threshold=value)
def test_total_limit_type_rejected(self):
for value in [False, 1.5, '8']:
with self.subTest(value=value):
self.assert_rejected(TypeError, total_limit=value)
def test_total_limit_range_rejected(self):
self.assert_rejected(ValueError, total_limit=-1)
def test_threshold_not_total_limit(self):
with gather_chunks([b'ab', b'cd'], memory_threshold=1,
total_limit=4) as stream:
self.assertEqual(stream.read(), b'abcd')
def test_closed_after_normal_exit(self):
with gather_chunks([b'a']) as stream:
self.assertFalse(stream.closed)
self.assertTrue(stream.closed)
with self.assertRaises(ValueError):
stream.read()
def test_closed_after_consumer_exception(self):
with self.assertRaisesRegex(RuntimeError, 'consumer'):
with gather_chunks([b'a']) as stream:
raise RuntimeError('consumer')
self.assertTrue(stream.closed)
def test_closed_after_producer_exception(self):
actual = tempfile.SpooledTemporaryFile()
def broken():
yield b'a'
raise RuntimeError('producer')
with patch('spooled_chunks.tempfile.SpooledTemporaryFile',
return_value=actual):
self.assert_rejected(RuntimeError, broken())
self.assertTrue(actual.closed)
def test_closed_after_validation_error(self):
actual = tempfile.SpooledTemporaryFile()
with patch('spooled_chunks.tempfile.SpooledTemporaryFile',
return_value=actual):
self.assert_rejected(TypeError, [b'a', 'wrong'])
self.assertTrue(actual.closed)
def test_closed_after_total_limit_error(self):
actual = tempfile.SpooledTemporaryFile()
with patch('spooled_chunks.tempfile.SpooledTemporaryFile',
return_value=actual):
self.assert_rejected(ValueError, [b'ab'], total_limit=1)
self.assertTrue(actual.closed)
class RolloverTests(unittest.TestCase):
# Observe public TemporaryFile construction, not private spool attributes.
def test_initially_no_temporary_file(self):
with patch('tempfile.TemporaryFile', wraps=tempfile.TemporaryFile) as make:
with tempfile.SpooledTemporaryFile(max_size=4):
make.assert_not_called()
def test_exact_threshold_stays_unrolled(self):
with patch('tempfile.TemporaryFile', wraps=tempfile.TemporaryFile) as make:
with tempfile.SpooledTemporaryFile(max_size=4) as stream:
stream.write(b'abcd')
make.assert_not_called()
def test_above_threshold_creates_file(self):
with patch('tempfile.TemporaryFile', wraps=tempfile.TemporaryFile) as make:
with tempfile.SpooledTemporaryFile(max_size=4) as stream:
stream.write(b'abcde')
make.assert_called_once()
stream.seek(0)
self.assertEqual(stream.read(), b'abcde')
def test_zero_disables_write_size_trigger(self):
with patch('tempfile.TemporaryFile', wraps=tempfile.TemporaryFile) as make:
with tempfile.SpooledTemporaryFile(max_size=0) as stream:
stream.write(b'x' * 10000)
make.assert_not_called()
stream.seek(0)
self.assertEqual(len(stream.read()), 10000)
def test_explicit_rollover_preserves_position(self):
with patch('tempfile.TemporaryFile', wraps=tempfile.TemporaryFile) as make:
with tempfile.SpooledTemporaryFile(max_size=100) as stream:
stream.write(b'abcd')
stream.seek(1)
stream.rollover()
make.assert_called_once()
self.assertEqual(stream.tell(), 1)
self.assertEqual(stream.read(), b'bcd')
def test_fileno_forces_rollover_with_zero_threshold(self):
with patch('tempfile.TemporaryFile', wraps=tempfile.TemporaryFile) as make:
with tempfile.SpooledTemporaryFile(max_size=0) as stream:
stream.write(b'ab')
self.assertIsInstance(stream.fileno(), int)
make.assert_called_once()
stream.seek(0)
self.assertEqual(stream.read(), b'ab')
def test_repeated_rollover_reuses_file(self):
with patch('tempfile.TemporaryFile', wraps=tempfile.TemporaryFile) as make:
with tempfile.SpooledTemporaryFile(max_size=4) as stream:
stream.rollover()
stream.rollover()
stream.fileno()
make.assert_called_once()
def test_read_at_write_end_needs_seek(self):
with tempfile.SpooledTemporaryFile(max_size=4) as stream:
stream.write(b'ab')
self.assertEqual(stream.read(), b'')
stream.seek(0)
self.assertEqual(stream.read(), b'ab')
if __name__ == '__main__':
unittest.main()在这两个文件所在目录执行以下命令,无需第三方依赖:
python3.12 --version python3.12 spooled_chunks.py python3.12 -m unittest -v test_spooled_chunks.py
本文实际运行环境为 Linux x86_64、CPython 3.12.14;35 个 unittest 测试方法全部通过,失败、错误、跳过均为 0。部分方法还含多个子测试,未把子测试另算成方法数。演示输出如下;测试耗时不作为性能结论。
b'alpha,beta\n'
五、上线前仍要补齐的边界
字节额度不是进程内存硬上限。生产端可能先构造了一个巨大数据块,检查时这块已经存在;转存前的一次写入也可能跨过阈值。下游如果调用无参数 read(),还会把全部内容读成一个 bytes。大结果应按固定大小读取,源端也应控制单块大小,不能只靠这个封装解决所有资源问题。
同样,零长度块不会增加累计字节数,无限空块或阻塞的生产器不会被 total_limit 终止。真实服务还应在外围设置超时、取消机制及必要的块数限制。临时目录空间不足或文件操作失败时,异常仍会向上传递;不要把它伪装成一次成功但内容为空的采集。
最后,自动关闭与临时文件清理不等于安全擦除,也不能证明数据一定进入某种物理介质。本文没有做速度比较或此类保证。这个工具解决的是清晰的暂存生命周期和输入总量检查:阈值负责切换,额度负责拒绝,with 负责收尾,三件事各自独立。

