繁体   English   中英

将 zip 文件转换为 bytea 以存储在 postgres 中 - python

[英]Converting a zip file to bytea to store in postgres - python

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

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

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

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)

如果文件已经存在,那么您的代码应如下所示:

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()

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

您可以使用bin2hex() function 如上述答案所示。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM