使用 Python + psycopg2 处理二进制数据(DB:Postgres 9.5)

Handling of binary data with Python + psycopg2 (DB: Postgres 9.5)

假设我有 table 测试列 id(bigint 类型)和数据(bytea 类型) .

当我在 Python.

中执行以下查询时,我不想显示列 data 中的实际二进制数据
select * from test;

我只想要一个显示 <binary data><BLOB> 的占位符,因为该列中的一些数据以数百 MB 为单位,在列中显示二进制数据没有任何意义。


是否可以在 psycopg2 中用占位符识别和替换二进制数据?

#!/usr/bin/python

import psycopg2

conn = psycopg2.connect(database = "testdb", user = "postgres", password = "pass123", host = "127.0.0.1", port = "5432")
print "Opened database successfully"

cur = conn.cursor()

cur.execute("SELECT id, data from test")
rows = cur.fetchall()
for row in rows:
   print("ID = ", row[0])
   print("DATA = ", row[1])


print "Operation done successfully";
conn.close()

我们从数据库中获取结果并根据结果生成 html 报告,此处用户可以在 html 文本框中提供任何查询,因此查询不是静态的,我们执行该查询并生成 html table。这是内部报告生成脚本。

如果数据是 bytea,您可以编写自己的 bytea 类型转换程序作为包装二进制字符串的对象。

请注意,数据无论如何都是在网络上获取和发送的。如果您不想要这种开销,就不要 select 这些字段。

>>> import psycopg2

>>> class Wrapper:
...     def __init__(self, thing):
...         self.thing = thing
...         

>>> psycopg2.extensions.register_type(
...     psycopg2.extensions.new_type(
...         psycopg2.BINARY.values, "WRAPPER", lambda x, cur: Wrapper(x)))

>>> cnn = psycopg2.connect('')
>>> cur = cnn.cursor()
>>> cur.execute("create table btest(id serial primary key, data bytea)")
>>> cur.execute("insert into btest (data) values ('foobar')")
>>> cur.execute("select * from btest")
>>> r = cur.fetchone()
>>> r
(1, <__main__.Wrapper instance at 0x7fb8740eba70>)
>>> r[1].thing
'\x666f6f626172'

使用的extensions函数请参考文档。