You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用peewee在SQLite中存储二进制数据及解决io.BytesIO()存储报错

在Peewee的BlobField中存储二进制数据及解决BytesIO报错问题

首先,Peewee的BlobField本身就是用来存储二进制数据的,但它只接受bytes、memoryview或BigBitFieldData实例作为合法输入——这也是你触发ValueError的核心原因:io.BytesIO()是一个内存字节流对象,并非直接的字节数据类型。

一、BlobField存储二进制数据的常规正确姿势

最直接的方式是传递bytes类型数据,这也是日常开发中最常用的场景:

  1. 直接使用现成的字节数据赋值
from peewee import Model, BlobField, SqliteDatabase

# 初始化数据库连接
db = SqliteDatabase('my_database.db')

# 定义模型
class BinaryStorage(Model):
    content = BlobField()

    class Meta:
        database = db

# 首次运行需创建表
db.create_tables([BinaryStorage])

# 存储bytes类型数据
raw_bytes = b"Sample binary content for BlobField"
BinaryStorage.create(content=raw_bytes)
  1. 从本地文件读取二进制数据存储
# 读取图片、音频等二进制文件
with open('my_image.png', 'rb') as f:
    file_bytes = f.read()
BinaryStorage.create(content=file_bytes)

二、解决io.BytesIO()数据的存储报错问题

io.BytesIO()是内存中的字节流容器,要存入BlobField,只需调用它的getvalue()方法转换成bytes类型即可:

import io

# 假设你有一个已初始化的BytesIO对象
bytes_stream = io.BytesIO(b"Data stored in BytesIO")
# 转换为BlobField接受的bytes类型
converted_data = bytes_stream.getvalue()

# 存入数据库
BinaryStorage.create(content=converted_data)

如果你的BytesIO是通过写入数据生成的,无需额外调整指针位置(getvalue()会返回整个缓冲区的内容,不受当前指针位置影响):

bytes_stream = io.BytesIO()
bytes_stream.write(b"Data written into BytesIO stream")
# 直接转换并存储
converted_data = bytes_stream.getvalue()
BinaryStorage.create(content=converted_data)

补充:从BlobField读取数据转回BytesIO

如果需要把读取到的bytes数据重新转换成BytesIO对象,直接将bytes传入构造器即可:

# 读取数据库中的记录
record = BinaryStorage.get()
# 转回BytesIO
recovered_stream = io.BytesIO(record.content)

内容的提问来源于stack exchange,提问作者Leopoldo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:04:28