1 from __future__ import with_statement
2 import cgi, cPickle as pickle, itertools, sys
3 import KhipuDB
4
6 if isinstance (key, str):
7 def key_function (object):
8 attr = getattr (object, key)
9 if callable (attr):
10 return attr ()
11 else:
12 return attr
13 return key_function
14 else:
15 return key
16
18 if not keys: return all
19 key0 = make_key_function (keys[0])
20 all = sorted (all, key = key0)
21 grouped = [(k, list (occ)) for k, occ in
22 itertools.groupby (all, key = key0)]
23 index = {}
24 for key, value in grouped:
25 index[key] = index_by (value, keys[1:])
26 return index
27
29 if isinstance (out, str):
30 with open (out, 'w') as out:
31 return html_index (index, out)
32 def recurse (subindex, level):
33 if isinstance (subindex, list):
34 out.write ('<OL>\n')
35 for item in subindex:
36 if hasattr (item, 'nice_str'):
37 s = item.nice_str ()
38 else:
39 s = str (item)
40 s = cgi.escape (s)
41 out.write ('<LI> <A HREF="%s">%s</A> </LI>\n' % (item.url (), s))
42 out.write ('</OL>\n')
43 elif level == 0:
44 for key in sorted (subindex.keys ()):
45 out.write ('<H2>%s</H2>\n' % (key or '<blank>'))
46 recurse (subindex[key], level+1)
47 else:
48 out.write ('<DL>\n')
49 for key in sorted (subindex.keys ()):
50 out.write ('<DT> %s </DT>\n' % (key or '<blank>'))
51 out.write ('<DD>\n')
52 recurse (subindex[key], level+1)
53 out.write ('</DD>\n')
54 out.write ('</DL>\n')
55 recurse (index, 0)
56
58 if what.endswith ('s'):
59 what = what[:-1]
60 if out is None:
61 out = ('out/%ss_by_%s.html' % (what, ','.join (keys))).replace (' ', '_')
62 if isinstance (out, str):
63 with open (out, 'w') as out:
64 return make_html_index (db, what, keys, out)
65 out.write ('''\
66 <HTML>
67 <HEAD>
68 <TITLE>%ss grouped by %s</TITLE>
69 </HEAD>
70 <BODY>
71 <H1>%ss grouped by %s</H1>
72 ''' % ((what, ', '.join (keys)) * 2))
73 whatclass = getattr (KhipuDB, what)
74 all = whatclass.select (db, order_by = whatclass.id_field)
75 index = index_by (all, keys)
76 htmlify_index (index, out)
77 out.write ('''
78 </BODY>
79 </HTML>
80 ''')
81
83 db = KhipuDB.KhipuDB ()
84 if len (sys.argv) <= 1:
85 print 'Usage: %s (Cord|CordCluster|Knot|KnotCluster|Khipu) key-to-group-by ...'
86 sys.exit (1)
87 make_html_index (db, sys.argv[1], sys.argv[2:])
88 db.save_cache ()
89 db.close ()
90
91 if __name__ == '__main__': main ()
92