Print the index page with dynamically calculated column widths.
David Blume

David Blume commited on 2016-09-11 11:18:35
Showing 1 changed files, with 20 additions and 6 deletions.

... ...
@@ -135,19 +135,33 @@ if __name__ == '__main__':
135 135
             # just the home page, then
136 136
             print "Content-type: text/plain; charset=UTF-8\n"
137 137
             wrote_response = True
138
-            headers = ['key', 'value', 'created', 'updated', 'origin', 'notes']
139
-            print "\t".join([i.ljust(12) for i in headers])
140
-            print "\t".join([('-' * len(i)).ljust(12) for i in headers])
138
+
139
+            rows = [('key', 'value', 'created', 'updated', 'origin', 'notes'),]
141 140
             for key in sorted(store, key=lambda k: store[k]['time'], reverse=True):
142
-                device = map_key_to_prefix(key)
143 141
                 d = store[key]
144 142
                 td = texttime.stringify(datetime.timedelta(seconds=time.time()-d['time']))
145 143
                 created = time.strftime('%Y-%m-%d', time.localtime(d['created']))
146 144
                 origin = map_ip_to_location(d['origin'])
147
-                print '\t'.join((key.ljust(12), d['value'].ljust(13), created, str(d['time']), origin, "%supdated %s ago" % (device, td)))
145
+                rows.append((key, d['value'], created, str(d['time']), origin,
146
+                            "%supdated %s ago" % (map_key_to_prefix(key), td)))
147
+
148
+            cols = zip(*rows)
149
+
150
+            # Compute column widths by taking maximum length of values per column
151
+            col_widths = [max(len(value) for value in col) for col in cols]
152
+
153
+            # Create a suitable format string for nice table output
154
+            fmt = "\t".join(["{%d:<%d}" % (i, v) for i, v in enumerate(col_widths)])
155
+
156
+            # Print each row using the computed format
157
+            print fmt.format(*rows.pop(0))
158
+            print "\t".join([('-' * i) for i in col_widths])  # column header separator
159
+            for row in rows:
160
+                print fmt.format(*row)
161
+
148 162
             print
149 163
             print 'Tip:'
150
-            print 'sync_ip () { export ENV_VAR=$(curl -s "%s?k=2FN50L002036,2FN44N010911"); }' % os.environ['SCRIPT_URI']
164
+            print 'sync_ip () { export ENV_VAR=$(curl -s "%s?k=YP008G581095,2N00FG504225"); }' % os.environ['SCRIPT_URI']
151 165
             print 'curl --data "`hostname -s`=`hostname -i`&auth=$AUTH" "%s"' % os.environ['SCRIPT_URI']
152 166
             print 'Source code at http://git.dlma.com/kvs.git/'
153 167
 
154 168