예제 #1
0
파일: mestat.py 프로젝트: HauptJ/atrack
def main():

    args = parse_qs(environ['QUERY_STRING'])
    form = FormPost()
    if form.has_key('FLUSH'):
        flush_all()

    if 'update' in args:
        stat()
        return
    
    ats = ['items', 'bytes', 'oldest_item_age', 'hits', 'byte_hits', 'misses']
    samples = mget('sample-times', namespace=NS)
    if not samples:
        stat()
        samples = mget('sample-times', namespace=NS) or []

    s = mmget([str(i) for i in samples], namespace=NS)
    a = []
    if s:
        a = dict([(k, [int(s[d][k]) for d in s]) for k in ats]) # attr -> vals
        a = dict([(k, (max(a[k]), min(a[k]), a[k])) for k in a]) # attrs -> (max, min, vals)
        #a = dict([(k, [61*(v+1-a[k][1])/(a[k][0]+1-a[k][1]) for v in a[k][2]]) for k in a]) # attrs -> norml-vals
        a = dict([(k, ([61*(v+1-a[k][1])/(a[k][0]+1-a[k][1]) for v in a[k][2]], a[k][1], a[k][0])) for k in a]) # attrs -> norml-vals

    print "Content-type: text/html"
    print ""
    #l = ["rend('"+k+"', %s);"%str([int(s[d][k]) for d in s]) for k in ats]
    #l = ["rend('"+k+"', %s);"%str([int(d) for d in a[k]]) for k in a]
    print """<html><head><script type="text/javascript" src="http://www.solutoire.com/download/gchart/gchart-0.2alpha_uncompressed.js"></script>
<script>
// Using: http://solutoire.com/gchart/
// x = """+repr(a)+"""
function rend(t, d, mx, mn) {
GChart.render({'renderTo': 'stats', 'size': '800x200', colors: 'FF0000,00FF00,0000FF,FFFF00,00FFFF,FF00FF', legend:'"""+'|'.join([k for k in a])+"""',  title: t, 'data': d});
}
function main() {
"""
    def rnd(name, data, mxmn, colors, legend):
        print "GChart.render({'size': '480x200&chg=0,20', axistype: 'x,y,r'," # colors: 'FF0000,00FF00,0000FF,FFFF00,00FFFF,FF00FF',"
        print "     renderTo: '"+name+"',"
        if len(data) == 2:
            print "     axisrange: '1,"+','.join([str(i) for i in mxmn[0]])+"|2,"+','.join([str(i) for i in mxmn[1]])+"',"
        elif len(data) == 1:
            print "     axisrange: '1,"+','.join([str(i) for i in mxmn[0]])+"', axistype: 'x,y',"
        print "     colors: '"+','.join(colors)+"',"
        print "     legend:'"+'|'.join([l for l in legend])+"',"
        print "     data: "+str([[int(d) for d in dd] for dd in data])
        print "});"

    #print "rend('stats', %s);"%str([[int(d) for d in a[k][0]] for k in a])
    if a:
        rnd('stats', [a['hits'][0], a['byte_hits'][0]], [a['hits'][1:3], a['byte_hits'][1:3]], ['FF0088', '0077cc'], ["Hits", "Hit Bytes"])
        rnd('stats', [a['items'][0], a['bytes'][0]], [a['items'][1:3], a['bytes'][1:3]], ['FF0088', '0077cc'], ["Items", "Bytes"])
        rnd('stats', [a['misses'][0]], [a['misses'][1:3]], ['FF0088'], ["Miss"])
        rnd('stats', [a['oldest_item_age'][0]], [[x/60 for x in a['oldest_item_age'][1:3]]], ['0077cc'], ["Max Age"])
    print """
예제 #2
0
파일: util.py 프로젝트: ikon42/reddit-unite
def data(**kwargs):
    '''Makes sure that certain pieces of information are always sent to
    the template engine along with the information supplied by the
    different handlers.
    '''
    data = {
        'site': web.ctx.homedomain,
        'user': {},
    }
    data.update(kwargs)
    user = users.get_current_user()
    if user:
        data['log_in_out'] = users.create_logout_url('/')
        data['logged_in'] = True
        data['user']['id'] = user.user_id()
        try:
            nickname = mget(key=user.user_id(), namespace='usernames')
            if nickname is None:
                q = User.all().filter('id', user.user_id()).fetch(1)
                nickname = q[0].nickname
                if not mset(key=user.user_id(), value=nickname, time=10, namespace='usernames'):
                    logging.error('Could not set memcache value!')
            data['user']['nickname'] = nickname
        except:
            data['user']['nickname'] = user.nickname()
        try:
            data['gravatar'] = get_gravatar(get_user(user_id=data['user_id'] or 'us').user.email())
        except KeyError:
            data['gravatar'] = get_gravatar('us')
    else:
        data['log_in_out'] = users.create_login_url('/')
        data['gravatar'] = get_gravatar('*****@*****.**')
    return data
예제 #3
0
파일: util.py 프로젝트: ikon42/reddit-unite
def get_user(user=None, user_id=None):
    '''Get a user from the DataStore using a User object or a user ID'''
    id = user.user_id() if user else user_id
    if id == 'us':
        return False
    else:
        e = mget(key=id, namespace='profile_data')
        if e is None:
            try:
                q = User.all().filter('id', id).fetch(1)
                e = q[0]
            except:
                u = User(
                    id=id,
                    user=user,
                    nickname=user.nickname(),
                )
                e = db.get(u.put())
        if e.bio is None or e.shared is None:
            if e.bio is None:
                m = User_Bio().put()
                e.bio = m
            if e.shared is None:
                p = User_Permissions().put()
                e.shared = p
            e = db.get(db.put(e))
        mset(key=id, value=e, time=10, namespace='profile_data')
        return e
예제 #4
0
def get_posts(limit=4):
    post_data = mget(
        key='_'.join([str(limit), 'posts']),
        namespace='posts'
    )
    if post_data is not None:
        return post_data
    else:
        query = Episode.all()
        query.order('-number')
        results = query.fetch(limit)
        post_data = [{
            'key': str(r.key()),
            'title': r.title,
            'number': r.number,
            'href': r.href,
            'thumb': r.thumb,
            'writeup': r.writeup,
        } for r in results]
        web.debug(post_data)
        if not madd(
            key='_'.join([str(limit), 'posts']),
            value=post_data,
            namespace="posts"
        ):
            logging.error('Memcache add failed!')
        return post_data
예제 #5
0
파일: util.py 프로젝트: ikon42/reddit-unite
def get_gravatar(email):
    '''Generates a gravatar image url for the passed email address'''
    url = mget(key=email, namespace='gravatars')
    if url is not None:
        return url
    else:
        url = ''.join([
            'https://secure.gravatar.com/avatar/',
            md5('*****@*****.**' if email.lower() == 'us' else email.lower()).hexdigest(),
            '?',
            urlencode({'s': '150', 'd': 'retro'}),
        ])
        mset(key=email, value=url, namespace='gravatars')
        return url
예제 #6
0
def main():

    args = parse_qs(environ['QUERY_STRING'])
    form = FormPost()
    if form.has_key('FLUSH'):
        flush_all()

    if 'update' in args:
        stat()
        return

    ats = ['items', 'bytes', 'oldest_item_age', 'hits', 'byte_hits', 'misses']
    samples = mget('sample-times', namespace=NS)
    if not samples:
        stat()
        samples = mget('sample-times', namespace=NS)

    s = mmget([str(i) for i in samples], namespace=NS)
    #
    a = dict([(k, [int(s[d][k]) for d in s]) for k in ats])  # attr -> vals
    a = dict([(k, (max(a[k]), min(a[k]), a[k]))
              for k in a])  # attrs -> (max, min, vals)
    #a = dict([(k, [61*(v+1-a[k][1])/(a[k][0]+1-a[k][1]) for v in a[k][2]]) for k in a]) # attrs -> norml-vals
    a = dict([
        (k,
         ([61 * (v + 1 - a[k][1]) / (a[k][0] + 1 - a[k][1])
           for v in a[k][2]], a[k][1], a[k][0])) for k in a
    ])  # attrs -> norml-vals
    print "Content-type: text/html"
    print ""
    #l = ["rend('"+k+"', %s);"%str([int(s[d][k]) for d in s]) for k in ats]
    #l = ["rend('"+k+"', %s);"%str([int(d) for d in a[k]]) for k in a]
    print """<html><head><script type="text/javascript" src="http://www.solutoire.com/download/gchart/gchart-0.2alpha_uncompressed.js"></script>
