【发布时间】:2013-08-16 10:11:43
【问题描述】:
我在 SQLAlchemy 中有一个表,其中有一列 IP 地址,以十进制格式表示。 如何将其更改为显示点格式?
【问题讨论】:
标签: sqlalchemy python-3.2
我在 SQLAlchemy 中有一个表,其中有一列 IP 地址,以十进制格式表示。 如何将其更改为显示点格式?
【问题讨论】:
标签: sqlalchemy python-3.2
从 DB 中获取十进制值并在 Python 代码中进行转换。安装IPy 模块并执行以下操作:
from IPy import IP
ip_dotted = str(IP(ip_dec))
如果您使用的是 Python 3.3,则 stdlib 中有 ipaddress:
from ipaddress import ip_address
ip_dotted = str(ip_address(ip_dec))
如果使用的 RDBMS 是 PostgreSQL,则可以在 DB 级别进行转换:
from sqlalchemy.sql import cast, func
from sqlalchemy.dialects.postgresql import INET
session.query(func.host(cast('0.0.0.0', INET) + SomeTable.ip_dec)).scalar()
最后,您可以自己进行计算,因此不会对特定库、Python 版本或 RDBMS 产生任何依赖:
segments = []
# From 3 to 0.
for n in range(3, -1, -1):
p = 256 ** n
segments.append(str(ip_dec // p))
ip_dec %= p
ip_dotted = '.'.join(segments)
【讨论】: