我的flask应用程序中有一个带有ips字段数组的用户模型。我想使用inet类型的postgresql数组:

from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import ARRAY, INET, Integer, Unicode, Column
db = SQLAlchemy()

class User(db.Model):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    login = Column(Unicode(15))
    password = Column(Unicode(34))
    name = Column(Unicode(100))
    permitted_ips = Column(ARRAY(INET))

但当我提出疑问时,我得到了错误的答案:
user = User.query.get(84)
print user.permitted_ips
#['{', '1', '7', '2', '.', '2', '0', '.', '2', '5', '.', '2', ',', '1', '7', '2', '.', '2', '0', '.', '2', '5', '.', '3', '}']

而不是['172.20.25.2','172.20.25.3']。sqlalchemy的当前版本是0.9.10。我试了最新的一个,但结果是一样的。能修好吗?

最佳答案

我发现数组不是自动解析的,所以需要用psycopg2库创建一个generic type caster

# needed imports
from psycopg2 import STRING
from psycopg2.extensions import register_type, new_array_type

注册数组类型,只需一次。
# to see the oid of inet. As pointed out by @univerio the oid should never
# change, so you don't need to fetch it every time your app starts.
tp = db.engine.execute("select typarray from pg_type where typname = 'inet'")
print(tp.fetchone())
# (1041,)

# registering the array type
register_type(new_array_type((1041,), 'INET[]', STRING))

现在您可以获取数组并正确解析它。
# fetch data
ips = db.engine.execute("select permitted_ips from users where id = 1")
print(ips.fetchone()[0])
# ['172.20.25.2', '172.20.25.3'].

08-28 16:45