<script>
// Using: http://solutoire.com/gchart/
// x = """ + repr(a) + """
function rend(t, d, mx, mn) {
GChart.render({'renderTo': 'stats', 'size': '800x200', colors: 'FF0000,00FF00,0000FF,FFFF00,00FFFF,FF00FF', legend:'""" + '|'.join(
        [k for k in a]) + """',  title: t, 'data': d});
}
function main() {
"""

    def rnd(name, data, mxmn, colors, legend):
        print "GChart.render({'size': '480x200&chg=0,20', axistype: 'x,y,r',"  # colors: 'FF0000,00FF00,0000FF,FFFF00,00FFFF,FF00FF',"
        print "     renderTo: '" + name + "',"
        if len(data) == 2:
            print "     axisrange: '1," + ','.join([
                str(i) for i in mxmn[0]
            ]) + "|2," + ','.join([str(i) for i in mxmn[1]]) + "',"
        elif len(data) == 1:
            print "     axisrange: '1," + ','.join([str(i) for i in mxmn[0]
                                                    ]) + "', axistype: 'x,y',"
        print "     colors: '" + ','.join(colors) + "',"
        print "     legend:'" + '|'.join([l for l in legend]) + "',"
        print "     data: " + str([[int(d) for d in dd] for dd in data])
        print "});"

    #print "rend('stats', %s);"%str([[int(d) for d in a[k][0]] for k in a])
    rnd('stats', [a['hits'][0], a['byte_hits'][0]],
        [a['hits'][1:3], a['byte_hits'][1:3]], ['FF0088', '0077cc'],
        ["Hits", "Hit Bytes"])
    rnd('stats', [a['items'][0], a['bytes'][0]],
        [a['items'][1:3], a['bytes'][1:3]], ['FF0088', '0077cc'],
        ["Items", "Bytes"])
    rnd('stats', [a['misses'][0]], [a['misses'][1:3]], ['FF0088'], ["Miss"])
    rnd('stats', [a['oldest_item_age'][0]],
        [[x / 60 for x in a['oldest_item_age'][1:3]]], ['0077cc'], ["Max Age"])
    print """