Question

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?

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top