htget.html


001| '''Get HTTP Resource.
001| 
001| Developer@Sonnack.com
001| April 2012
001| '''

002| ####################################################################################################
003| from urllib.request import urlopen
004| from socket import gethostbyaddr
005| from json import loads
006| from logger import logger
007| from goodies import typename
008| ####################################################################################################
009| Log = logger('htget')
010| 
011| URL0 = 'https://sonnack.com/'
012| URL1 = 'https://sonnack.com/contents.html'
013| URL2 = 'https://sonnack.com/logo.gif'
014| 
015| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
016| class htget (object):
017|     '''HTTP Get class.
017| 
017| Attributes:
017|     url                 URL of resource to get
017|     statusCode          numeric status code
017|     statusText          text status code
017|     status              numeric and text status
017|     link                requested URL
017|     headers             dictionary of response headers
017|     data                content of the response
017| 
017| Methods:
017|     save                save content to a (binary) file
017| 
017| '''

018|     def __init__ (self, url):
019|         '''Create a new htget instance. ***This makes an http request!***'''
020|         self.url = url
021|         try:
022|             Log.trace(f'htget: {self.url}')
023| 
024|             # Request an HTTP document...
025|             rqst = urlopen(self.url)
026| 
027|             # Success (if we get this far)...
028|             self.statusCode = rqst.status
029|             self.statusText = rqst.reason
030|             self.status = f'{self.statusCode} {self.statusText}'
031|             # LINK might not be the same as URL...
032|             self.link = rqst.geturl()
033|             # Get the document response headers...
034|             self.headers = rqst.getheaders()
035|             # Read the document content...
036|             self.data = rqst.read()
037| 
038|         except Exception as e:
039|             self.statusCode = -1
040|             self.statusText = str(e)
041|             self.status = f'ERR: "{e}"'
042|             self.link = ''
043|             self.headers = {}
044|             self.data = None
045| 
046|         else:
047|             Log.trace(f'htget: {self.status} ({len(self.data)} bytes)')
048| 
049|     def __len__ (self):
050|         '''Length of a request is the length of the content (if any).'''
051|         return len(self.data)
052| 
053|     def __str__ (self):
054|         '''Pretty print is URL and status.'''
055|         return f'{self.url}\n[{self.status}]'
056| 
057|     def __repr__ (self):
058|         '''Debug string.'''
059|         return f'<{typename(self)} @{id(self):012x}>'
060| 
061|     def save (self, filename):
062|         '''Save content (as bytes) to filename.'''
063|         Log.trace(f'htget: open {filename}')
064| 
065|         # Open a binary file...
066|         f = open(filename, mode='wb')
067|         try:
068|             # Write the data...
069|             f.write(self.data)
070|         except:
071|             raise
072|         else:
073|             Log.trace(f'htget: wrote {filename}')
074|         finally:
075|             # Be sure to close the file...
076|             f.close()
077| 
078| 
079| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
080| class json_get (htget):
081|     '''HTTP GET JSON class.'''
082| 
083|     def __init__ (self, url):
084|         '''New instance.'''
085|         super().__init__(url)
086|         self.jsondata = {}
087| 
088|         if self.statusCode == 200:
089|             self.jsondata = loads(self.data)
090| 
091|     def __len__ (self):
092|         '''Length is length of JSON content.'''
093|         return len(self.jsondata)
094| 
095|     def __iter__ (self):
096|         '''Iterate JSON content.'''
097|         return iter(self.jsondata)
098| 
099|     def __getitem__ (self, name):
100|         '''Return an item from jsondata (or None).'''
101|         if name in self.jsondata:
102|             return self.jsondata[name]
103|         return None
104| 
105| 
106| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
107| class ip_info (htget):
108|     URL = 'https://geolocation-db.com/json/%s'
109| 
110|     def __init__ (self, ip_addr):
111| 
112|         self.ip = ip_addr
113|         self.info = {}
114| 
115|         try:
116|             self.dns = gethostbyaddr(self.ip)
117|             self.host = self.dns[0]
118| 
119|         except:
120|             self.dns = ('unknown', [], [])
121|             self.host = 'unknown'
122| 
123|         # Get geolocation info...
124|         super().__init__(self.URL % self.ip)
125|         Log.debug(self.link)
126|         Log.debug(self.status)
127| 
128|         for name,value in self.headers:
129|             Log.debug(f'{name}: "{value}"')
130|         Log.debug()
131| 
132|         if self.statusCode == 200:
133|             # Convert JSON...
134|             self.info = loads(self.data.decode('utf8'))
135| 
136|         # Extract fields...
137|         self.latitude = float(self.info['latitude']) if 'latitude' in self.info else 0.0
138|         self.longitude = float(self.info['longitude']) if 'longitude' in self.info else 0.0
139|         self.country = self.info['country_name'] if 'country_name' in self.info else ''
140|         self.state = self.info['state'] if 'state' in self.info else ''
141|         self.city = self.info['city'] if 'city' in self.info else ''
142| 
143| 
144| 
145| 
146| 
147| ####################################################################################################
148| '''eof'''
149|