本文整理汇总了Python中person.models.Person.load_session_stats方法的典型用法代码示例。如果您正苦于以下问题:Python Person.load_session_stats方法的具体用法?Python Person.load_session_stats怎么用?Python Person.load_session_stats使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类person.models.Person
的用法示例。
在下文中一共展示了Person.load_session_stats方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: person_session_stats_export
# 需要导入模块: from person.models import Person [as 别名]
# 或者: from person.models.Person import load_session_stats [as 别名]
def person_session_stats_export(request, session, cohort, statistic):
try:
stats = Person.load_session_stats(session)
except ValueError:
# no stats
raise Http404()
# collect data
rows = []
for person_id, person_stats in stats["people"].items():
if cohort not in [c["key"] for c in person_stats["cohorts"]]: continue
if statistic not in person_stats["stats"]: continue
if "context" not in person_stats["stats"][statistic]: continue
rows.append([
person_stats["stats"][statistic]["context"][cohort]["rank_ascending"],
person_stats["stats"][statistic]["context"][cohort]["rank_descending"],
person_stats["stats"][statistic]["context"][cohort]["percentile"],
person_stats["stats"][statistic]["value"],
int(person_id),
"", # bioguide ID
int(person_stats["role_id"]),
"", # state
"", # district
])
if len(rows) == 0:
raise Http404()
# assign sortname to the 2nd column so we can use it in sorting
people = Person.objects.in_bulk([r[4] for r in rows])
roles = PersonRole.objects.in_bulk([r[6] for r in rows])
for r in rows:
#if r[4] not in people: continue # database mismatch, happens during testing
r[5] = people[r[4]].bioguideid
r[6], r[7] = roles[r[6]].state, roles[r[6]].district if isinstance(roles[r[6]].district, int) else ""
r[8] = people[r[4]].lastname.encode("utf-8")
# sort by rank, then by name
rows.sort(key = lambda r : (r[0], r[8]))
# format CSV
import csv, StringIO
outfile = StringIO.StringIO()
writer = csv.writer(outfile)
writer.writerow(["rank_from_low", "rank_from_high", "percentile", statistic, "id", "bioguide_id", "state", "district", "name"])
for row in rows: writer.writerow(row)
output = outfile.getvalue()
# construct response
if request.GET.get("inline") is None:
r = HttpResponse(output, content_type='text/csv')
r['Content-Disposition'] = 'attachment; filename=' + "govtrack-stats-%s-%s-%s.csv" % (session, cohort, statistic)
else:
r = HttpResponse(output, content_type='text/plain')
return r
示例2: person_session_stats_overview
# 需要导入模块: from person.models import Person [as 别名]
# 或者: from person.models.Person import load_session_stats [as 别名]
def person_session_stats_overview(request, session, cohort, specific_stat):
try:
stats = Person.load_session_stats(session)
except ValueError:
# no stats
raise Http404()
from person.views_sessionstats import get_cohort_name, stat_titles
try:
cohort_title = get_cohort_name(cohort, True) if cohort else None
except ValueError:
# invalid URL
raise Http404()
# Get all of the cohorts in the data.
cohorts = { }
cohort_keys = set()
for person in stats["people"].values():
for c in person["cohorts"]:
c = c["key"]
cohorts[c] = cohorts.get(c, 0) + 1
cohort_keys.add(c)
cohorts = [ (-v, k, get_cohort_name(k, True), v) for k,v in cohorts.items() if "delegation" not in k and v > 10]
cohorts = sorted(cohorts)
# Gather data.
metrics = { }
for pid, person in stats["people"].items():
try:
personobj = Person.objects.get(id=int(pid))
except:
# debugging
continue
for stat, statinfo in person["stats"].items():
if specific_stat is not None and stat != specific_stat: continue
for cohort_key, context in statinfo.get("context", {}).items():
# filter by cohort, if we're doing that
if cohort is not None and cohort != cohort_key: continue
if cohort is None and cohort_key not in ("house", "senate"): continue
# create an entry for this statistic
metrics.setdefault(stat, {
"key": stat,
"title": stat_titles[stat]["title"],
"superlatives": stat_titles[stat]["superlatives"],
"icon": stat_titles[stat]["icon"],
"contexts": { }
})
metrics[stat]["title"] = metrics[stat]["title"].replace("{{other_chamber}}", "Other Chamber")
metrics[stat]["contexts"].setdefault(cohort_key, {
"key": cohort_key,
"title": get_cohort_name(cohort_key, True),
"N": context["N"],
"people": ([], []),
})
# if this person ranks #1, #2, #3, fill him in
c = metrics[stat]["contexts"][cohort_key]["people"]
if specific_stat is not None:
c[0].append( (context["rank_descending"], statinfo["value"], personobj) )
elif context["rank_ties"] <= 3:
if context["rank_ascending"] < 3:
c[1].append( (context["rank_descending"], statinfo["value"], personobj) )
elif context["rank_descending"] < 3:
c[0].append( (context["rank_descending"], statinfo["value"], personobj) )
metrics = sorted(metrics.values(), key = lambda m : m["title"])
for m in metrics:
m["contexts"] = sorted(m["contexts"].values(), key = lambda c : -c["N"])
for c in m["contexts"]:
c["people"][0].sort()
c["people"][1].sort()
#from person.views_sessionstats import clean_person_stats
#for pid, personstats in stats["people"].items():
# clean_person_stats(personstats)
import dateutil.parser
return {
"session": session,
"period": session_stats_period(session, stats),
"meta": stats["meta"],
"metrics": metrics,
"cohorts": cohorts,
"cohort": cohort,
"cohort_title": cohort_title,
"specific_stat": specific_stat,
"specific_stat_title": stat_titles[specific_stat]["title"].replace("{{other_chamber}}", "Other Chamber") if specific_stat else None,
"publishdate": dateutil.parser.parse(stats["meta"]["as-of"]),
}