문제

I have a table in SQLAlchemy with a column IPaddress, that is represented in decimal format. How can I change it to show a dotted format instead?

도움이 되었습니까?

해결책

Get the decimal value from DB and do the conversion in Python code. Install IPy module and do the following:

from IPy import IP
ip_dotted = str(IP(ip_dec))

If you were using Python 3.3, there's ipaddress in stdlib:

from ipaddress import ip_address
ip_dotted = str(ip_address(ip_dec))

If RDBMS in use is PostgreSQL, conversion can be done at DB level:

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

Finally, you can do calculations yourself, so there won't be any dependencies on specific libraries, Python versions or 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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top