Last active
June 10, 2021 18:31
-
-
Save landonstewart/24c2525eb9cdc7e24e97c4e939f7edcb to your computer and use it in GitHub Desktop.
Overriding the save() method for a Django model to dynamically obtain the hostname and IP addresses for a URL if none were given
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from socket import getaddrinfo | |
from socket import IPPROTO_TCP # pylint: disable=no-name-in-module | |
def save(self, *args, **kwargs): | |
"""Override save.""" | |
if self.url: | |
if not self.hostname: | |
self.hostname = urlparse(self.url).hostname | |
if self.hostname: | |
if not self.ip_addrs: | |
# Use socket to get all the IP addresses using a fictional connection to tcp/443 | |
# No connection is actually made | |
_ = getaddrinfo(self.hostname, 443, proto=IPPROTO_TCP) | |
ip_addrs = [x[4][0] for x in _] | |
self.ip_addrs = ip_addrs | |
super().save(*args, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment