63 lines
1.6 KiB
Python
63 lines
1.6 KiB
Python
class TableFormatter:
|
|
def headings(self, headers):
|
|
raise NotImplementedError()
|
|
|
|
def row(self, rowdata):
|
|
raise NotImplementedError()
|
|
|
|
|
|
class TextTableFormatter:
|
|
def _printer(self, data):
|
|
print(*("{: >10}".format(value) for value in data))
|
|
|
|
def headings(self, headers):
|
|
self._printer(headers)
|
|
print(*("{:->10}".format("") for _ in headers))
|
|
|
|
def row(self, rowdata):
|
|
self._printer(rowdata)
|
|
|
|
|
|
class CSVTableFormatter:
|
|
def _printer(self, data):
|
|
print(",".join(str(value) for value in data))
|
|
|
|
def headings(self, headers):
|
|
return self._printer(headers)
|
|
|
|
def row(self, rowdata):
|
|
return self._printer(rowdata)
|
|
|
|
|
|
class HTMLTableFormatter:
|
|
def _cell(self, value, tag):
|
|
return f"<{tag}>{value}</{tag}>"
|
|
|
|
def _printer(self, data, tag):
|
|
line = f"<tr>{' '.join(self._cell(str(value), tag) for value in data)}</tr>"
|
|
print(line)
|
|
|
|
def headings(self, headers):
|
|
return self._printer(headers, "th")
|
|
|
|
def row(self, rowdata):
|
|
return self._printer(rowdata, "td")
|
|
|
|
|
|
def create_formatter(name):
|
|
formatters = {
|
|
"text": TextTableFormatter,
|
|
"csv": CSVTableFormatter,
|
|
"html": HTMLTableFormatter,
|
|
}
|
|
formatter = formatters.get(name, None)
|
|
if not name:
|
|
raise ValueError(f'formatter named "{name}" not implemented')
|
|
return formatter()
|
|
|
|
|
|
def print_table(records, fields, formatter):
|
|
formatter.headings(fields)
|
|
for record in records:
|
|
formatter.row([getattr(record, fieldname) for fieldname in fields])
|