webpage.html
001| '''HTML and CGI Webpage template classes.
001|
001| Classes:
001| WebPage ~HTML webpage
001| CalandarPage ~HTML TABLE Calender
001|
001| TabPageHtml (WebPage) ~PageWriter for TAB files
001| TabPageListHtml (WebPage) ~PageWriter for TAB list files
001| BinDumpPage (WebPage) ~Hex Dump page
001|
001| CgiPage (WebPage) ~CGI webpage
001| AjaxResponse ~CGI AJAX response
001| CgiImage ~CGI image
001|
001| Functions:
001| htmlize (line, highlight)
001| make_web_calendar (year, kwargs)
001| Cgi_Huh_Page (ostrm, content)
001| Cgi_Error_Page (ostrm, etext, stacklist)
001|
001| Data:
001| EOL - newline
001| TAB - tab
001| Today - current date
001| Now - current datetime
001| HttpPageHeader - HTTP page template
001| HttpAjaxHeader - HTTP page template
001| HttpImageHeader - HTTP image header
001| HtmlPageWrapper - HTML page basic frame
001| HtmlPageHead - HTML page standard header
001| HtmlPageFoot - HTML page standard footer
001| HtmlErrorPage - HTML error page template
001|
001| Includes WebPage subclasses and functions for:
001| Year Calendar Page - make_web_calendar(yr,**) function
001| - CalendarPage(yr,**) class
001| Binary Dump Page - BinDumpPage(nm,dat,**) class
001| TAB/CSV File Page - TabPageHtml(nm,fo,**) class
001| - TabPageListHtml(nm,fo,nc) class
001|
001| Basic Example:
001| page = WebPage('Test', **kwargs)
001| page.add('<p>Hello, World!</p>')
001| page.add('<p>This is a test.</p>')
001| page.write(stdout)
001|
001| '''
002|
003| from sys import stdout
004| from os import path
005| from io import BytesIO
006| from random import randint
007| from datetime import date, datetime, timedelta
008| from dates import UTC, CST
009| from goodies import KWARG
010|
011| EOL = '\n'
012| TAB = '\t'
013| Today = date.today()
014| Now = datetime.now()
015|
016|
017|
018| def htmlize (line, highlight=False):
019| '''Clean up text for HTML.'''
020| if '&' in line:
021| line = line.replace('&','&')
022| if '<' in line:
023| line = line.replace('<','<')
024| if '>' in line:
025| line = line.replace('>','>')
026| return line
027|
028|
029| HttpPageHeader = '''\
029| Content-Type: text/html; charset=UTF-8
029| Last-Modified: {0}
029| Pragma: no-cache
029| Errors-To: service@localhost
029| X-My-BFF-List: Jeannie; Shantih; Nancy; Scott; Jamie;
029| X-Best-Sport: Baseball
029| X-A-Great-Dog: Bentley
029| X-My-Dog-RIP: Samantha
029| X-Clacks-Overhead: Sir Terry Pratchett
029| X-Clacks-Overhead: Carl Sagan
029| X-Ultimate-Answer: 42
029| X-My-Signature: lux et veritas; sapere aude
029| '''
030|
031| HttpAjaxHeader = '''\
031| Content-Type: text/xml; charset=UTF-8
031| Last-Modified: {0}
031| Pragma: no-cache
031| Errors-To: service@localhost
031| X-My-BFF-List: Jeannie; Shantih; Nancy; Scott; Jamie;
031| X-Best-Sport: Baseball
031| X-A-Great-Dog: Bentley
031| X-My-Dog-RIP: Samantha
031| X-Clacks-Overhead: Sir Terry Pratchett
031| X-Clacks-Overhead: Carl Sagan
031| X-Ultimate-Answer: 42
031| X-My-Signature: lux et veritas; sapere aude
031| '''
032|
033| HttpImageHeader = '''\
033| Content-Type: image/png
033| Content-Length: {0}
033| Last-Modified: {1}
033| Pragma: no-cache
033| Errors-To: service@localhost
033| X-My-BFF-List: Jeannie; Shantih; Nancy; Scott; Jamie;
033| X-Best-Sport: Basebal
033| X-A-Great-Dog: Bentley
033| X-My-Dog-RIP: Samantha
033| X-Clacks-Overhead: Sir Terry Pratchett
033| X-Clacks-Overhead: Carl Sagan
033| X-Ultimate-Answer: 42
033| X-My-Signature: lux et veritas; sapere aude
033| '''
034|
035|
036| HtmlErrorPage = '''\
036| Content-Type: text/html; charset=UTF-8
036| Last-Modified: {0}
036| Pragma: no-cache
036|
036| <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
036| <html>
036| <head>
036| <title>Error</title>
036| <link rel="stylesheet" type="text/css" href="/basic.css">
036| </head>
036|
036| <body>
036| <div id="PageHead">
036| <h1>Sonnack.com</h1>
036| <h2>Web Applications</h2>
036| </div>
036|
036| <div id="PageBody">
036| <h3>Error!</h3>
036| <hr>
036| <div id="PageContent">{1}</div>
036| <hr>
036| </div>
036|
036| <div id="PageFoot">
036| <span class="Lt">© 2018<br><em>All rights reserved.</em></span>
036| <span class="Rt">Private page!<br>You probably have no business here!</span>
036| <br style="clear:both;">
036| </div>
036| </body>
036| </html>
036| '''
037|
038| HtmlPageWrapper = '''\
038| <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
038| <html>
038| <head>
038| <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
038| <meta http-equiv="Last-Modified" content="{0}">
038| <title>{1}</title>
038| <link rel="stylesheet" type="text/css" href="/basic.css">
038| </head>
038| <body>
038| <div id="PageHead">
038| <h1>Sonnack.com</h1>
038| <h2>Web Applications</h2>
038| </div>
038| <div id="PageBody">{2}</div>
038| <div id="PageFoot">
038| <span class="Lt">© 2019 Chris Sonnack<br><em>All rights reserved.</em></span>
038| <span class="Rt"><em>feedback:</em><br><a target="_blank" href="mailto:webspinner@sonnack.com">Webspinner@Sonnack.com</a></span>
038| <br style="clear:both;">
038| </div>
038| </body>
038| </html>
038| '''
039|
040|
041| HtmlPageHead = '''\
041| <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
041| <html>
041| <head>
041| <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
041| <meta http-equiv="Last-Modified" content="{0}">
041| <meta http-equiv="Generator" content="python:lib:webpage">
041| {1}<title>{2}</title>
041| {3}{4}{5}</head>
041|
041| <body{6}>
041| <div id="PageHead">
041| <h1>{7}</h1>{8}
041| </div>
041|
041| <div id="PageBody">
041| '''
042|
043| HtmlPageFoot = '''\
043| </div><!-- PageBody -->
043|
043| <div id="PageFoot">
043| <span class="Lt">© 2018 Chris Sonnack<br><em>All rights reserved.</em></span>
043| <span class="Rt"><em>feedback:</em><br><a target="_blank" href="mailto:webspinner@sonnack.com">Webspinner@Sonnack.com</a></span>
043| Last Modified: {0}
043| <br style="clear:both;">
043| </div>
043|
043| </body>
043| </html>
043| '''
044|
045|
046| class WebPage:
047| '''Web Page template class.
047|
047| page = WebPage(title, **kwargs)
047|
047| kwargs:
047| h1 - H1 text
047| h2 - H2 text
047| h3 - H3 text
047| css - list of CSS URLs for <LINK> headers
047| js - list of JavaScript URLs for <SCRIPT> headers
047| csstxt - text for a <STYLE> header
047| jstxt - text for a <SCRIPT> header
047| meta - list of <META> (name,value) tuples
047| onload - text for the <BODY onload> attribute
047|
047| Methods:
047| add (text) - add text to the body content
047| content () - generate and return the page HTML
047| write (fp) - generate and write page HTML to fp
047| save (fn) - generate and write page HTML to file
047|
047| '''
048| def __init__ (self, title, **kwargs):
049| self.dt = datetime.now(UTC())
050| self.lt = self.dt.astimezone(CST())
051| self.ct = self.dt.ctime()
052| self.title = title
053| self.h1 = KWARG('h1', 'Sonnack.com', str, kwargs)
054| self.h2 = KWARG('h2', 'Web Application', str, kwargs)
055| self.h3 = KWARG('h3', title, str, kwargs)
056| self.js = KWARG('js', [], list, kwargs)
057| self.css = KWARG('css', ['/basic.css'], list, kwargs)
058| self.meta = KWARG('meta', [], list, kwargs)
059| self.onload = KWARG('onload', '', str, kwargs)
060| self.csstxt = KWARG('csstxt', '', str, kwargs)
061| self.jstxt = KWARG('jstxt', '', str, kwargs)
062| self.body = []
063| if (self.h3 is not None) and (0 < len(self.h3)):
064| self.body.append(f'<h3>{self.h3}</h3>')
065|
066| def add (self, txt=''):
067| self.body.append(txt)
068|
069| def content (self):
070| self._make_page()
071| self.body.append(EOL)
072| pagetext = EOL.join(self.body)
073| return self.head + pagetext + self.foot
074|
075| def write (self, fp):
076| fp.write(self.content())
077| fp.flush()
078|
079| def save (self, filename, encoding='utf-8', log=None):
080| fp = open(filename, mode='w', encoding=encoding)
081| try:
082| self.write(fp)
083| except Exception as e:
084| if log:log.error(f'ERROR: {e}')
085| raise
086| else:
087| if log:log.info(f'wrote: {filename}')
088| finally:
089| fp.close()
090|
091| def _make_page (self):
092| args = []
093| args.append(self.ct)
094| args.append(self._meta())
095| args.append(self.title)
096| args.append(self._css())
097| args.append(self._js())
098| args.append(self._xheader())
099| args.append(self._onload())
100| args.append(self.h1)
101| args.append('' if len(self.h2) == 0 else f'\n<h2>{self.h2}</h2>')
102| self.head = HtmlPageHead.format(*args)
103| self.foot = HtmlPageFoot.format(self.lt.strftime('%b %d, %Y %I:%M %p'))
104|
105| def _css (self):
106| a = []
107| for x in self.css:
108| a.append(f'<link rel="stylesheet" type="text/css" href="{x}">{EOL}')
109| return ''.join(a)
110|
111| def _js (self):
112| a = []
113| for x in self.js:
114| a.append(f'<script type="text/javascript" src="{x}"></script>{EOL}')
115| return ''.join(a)
116|
117| def _meta (self):
118| a = []
119| for x,y in self.meta:
120| a.append(f'<meta http-equiv="{x}" content="{y}">{EOL}')
121| return ''.join(a)
122|
123| def _xheader (self):
124| a = []
125| if self.csstxt:
126| a.append(f'<style type="text/css">{EOL}')
127| a.append(self.csstxt)
128| a.append(EOL)
129| a.append(f'</style>{EOL}')
130| if self.jstxt:
131| a.append(f'<script type="text/javascript"><!--{EOL}')
132| a.append(self.jstxt)
133| a.append(EOL)
134| a.append(f'//-->{EOL}')
135| a.append(f'</script>{EOL}')
136| return ''.join(a)
137|
138| def _onload (self):
139| return f' onload="{self.onload}"' if self.onload else ''
140|
141| def __str__ (self):
142| return self.title
143|
144|
145|
146| class CalendarPage:
147| '''\
147| HTML TABLE Calender class.
147|
147| Emits an HTML <TABLE> version of a calender.
147|
147| Input Properties:
147| year - calendar year (int, required)
147| caption - calendar caption (default: the year)
147| cb_year - callback function to print calendar Year
147| cb_month - callback function to print calendar Month
147| cb_day - callback function to print calendar Date
147| cb_prev - callback function to print "previous year" link
147| cb_next - callback function to print "next year" link
147|
147| Instance Properties (treat as read-only):
147| .dotw - "Sun", "Mon",..
147| .days - "Sunday", "Monday",..
147| .content - list of generated HTML lines
147| .dt0 - calendar year (Jan 1)
147| .dt1 - date "cursor" (changes)
147| .caption - calendar caption
147| .cb_day - day writer callback
147| .cb_month - month writer callback
147| .cb_year - year writer callback
147| .cb_prev - previous year writer callback
147| .cb_next - next year writer callback
147| .curr_dt()
147| .curr_weekday()
147|
147| NOTE: callback functions receive the CalendarPage object as the single parameter.
147| '''
148| dotw = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
149| days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
150|
151| def __init__ (self, year, **kwargs):
152| self.dt0 = date(year, 1, 1)
153| self.dt1 = date(year, 1, 1)
154| self.fmt = '%Y'
155| self.one_day = timedelta(1)
156| self.cal_head = '<th colspan="3">%d days</th>' % len(self)
157| self.cal_foot = '<th colspan="3">© cjsonnack</th>'
158| self.month_head = ''.join(['<th>%s</th>' % CalendarPage.dotw[n] for n in range(7)])
159| self.month_foot = self.month_head
160| self.caption = kwargs['caption'] if 'caption' in kwargs else str(self.dt0.year)
161| self.cb_day = kwargs['cb_day'] if 'cb_day' in kwargs else lambda x: x.dt1.strftime('%d')
162| self.cb_month = kwargs['cb_month'] if 'cb_month' in kwargs else lambda x: x.dt1.strftime('%b')
163| self.cb_year = kwargs['cb_year'] if 'cb_year' in kwargs else lambda x: x.dt1.strftime('%Y')
164| self.cb_prev = kwargs['cb_prev'] if 'cb_prev' in kwargs else None
165| self.cb_next = kwargs['cb_next'] if 'cb_next' in kwargs else None
166| self.content = []
167| self._build()
168|
169| def __str__ (self):
170| return self.dt0.strftime(self.fmt)
171|
172| def __call__ (self): return EOL.join(self.content)
173|
174| def __bool__ (self): return True
175|
176| def __len__ (self):
177| '''Returns number of days in the year.'''
178| next_year = self.dt0.replace(year=self.dt0.year+1)
179| td = next_year - self.dt0
180| return td.days
181|
182| def __getitem__ (self, ix): return self.dt0+timedelta(ix)
183| def __setitem__ (self, ix, value): raise NotImplemented("Dates are fixed.")
184| def __delitem__ (self, ix): raise NotImplemented("Dates are fixed.")
185|
186| def curr_dt (self):
187| return self.dt1
188| def curr_weekday (self):
189| '''Returns {Su=0,M=1,Tu=2,W=3,Th=4,F=5,Sa=6} on cursor date.'''
190| return ((self.dt1.weekday() + 1) % 7)
191|
192| def _build (self):
193| cap = self._callback_year(self.caption)
194| cb_prev = self.cb_prev
195| cb_next = self.cb_next
196| ht_prev = cb_prev(self.dt0.year - 1) if cb_prev else ''
197| ht_next = cb_next(self.dt0.year + 1) if cb_next else ''
198| self.content.append('')
199| self.content.append('<table class="CalendarBody">')
200| self.content.append('<caption>%s%s%s</caption>' % (ht_prev, cap, ht_next))
201| self.content.append('<thead><tr>%s</tr></thead>' % self.cal_head)
202| self.content.append('<tfoot><tr>%s</tr></tfoot>' % self.cal_foot)
203| self._write_body()
204| self.content.append('</table>')
205| self.content.append('')
206|
207| def _write_body (self):
208| self.content.append('<tbody>')
209|
210| for row in [0, 3, 6, 9]:
211| self.content.append('<tr>')
212| for col in [1, 2, 3]:
213| self.content.append('<td>')
214| self._write_month(row+col)
215| self.content.append('</td>')
216| self.content.append('</tr>')
217| self.content.append('<tr><th colspan="3"> </th></tr>')
218| self.content.append('</tbody>')
219|
220| def _write_month (self, m):
221| self.dt1 = date(self.dt0.year, m, 1)
222| cap = self._callback_month(self.dt1.strftime('%B'))
223| self.content.append('<table class="CalendarMonth">')
224| self.content.append('<caption>%s</caption>' % cap)
225| self.content.append('<thead><tr>%s</tr></thead>' % self.month_head)
226| self.content.append('<tfoot><tr>%s</tr></tfoot>' % self.month_foot)
227| self._month_body(m)
228| self.content.append('</table>')
229| self.content.append('')
230|
231| def _month_body (self, m):
232| start_day = self.curr_weekday()
233| start_flag = False
234| self.content.append('<tbody>')
235|
236| for _ in range(6):
237| self.content.append('<tr>')
238|
239| for d in range(7):
240| if start_flag:
241| if m == self.dt1.month:
242| self._month_day()
243| else:
244| self.content.append('<td> </td>')
245| else:
246| if d < start_day:
247| self.content.append('<td> </td>')
248| else:
249| start_flag = True
250| self._month_day()
251| self.content.append('</tr>')
252| self.content.append('</tbody>')
253|
254| def _month_day (self):
255| cls = CalendarPage.days[self.curr_weekday()]
256| txt = self._callback_day(str(self.dt1.day))
257| self.content.append('<td class="%s">%s</td>' % (cls, txt))
258|
259| self.dt1 = self.dt1 + self.one_day
260|
261| def _callback_year (self, s):
262| if self.cb_year:
263| try:
264| return self.cb_year(self)
265| except Exception as e:
266| return e
267| return s
268|
269| def _callback_month (self, s):
270| if self.cb_month:
271| try:
272| return self.cb_month(self)
273| except Exception as e:
274| return e
275| return s
276|
277| def _callback_day (self, s):
278| if self.cb_day:
279| try:
280| return self.cb_day(self)
281| except Exception as e:
282| return e
283| return s
284|
285| def __repr__ (self):
286| s = '{CalendarPage:{date:%s, format:%s}}'
287| t = (self.dt0, self.fmt)
288| return s % t
289|
290|
291| def make_web_calendar (year, **kwargs):
292| '''\
292| Make Web Calendar.
292|
292| input properties:
292| year - calendar year
292| fname - filename (requires embedded %s or %d)
292| fpath - filepath
292| h1, h2 - HTML H1 & H2 banner
292| css, js - HTML CSS & Javascript links
292|
292| NOTE: kwargs are also passed to CalendarPage object.
292|
292| '''
293|
294| fname = kwargs['fname'] if 'fname' in kwargs else '%04d.html'
295| fpath = kwargs['fpath'] if 'fpath' in kwargs else None
296| fn = path.join(fpath, fname % year) if fpath else (fname % year)
297| fp = open(fn, mode='w', encoding='utf-8')
298| try:
299|
300| cal_props = dict(kwargs)
301| cal = CalendarPage(year, **cal_props)
302|
303|
304| if 'h1' not in kwargs: kwargs['h1'] = 'Sonnack.com'
305| if 'h2' not in kwargs: kwargs['h2'] = 'Web Calendar'
306| if 'css' not in kwargs: kwargs['css'] = ['/basic.css','/pub/cal/calendar.css']
307| if 'js' not in kwargs: kwargs['js'] = []
308|
309| page = WebPage('Calendar', **kwargs)
310| page.body = cal.content
311| page.write(fp)
312| except:
313| raise
314| finally:
315| fp.close()
316| return 'Done'
317|
318|
319|
320| class TabPageHtml (WebPage):
321| '''PageWriter object for writing TAB files.'''
322| PageProps = {
323| 'h1': 'Sonnack.com',
324| 'h2': 'Python WebApps',
325| 'h3': 'TAB–to–HTML',
326| 'css': ['/basic.css', 'tab2html.css'],
327| }
328| def __init__ (self, name, fobj, **kwargs):
329| super().__init__('Tab2HTML', **TabPageHtml.PageProps)
330| self.name = name
331| self.fobj = fobj
332| self.hdrs = fobj.hdrs
333| self.data = fobj.data
334| self.write_head = KWARG('/head', True, bool, kwargs)
335| self.write_foot = KWARG('/foot', True, bool, kwargs)
336| self._build()
337|
338| def _build (self):
339| self.add('<h4>%s</h4>' % self.name)
340| self.add()
341| self.add('<table class="TabData">')
342|
343| if self.write_head:
344| self.add('<thead>')
345| self.add('<tr>')
346| for cx,hdr in enumerate(self.hdrs):
347| self.add('<th class="C%d">%s</th>' % (1+cx,hdr))
348| self.add('</tr>')
349| self.add('</thead>')
350|
351| if self.write_foot:
352| self.add('<tfoot>')
353| self.add('<tr>')
354| for cx,hdr in enumerate(self.hdrs):
355| self.add('<th class="C%d">%s</th>' % (1+cx,hdr))
356| self.add('</tr>')
357| self.add('</tfoot>')
358|
359| self.add('<tbody>')
360| for rx,row in enumerate(self.data):
361| self.add('<tr class="R%d">' % (1+rx))
362| for cx,col in enumerate(row):
363| self.add('<td class="C%d">%s</td>' % (1+cx,col))
364| self.add('</tr>')
365| self.add('</tbody>')
366| self.add('</table>')
367|
368|
369| class TabPageListHtml (WebPage):
370| '''PageWriter object for writing TAB list files.'''
371| PageProps = {
372| 'h1': 'Sonnack.com',
373| 'h2': 'Python WebApps',
374| 'h3': 'TAB–to–HTML',
375| 'css': ['/basic.css', 'tab2html.css'],
376| }
377| def __init__ (self, name, fobj, ncol):
378| super().__init__('Tab2HTML', **TabPageListHtml.PageProps)
379| self.name = name
380| self.fobj = fobj
381| self.hdrs = fobj.hdrs
382| self.data = fobj.data
383| self.ncol = ncol
384| self._build()
385|
386| def _build (self):
387| self.add('<h4>%s</h4>' % self.name)
388| self.add()
389| self.add('<table class="TabData">')
390| self.add('<tbody>')
391|
392| for cx,hdr in enumerate(self.hdrs):
393| self.add('<tr class="R%d">' % (2+cx))
394| self.add('<th class="C0">%s</th>' % hdr)
395|
396| for rx in range(self.ncol):
397| row = self.data[rx]
398| self.add('<td class="C%d">%s</td>' % (2+rx,row[cx]))
399| self.add('</tr>')
400| self.add('</tbody>')
401| self.add('</table>')
402| self.add()
403|
404|
405| Bin2HtmlCss = '''\
405| #PageBody h3 {
405| font-size: 11pt;
405| margin-bottom: 2pt;
405| }
405| #PageBody h4 {
405| font-size: 12pt;
405| font-weight: normal;
405| margin-bottom: 18pt;
405| }
405| #PageBody table {
405| background-color: #3f3f3f;
405| text-height: 1.0;
405| border-spacing: 3px 0;
405| padding: 0 2px;
405| border: 2px solid black;
405| margin: 18pt auto 18pt 24pt;
405| }
405| #PageBody table thead th {
405| background-color: #000000;
405| color: #ffffff;
405| font-family: serif;
405| font-size: 13pt;
405| font-weight: bold;
405| font-style: normal;
405| text-align: center;
405| vertical-align: bottom;
405| padding: 3px auto 5px auto;
405| }
405| #PageBody table tbody tr {
405| background-color: #7f7f7f;
405| }
405| #PageBody table tbody td {
405| font-family: monospace;
405| font-size: 10pt;
405| font-weight: bold;
405| font-style: normal;
405| border-bottom: 1px solid black;
405| }
405| #PageBody table tbody td.Addrs {
405| white-space: nowrap;
405| background-color: #ffffbf;
405| text-align: right;
405| }
405| #PageBody table tbody td.Data {
405| white-space: nowrap;
405| background-color: #f0fff0;
405| }
405| #PageBody table tbody td.Chars {
405| white-space: nowrap;
405| background-color: #f0f0ff;
405| }
405| '''
406|
407| class BinDumpPage (WebPage):
408| PageProps = {
409| 'h2': 'Python WebApps',
410| 'csstxt': Bin2HtmlCss
411| }
412| def __init__ (self, name, bdata, **kwargs):
413| super().__init__('Bin2HTML', **BinDumpPage.PageProps)
414| self.name = name
415| self.data = bdata
416| self.nmode = KWARG('nbrs', 'x', str, kwargs)
417| self.dmode = KWARG('data', 'x', str, kwargs)
418| self.nwide = KWARG('nw', 4, int, kwargs)
419| self.dwide = KWARG('dw', 2, int, kwargs)
420| self.cols = KWARG('cols', 16, int, kwargs)
421| self.size = KWARG('size', 1, int, kwargs)
422| self.endian = KWARG('bd', 'LE', str, kwargs).upper()
423| self.addr_fmt = '%%0%d%c' % (self.nwide, self.nmode)
424| self.data_fmt = '%%0%d%c' % (self.dwide, self.dmode)
425| self.FormatAddr = lambda n:(self.addr_fmt % n)
426| self.FormatData = lambda n:(self.data_fmt % n)
427| self._build()
428| assert self.size in [1,2,4], ValueError('Width must be: 1, 2, or 4! [%s]' % self.size)
429| assert self.endian in ['LE','BE'], ValueError('Endian must be "LE" or "BE"! ["%s"]' % self.endian)
430| assert (len(self.data) % self.size) == 0, ValueError('Sequence length must be a multiple of Width! [%d<>%d]' % (len(self.data),self.size))
431|
432| def _build (self):
433| def SafeChar (c):
434| if c <= 32: return '.'
435| if c in [127, 129, 141, 143, 144, 157, 160, 173]: return '.'
436| if 127 < c: return ('&#%d;' % c)
437| ch = chr(c)
438| if ch == '&': return '&'
439| if ch == '<': return '<'
440| if ch == '>': return '>'
441| if ch == '"': return '"'
442| return ch
443|
444| self.add('<h4>%s</h4>' % self.name)
445| self.add()
446| self.add('<table>')
447| self.add('<thead>')
448| self.add('<tr><th>Addr</th><th>Data</th><th>Chars</th></tr>')
449| self.add('</thead>')
450| self.add('<tbody>')
451| for bx in range(0, len(self.data), self.cols):
452|
453| buf = self.data[bx:bx+self.cols]
454| dat = self._make_row(buf)
455|
456|
457| self.add('<tr>')
458| self.add('<td class="Addrs">%s</td>' % self.FormatAddr(bx))
459|
460|
461| bt = [self.FormatData(b) for b in dat]
462| self.add('<td class="Data">%s</td>' % (' '.join(bt)))
463|
464|
465| ct = [SafeChar(c) for c in buf]
466| self.add('<td class="Chars">%s</td>' % ''.join(ct))
467| self.add('</tr>')
468| self.add('</tbody>')
469| self.add('</table>')
470| self.add(EOL)
471|
472| def _make_row (self, seq):
473| '''Given a sequence of bytes, return BYTES, WORDS or DWORDS.'''
474| bixs = list(reversed(range(self.size)) if self.endian=='BE' else range(self.size))
475| dix = 0
476| out = []
477| while (dix+self.size) <= len(seq):
478| acc = 0
479| for ix,bix in enumerate(bixs):
480| val = seq[bix+dix]
481| acc += (val << (8 * ix))
482| out.append(acc)
483| dix += self.size
484|
485| return out
486|
487|
488|
489| class CgiPage (WebPage):
490| '''CGI Web Page class. (Extends WebPage.)
490|
490| Extends the idea of a webpage to include CGI, mainly in providing
490| an HTTP header, but also in providing error-handling during requests.
490|
490| Methods:
490| obj(ostrm,cb) - Call the instance to write the page to <ostrm>.
490| The (optional) <cb> function generates user page content.
490| '''
491|
492| def _make_page (self):
493| super(CgiPage,self)._make_page()
494| self.http = HttpPageHeader.format(self.ct)
495|
496| def content (self):
497| self._make_page()
498| self.body.append(EOL)
499| return self.http + EOL + self.head + EOL.join(self.body) + self.foot
500|
501| def __call__ (self, fp, cb_function=None):
502| try:
503| self._make_page()
504| self.body.append(EOL)
505|
506|
507| fp.write(self.http)
508| fp.write(EOL)
509|
510|
511| fp.write(self.head)
512| fp.flush()
513|
514|
515| if cb_function:
516| cb_function(self, fp)
517| else:
518| fp.write(EOL.join(self.body))
519| fp.flush()
520|
521|
522| fp.write(self.foot)
523| fp.flush()
524|
525| except Exception as e:
526| fp.write(HtmlErrorPage.format(self.dt.ctime(), e))
527| fp.flush()
528|
529|
530|
531| class AjaxResponse:
532| '''AJAX Response class.
532|
532| Methods:
532| obj(ostrm) - Call the instance to write the content to <ostrm>.
532|
532| '''
533| def __init__ (self, content, errcode=200, errmesg='Ok'):
534| self.errcode = errcode
535| self.errmesg = errmesg
536| self.content = content
537|
538| def __call__ (self, fp):
539|
540| ts = datetime.now(UTC())
541| fp.write(HttpAjaxHeader.format(ts.ctime()))
542| fp.write(EOL)
543| fp.write('<?xml version="1.0" encoding="UTF-8" ?>\n')
544| fp.write('<ajax version="1.0" provider="com.cjs.www.ajax">\n')
545| fp.write('<ajaxStatus>\n')
546| fp.write('<ajaxCode>%d</ajaxCode>\n' % self.errcode)
547| fp.write('<ajaxMessage>%s</ajaxMessage>\n' % self.errmesg)
548| fp.write('</ajaxStatus>\n')
549| fp.write('<ajaxContent>\n')
550| fp.write(self.content)
551| fp.write('</ajaxContent>\n')
552| fp.write('</ajax>\n')
553| fp.flush()
554|
555|
556|
557| class CgiImage (object):
558| '''CGI Image class.
558|
558| Methods:
558| obj(ostrm) - Call the instance to write the image to <ostrm>.
558|
558| '''
559| def __init__ (self, img):
560| self.img = img
561|
562| def __call__ (self, fp):
563|
564| output = BytesIO()
565| self.img.save(output, 'PNG')
566| content = output.getvalue()
567| output.close()
568|
569| ts = datetime.now(UTC())
570| fp.write(HttpImageHeader.format(len(content), ts.ctime()))
571| fp.write(EOL)
572| fp.flush()
573| fp.buffer.write(content)
574| fp.flush()
575|
576| def __str__ (self):
577| return str(self.img)
578|
579|
580|
581| PageHuh = '''\
581| <h3>Say What?</h3>
581| <p>"%s"</p>
581| <p style="font-style:italic;">I didn't catch that…</p>
581| '''
582|
583| def Cgi_Huh_Page (fp, content):
584| ts = datetime.now(UTC()).ctime()
585| page = PageHuh % content
586|
587| fp.write(HttpPageHeader.format(ts))
588| fp.write(EOL)
589| fp.write(HtmlPageWrapper.format(ts, 'Huh?', page))
590|
591|
592|
593| PageError = '''\
593| <h3>ERROR!</h3>
593| <div>Message:</div>
593| <pre class="ErrorText">%s</pre>
593| <hr>
593| <div>Stack:</div>
593| <pre class="StackText">%s</pre>
593| <hr>
593| '''
594|
595| def Cgi_Error_Page (fp, etext, stack):
596| ts = datetime.now(UTC()).ctime()
597| page = PageError % (etext, EOL.join(stack))
598|
599| fp.write(HttpPageHeader.format(ts))
600| fp.write(EOL)
601| fp.write(HtmlPageWrapper.format(ts, 'ERROR!', page))
602|
603|
604|
605|
606| '''eof'''
607|