postgresql - 如何在 flask-sqlalchemy 中使用 INET 的 ARRAY?

标签 postgresql flask sqlalchemy

我的 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。我尝试了最新的,但结果是一样的。有可能解决这个问题吗?

最佳答案

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

# 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'].

关于postgresql - 如何在 flask-sqlalchemy 中使用 INET 的 ARRAY?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37204982/

相关文章:

mysql - Heroku 为什么使用 Postgresql?

postgresql - PostgreSQL的官方Docker镜像如何以及在何处保留其数据库

javascript - 服务器找不到 JavaScript 文件

python - Neo4j Python bolt 驱动程序 : how to convert the result to Json?

sql - 如何在不过多往返数据库的情况下使用 SQL AUTOINCREMENT 主键?

python - 如何在 SQLAlchemy 中使用 postgres 数字范围

postgresql - 使用Spring Boot和PostgreSQL的Redis数据库

python - oauth2回调时如何恢复flask.session对象

python - 加入表本身以查找具有相同关系的用户

sql - 在 Web 应用程序中提供快速 `select count(*)` 功能