_code.py

homeblogtwitterthingiverse



_code.py file for my site:


import random, os, string

password = u' ... '

vote_length = 20

def handle_vote(name, query):
    vote_name = query.get('votename',u'')

    record = eval(load(vote_name, u'_vote'))

    address = os.environ['REMOTE_ADDR']
    if address in record['ips']:
        return make_error(u'Someone at this IP has already voted')

    record['ips'] = [address] + record['ips'][:20]

    for key in query:
        if key[:3] == 'has':
            text = unquote_paranoid(key[3:])
            if text not in record['items']:
                continue

            if query.get('checkbox'+key[3:],u'') == u'on':
                record['items'][text] += '1'
            else:
                record['items'][text] += '0'
            
            record['items'][text] = record['items'][text][-vote_length:]

    new = query.get('new', u'')
    if new and new not in record['items'] and \
       query.get('newcheckbox',u'') == u'on':
        record['items'][new] = '1'

    for key in record['items'].keys():
        if len(record['items'][key]) >= vote_length and \
           '1' not in record['items'][key]:
            del record['items'][key]
    
    save(repr(record), vote_name, u'_vote')

    return make_redirect(query.get('page',u''))

vote_form_counter = 0

context_vote = ['item*', 'continue_to']
def markup_vote(text, meta, item=[ ], continue_to=None):
    global vote_form_counter
    vote_name = unquote_html(text).strip()
    
    if not exists(vote_name):
        return u''

    form_name = u'voteform'+unicode(vote_form_counter)
    vote_form_counter += 1

    if continue_to == None:
        continue_to = meta['name']
        
        
    try:
        if exists(vote_name, u'_vote'):
            record = eval(load(vote_name, u'_vote'))
        else:
            record = { 
                'n' : 0, 
                'items' : { },
                'ips' : [ ]
            }

        for i in item:
            i = unquote_html(i)
            if i not in record['items']:
                record['items'][i] = ''

        save(repr(record), vote_name, u'_vote')
    except:
        return u''

    address = os.environ['REMOTE_ADDR']
    already_voted = (address in record['ips'])

    list = [ ]
    for key in record['items']:
        data = record['items'][key]
        rating = data.count('1')
        rating2 = (rating+0.5) / (len(data)+1.0)
        list.append( (rating, rating2, data, key) )

    random.shuffle(list)
    list.sort(lambda a,b: cmp(b[0],a[0]))

    top = list[:3]
    list = list[3:]
    list.sort(lambda a,b: cmp(b[1],a[1]))
    #random.shuffle(list)
    list = top + list[:6]

    result = u'<table cellpadding=0 cellspacing=1>'
    n = 0
    for rating, rating2, data, name in list:
        if already_voted and rating == 0:
            continue

        result += u'<tr><td>'
        result += u'<table cellpadding=0 cellspacing=0 width=40>'
        result += u'<tr height=8>'

        votes = '-'*(20-len(data))+data
        for vote in votes:
            if vote == '-':
                color = u'#ffffff'
            elif vote == '1':
                #color = u'#ff8800'
                color = u'#ee7700'
            else:
                color = u'#eeeeee'
            result += u'<td width=2 bgcolor='+color+u'></td>'

        if len(list) <= 3 or (n <= 3 and list[3][0] < rating):
            font_color = u'#000000'
        else:
            font_color = u'#888888'

        result += u'</tr></table></td><td valign=top>'
        
        if not already_voted: 
            result += (u'<input type=hidden name=has' + 
                       quote_paranoid(name) + u' value=yes>' +
                       u'<input type=checkbox name=checkbox' + 
                       quote_paranoid(name) + u'>')

        result += (u'</td><td><font size=-2 color='+font_color+u'>' + 
                   name + u'</font></td></tr>')
        n += 1

    if not already_voted:
        result += (u'<tr><td></td><td><input type=checkbox name=newcheckbox></td><td>' +
                   u'<input name=new size=5 maxlength=30 onKeyPress="document.'+
                   form_name+'.newcheckbox.checked=true;">' +
                   u'</td></tr>'
                   u'<tr><td></td><td colspan=2 align=left>' +
                   u'<input value=vote type=submit>' +
                   u'</td></tr>')

    result += u'</table>'
    
    return u'<hr><p><font face="Sans-Serif">' + \
           make_form(result, extra_options=u'name='+form_name,
                     action='vote', votename=vote_name, page=continue_to) + \
           u'</font><p><hr>'


def markup_linkwithvote(text, meta, url=None, page=None, file=None):
    # extended to show vote
    title_bit = u''
    if page != None and file == None and \
       exists(page.strip(), u'_vote'):
        record = eval(load(page.strip(), u'_vote'))
        list = [ ]
        for key in record['items']:
            rating = record['items'][key].count('1')
            if rating:
                list.append( (rating, key) )

        if list:
            random.shuffle(list)
            list.sort(lambda a,b: cmp(b[0],a[0]))
            list = [ b for a,b in list[:3] ]

            title_bit = u' title="' + \
                        quote_html(string.join(list, u', ')) + u'"'
        else:
            title_bit = u' title="-"'


    text, url = _resolve_url(text, meta, url, page, file)

    return u'<a href="' + quote_html(url) + u'"' + \
           title_bit + u'>' + text + '</a>'



def handle_showcode(name, query):
    text = load(name)
    text = quote_html(text, True)
    text = text.replace('\n','\n<br>')

    return make_http_page(u"""\
[title Page markup: [_insert _pagename]]
[left][right]
Markup for page [link "[_insert _pagename]" [page [_insert _pagename]]]:


[sans [_insert_html _pagetext]]
""", { '_pagename': name, '_pagetext': text })


def handle_showself(name, query):
    file = open(data_dir+'/_code.py','r')
    text = file.read()
    file.close()

    text = text.replace(password, ' ... ')

    return make_http_page(u"""\
[title _code.py]
[left][right]
_code.py file for [link [page ] my site]:


[mono [_insert _pagetext]]
""", { '_pagetext': text })





[æ]