#!/usr/bin/python import sqlite import datetime import cgi, cgitb from math import ceil import re cgitb.enable NUM_PER_PAGE=50.0 buf = '' def out(txt): global buf buf += str(txt) def link(match): url = match.group('url') txt = url if len(txt) > 30: txt = txt[:20] + '…' + txt[-10:] return '%s' % (url, txt) def q(txt): txt = str(txt).replace('&','&').replace('<','<').replace('>','>').replace('"','"').replace('\n','
') # linkify rx = re.compile('(?P(https?://\S+|www\S+))') return rx.sub(link, txt) database = 'ubuntu' form = cgi.FieldStorage() try: page = int(form['page'].value) except: page = 0 order_by = 'added DESC' try: order_by = form['order'].value if order_by not in ('added DESC', 'added ASC', 'name DESC', 'name ASC', 'popularity DESC','popularity ASC'): order_by = 'added DESC' except: order_by = 'added DESC' con = sqlite.connect('/home/dennis/ubugtu/data/facts/%s.db' % database) cur = con.cursor() cur.execute("""SELECT COUNT(*) FROM facts WHERE value NOT LIKE '%%'""") num = cur.fetchall()[0][0] npages = int(ceil(num / float(NUM_PER_PAGE))) out('·') for i in range(npages): out(' %d ·' % (order_by, i, i+1)) out('
Order by
·') out(' %s ·' % ('name ASC', page, 'Name +')) out(' %s ·' % ('name DESC', page, 'Name -')) out(' %s ·' % ('popularity ASC', page, 'Popularity +')) out(' %s ·' % ('popularity DESC', page, 'Popularity -')) out(' %s ·' % ('added ASC', page, 'Date added +')) out(' %s ·' % ('added DESC', page, 'Date added -')) out('') cur.execute("SELECT name, value, author, added, popularity FROM facts WHERE value NOT LIKE '%%' ORDER BY %s LIMIT %d, %d" % (order_by, page*NUM_PER_PAGE, NUM_PER_PAGE)) factoids = cur.fetchall() i = 0 for f in factoids: cur.execute("SELECT name FROM facts WHERE value LIKE %s", ' ' + f[0]) f = list(f) f[0] += '\n' + '\n'.join([x[0] for x in cur.fetchall()]) out('' % tuple([q(x) for x in f])) out('
FactoidValueAuthor
%s%s%s
Added on: %s
Requested %s times
') print "Content-Type: text/html; charset=UTF-8" print "" fd = open('factoids.tmpl') tmpl = fd.read() fd.close() print tmpl % (buf)