ipo_http.html


001| """IPO Implementation -- HTTP.
001| 
001| Classes:
001|     ipo_input_http_data (ipo_input)             ~HTTP Input subclass (data)
001|     ipo_input_http_text (ipo_input)             ~HTTP Input subclass (text)
001| 
001| """

002| ####################################################################################################
003| from urllib.request import urlopen
004| from socket import gethostbyaddr
005| from logger import logger
006| from goodies import typename, KWARG
007| from files import CR, LF
008| from ipo_defs import ipo_token, ipo_input, EOL_TAG, SPC_TAG
009| ####################################################################################################
010| Log = logger('HTTP')
011| 
012| 
013| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
014| class ipo_input_http (ipo_input):
015|     """HTTP Input base class (abstract)."""
016|     tag = 'Http'
017| 
018|     def __init__ (self, name, **kwargs):
019|         """New InputHttp instance."""
020|         super().__init__(name, **kwargs)
021|         self.url = KWARG('url', '', str, kwargs)
022|         self.data = []
023|         assert len(self.url), ValueError('No URL provided!')
024| 
025|     def start (self, datum):
026|         """Initialize this object."""
027|         super().start(datum)
028|         # Get http...
029|         try:
030|             # Request an HTTP document...
031|             Log.info(f'htget {self.url}')
032|             rqst = urlopen(self.url)
033| 
034|             # Capture status codes...
035|             self.requestCode = rqst.status
036|             self.requestText = rqst.reason
037|             self.requestStatus = f'{self.requestCode} {self.requestText}'
038| 
039|             # LINK might not be the same as URL...
040|             self.link = rqst.geturl()
041| 
042|             # Get the document response headers...
043|             self.headers = rqst.getheaders()
044| 
045|             # Read the document content...
046|             self.data = rqst.read()
047| 
048|         except Exception as e:
049|             self.requestCode = -1
050|             self.requestText = str(e)
051|             self.requestStatus = 'ERR: "%s"' % e
052|             self.link = ''
053|             self.headers = {}
054|             self.data = None
055| 
056|         else:
057|             Log.info(f'htget {self.requestStatus} ({len(self.data)} bytes)')
058| 
059|         Log.info()
060|         return datum
061| 
062| 
063| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
064| class ipo_input_http_data (ipo_input_http):
065|     """HTTP Input subclass (data)."""
066|     tag = 'Data'
067| 
068|     def __init__ (self, **kwargs):
069|         """New InputHttpData instance."""
070|         super().__init__('HttpDataIn', **kwargs)
071| 
072|     def __call__ (self):
073|         """Return next chunk of data."""
074|         if self.status < 0:
075|             return None
076| 
077|         if len(self.data) <= self.count:
078|             self.status = -1
079|             return None
080| 
081|         b = self.data[self.count]
082|         datum = [ipo_token(bytes([b]), self.count+1, 1, 'byte')]
083|         super().__call__(datum)
084|         return datum
085| 
086| 
087| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
088| class ipo_input_http_text (ipo_input_http):
089|     """HTTP Input subclass (text)."""
090|     tag = 'Text'
091| 
092|     def __init__ (self, **kwargs):
093|         """New InputHttpText instance."""
094|         super().__init__('HttpTextIn', **kwargs)
095|         self.cr = KWARG('cr', 1, int, kwargs)
096| 
097|     def __call__ (self):
098|         """Return next chunk of data."""
099|         if self.status < 0:
100|             return None
101| 
102|         if len(self.data) <= self.count:
103|             self.status = -1
104|             return None
105| 
106|         # Get next character...
107|         ch = chr(self.data[self.count])
108| 
109|         # Strip CR if requested...
110|         if self.cr and (ch == CR):
111|             datum = []
112|         else:
113|             datum = [ipo_token(ch, self.count+1, 1, 'char')]
114| 
115|         super().__call__(datum)
116|         return datum
117| 
118| 
119| ####################################################################################################
120| if __name__ == '__main__':
121|     print()
122|     ipos = []
123| 
124|     ipos.append(ipo_input_http_data(**{'url': r'http://localhost/local.html'}))
125|     ipos.append(ipo_input_http_text(**{'url': r'http://localhost/local.html'}))
126|     ipos.append(None)
127| 
128|     for ix,obj in enumerate(ipos):
129|         if obj is None:
130|             print()
131|             continue
132|         print(f'{ix:2d}: {obj!s}')
133|         obj.start(None)
134|     print()
135| 
136|     g = ipos[0]
137|     print(f'{len(g.data) = }')
138|     print()
139| ####################################################################################################
140| """eof"""
141|