【问题标题】:Converting a zip file to bytea to store in postgres - python将 zip 文件转换为 bytea 以存储在 postgres 中 - python
【发布时间】:2020-11-18 04:19:00
【问题描述】:

我想使用 python 将 zip 文件存储在 postgres 数据库中。

看起来这应该很容易,但我无法解决。

这是我尝试过的 - 我的问题是如何将 zipfile 转换为 bytea 对象。

from zipfile import ZipFile
from io import BytesIO, StringIO


filename = "test.zip"
with ZipFile(filename, 'w') as zip_archive:
    binary_stream = BytesIO(zip_archive)

def store_blob(filename, blob):
    with db.engine.connect() as connection:
        res = connection.execute('''INSERT INTO test (filename, model_file) VALUES (%s,                     %s)''', (filename, blob ))


store_blob(filename, binary_stream)

【问题讨论】:

  • 为什么要打开文件进行写入?
  • 正在尝试转换为 bytea - 有没有办法在不打开它的情况下做到这一点?
  • 文件test.zip是否已经存在?
  • 是的,我只需要将它从磁盘获取到数据库
  • 您观察到的实际错误是什么?如果您添加错误消息或堆栈跟踪,则有更多机会正确诊断问题。

标签: python postgresql sqlalchemy bytea


【解决方案1】:

如果文件已经存在,那么你的代码应该是这样的:

def store_blob(filename, blob):
    with db.engine.connect() as connection:
        res = connection.execute(
             '''INSERT INTO test (filename, model_file) VALUES (%s,%s)''', 
             (filename, blob ))

filename = "test.zip"
with open(filename, 'rb') as zip_archive:
    store_blob(filename, zip_archive.read())

您的代码不需要知道文件的格式。您要做的就是使用binary 标志为read 打开它以防止解码,并将其read()(产生b'')作为参数传递给execute()

【讨论】:

    【解决方案2】:

    我相信这里已经有一个公认的答案Storing Zip file in Postgres

    您可以使用上述答案中演示的bin2hex() 函数。

    关于 postgres bytea 数据类型的信息:https://www.postgresql.org/docs/current/datatype-binary.html#AEN5318

    【讨论】:

    • OP 专门询问 python 实现,而不是 php。
    猜你喜欢
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    相关资源
    最近更新 更多