本文整理汇总了Python中kalite.main.models.UserLog类的典型用法代码示例。如果您正苦于以下问题:Python UserLog类的具体用法?Python UserLog怎么用?Python UserLog使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了UserLog类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: query_logs
def query_logs(users, items, logtype, logdict):
"""
Get a specified subset of logs for a particular set of users for either exercises or videos.
users: list of users to query against.
items: list of either exercises of videos to query.
logtype: video or exercise - in future this could be expanded to query activity logs too.
logdict: user keyed dictionary of logs (presumed to be empty by this code)
"""
if logtype == "exercise":
all_logs = ExerciseLog.objects.filter(user__in=users, exercise_id__in=items).values(
'user', 'complete', 'exercise_id', 'attempts', 'points', 'struggling', 'completion_timestamp', 'streak_progress').order_by('completion_timestamp')
elif logtype == "video":
all_logs = VideoLog.objects.filter(user__in=users, video_id__in=items).values(
'user', 'complete', 'video_id', 'total_seconds_watched', 'completion_timestamp', 'points').order_by('completion_timestamp')
elif logtype == "activity" and UserLog.is_enabled():
all_logs = UserLog.objects.filter(user__in=users).values(
'user', 'last_active_datetime', 'total_seconds').order_by('last_active_datetime')
elif logtype == "summaryactivity" and UserLog.is_enabled():
all_logs = UserLogSummary.objects.filter(user__in=users).values(
'user', 'device', 'total_seconds').order_by('end_datetime')
else:
assert False, "Unknown log type: '%s'" % logtype # indicates a programming error
for log in all_logs:
logdict[log['user']].append(log)
return logdict
示例2: generate_fake_coachreport_logs
def generate_fake_coachreport_logs(password="hellothere"):
try:
t = FacilityUser.objects.get(facility=Facility.objects.all()[0], username=random.choice(firstnames))
except FacilityUser.DoesNotExist as e:
t = FacilityUser(facility=Facility.objects.all()[0], username=random.choice(firstnames))
t.set_password(password)
t.save()
# TODO: create flags later
num_logs = 20
logs = []
for _ in xrange(num_logs):
date_logged_in = datetime.datetime.now() - datetime.timedelta(days=random.randint(1, 10))
date_viewed_coachreport = date_logged_in + datetime.timedelta(minutes=random.randint(0, 30))
date_logged_out = date_viewed_coachreport + datetime.timedelta(minutes=random.randint(0, 30))
login_log = UserLog.objects.create(
user=t,
activity_type=UserLog.get_activity_int("login"),
start_datetime=date_logged_in,
last_active_datetime=date_viewed_coachreport,
end_datetime=date_logged_out,
)
logging.info("created login log for teacher %s" % t.username)
coachreport_log = UserLog.objects.create(
user=t,
activity_type=UserLog.get_activity_int("coachreport"),
start_datetime=date_viewed_coachreport,
last_active_datetime=date_viewed_coachreport,
end_datetime=date_viewed_coachreport,
)
logs.append((login_log, coachreport_log))
logging.info("created coachreport log for teacher %s" % t.username)
return logs
示例3: logout
def logout(request):
if "facility_user" in request.session:
# Logout, ignore any errors.
try:
UserLog.end_user_activity(request.session["facility_user"], activity_type="login")
except ValidationError as e:
logging.error("Failed to end_user_activity upon logout: %s" % e)
del request.session["facility_user"]
auth_logout(request)
next = request.GET.get("next", reverse("homepage"))
if next[0] != "/":
next = "/"
return HttpResponseRedirect(next)
示例4: logout
def logout(self, request, **kwargs):
self.method_check(request, allowed=['get'])
if "facility_user" in request.session:
try:
# First, update it because this is a real event
UserLog.update_user_activity(request.session["facility_user"], activity_type="login")
# ...then end it
UserLog.end_user_activity(request.session["facility_user"], activity_type="login")
del request.session['facility_user']
except ValidationError as e:
logging.error("Failed to end_user_activity upon logout: %s" % e)
logout(request)
return self.create_response(request, {
'success': True,
'redirect': reverse("homepage")
})
示例5: test_query_login_teacher
def test_query_login_teacher(self):
"""Check the # of queries when logging in as a teacher."""
teacher = FacilityUser(is_teacher=True, username="t1", facility=self.facility)
passwd = self._gen_valid_password()
teacher.set_password(passwd)
teacher.save()
with self.assertNumQueries(FuzzyInt(25, 43) + 3 * UserLog.is_enabled()):
self.browser_login_teacher("t1", passwd, self.facility)
示例6: test_query_login_student
def test_query_login_student(self):
"""Check the # of queries when logging in as a student."""
student = FacilityUser(is_teacher=False, username="s1", facility=self.facility)
passwd = self._gen_valid_password()
student.set_password(passwd)
student.save()
expected_num_queries = 30 + 3*UserLog.is_enabled()
with self.assertNumQueries(FuzzyInt(expected_num_queries - 3, expected_num_queries + 5)):
self.browser_login_student("s1", passwd, self.facility)
示例7: log_coach_report_view
def log_coach_report_view(request):
"""Record coach report view by teacher"""
if "facility_user" in request.session:
try:
# Log a "begin" and end here
user = request.session["facility_user"]
UserLog.begin_user_activity(user, activity_type="coachreport")
UserLog.update_user_activity(user, activity_type="login") # to track active login time for teachers
UserLog.end_user_activity(user, activity_type="coachreport")
except ValidationError as e:
# Never report this error; don't want this logging to block other functionality.
logging.error("Failed to update Teacher userlog activity login: %s" % e)
示例8: account_management
def account_management(request):
# Only log 'coachreport' activity for students,
# (otherwise it's hard to compare teachers)
if "facility_user" in request.session and not request.session["facility_user"].is_teacher and reverse("login") not in request.META.get("HTTP_REFERER", ""):
try:
# Log a "begin" and end here
user = request.session["facility_user"]
UserLog.begin_user_activity(user, activity_type="coachreport")
UserLog.update_user_activity(user, activity_type="login") # to track active login time for teachers
UserLog.end_user_activity(user, activity_type="coachreport")
except ValidationError as e:
# Never report this error; don't want this logging to block other functionality.
logging.error("Failed to update student userlog activity: %s" % e)
return student_view_context(request)
示例9: tabular_view
#.........这里部分代码省略.........
# Return groups and ungrouped
search_groups = search_groups[0] # make sure to include ungrouped students
users = FacilityUser.objects.filter(
Q(group__in=search_groups) | Q(group=None, facility=facility), is_teacher=False
).order_by(*student_ordering)
else:
# Show all (including ungrouped)
for groups_dict in groups:
search_groups += groups_dict["groups"]
users = FacilityUser.objects.filter(Q(group__in=search_groups) | Q(group=None), is_teacher=False).order_by(
*student_ordering
)
# We have enough data to render over a group of students
# Get type-specific information
if report_type == "exercise":
# Fill in exercises
exercises = get_topic_exercises(topic_id=topic_id)
exercises = sorted(exercises, key=lambda e: (e["h_position"], e["v_position"]))
context["exercises"] = exercises
# More code, but much faster
exercise_names = [ex["name"] for ex in context["exercises"]]
# Get students
context["students"] = []
exlogs = (
ExerciseLog.objects.filter(user__in=users, exercise_id__in=exercise_names)
.order_by(*["user__%s" % field for field in student_ordering])
.values("user__id", "struggling", "complete", "exercise_id")
)
exlogs = list(exlogs) # force the query to be evaluated
exlog_idx = 0
for user in users:
log_table = {}
while exlog_idx < len(exlogs) and exlogs[exlog_idx]["user__id"] == user.id:
log_table[exlogs[exlog_idx]["exercise_id"]] = exlogs[exlog_idx]
exlog_idx += 1
context["students"].append(
{ # this could be DRYer
"first_name": user.first_name,
"last_name": user.last_name,
"username": user.username,
"name": user.get_name(),
"id": user.id,
"exercise_logs": log_table,
}
)
elif report_type == "video":
# Fill in videos
context["videos"] = get_topic_videos(topic_id=topic_id)
# More code, but much faster
video_ids = [vid["id"] for vid in context["videos"]]
# Get students
context["students"] = []
vidlogs = (
VideoLog.objects.filter(user__in=users, video_id__in=video_ids)
.order_by(*["user__%s" % field for field in student_ordering])
.values("user__id", "complete", "video_id", "total_seconds_watched", "points")
)
vidlogs = list(vidlogs) # force the query to be executed now
vidlog_idx = 0
for user in users:
log_table = {}
while vidlog_idx < len(vidlogs) and vidlogs[vidlog_idx]["user__id"] == user.id:
log_table[vidlogs[vidlog_idx]["video_id"]] = vidlogs[vidlog_idx]
vidlog_idx += 1
context["students"].append(
{ # this could be DRYer
"first_name": user.first_name,
"last_name": user.last_name,
"username": user.username,
"name": user.get_name(),
"id": user.id,
"video_logs": log_table,
}
)
else:
raise Http404(_("Unknown report_type: %(report_type)s") % {"report_type": report_type})
if "facility_user" in request.session:
try:
# Log a "begin" and end here
user = request.session["facility_user"]
UserLog.begin_user_activity(user, activity_type="coachreport")
UserLog.update_user_activity(user, activity_type="login") # to track active login time for teachers
UserLog.end_user_activity(user, activity_type="coachreport")
except ValidationError as e:
# Never report this error; don't want this logging to block other functionality.
logging.error("Failed to update Teacher userlog activity login: %s" % e)
return context
示例10: test_query_logout_admin
def test_query_logout_admin(self):
""""""
self.test_query_login_admin()
with self.assertNumQueries(FuzzyInt(6, 7) + 0*UserLog.is_enabled()):
self.browser_logout_user()
示例11: generate_fake_exercise_logs
def generate_fake_exercise_logs(
facility_user=None, topics=topics, start_date=datetime.datetime.now() - datetime.timedelta(days=30 * 6)
):
"""Add exercise logs for the given topics, for each of the given users.
If no users are given, they are created.
If no topics exist, they are taken from the list at the top of this file.
By default, users start learning randomly between 6 months ago and now.
"""
date_diff = datetime.datetime.now() - start_date
exercise_logs = []
user_logs = []
# It's not a user: probably a list.
# Recursive case
if not hasattr(facility_user, "username"):
# It's NONE :-/ generate the users first!
if not facility_user:
(facility_user, _, _) = generate_fake_facility_users()
for topic in topics:
for user in facility_user:
(elogs, ulogs) = generate_fake_exercise_logs(facility_user=user, topics=[topic], start_date=start_date)
exercise_logs.append(elogs)
user_logs.append(ulogs)
# Actually generate!
else:
# Get (or create) user type
try:
user_settings = json.loads(facility_user.notes)
except:
user_settings = sample_user_settings()
facility_user.notes = json.dumps(user_settings)
facility_user.save()
date_diff_started = datetime.timedelta(
seconds=datediff(date_diff, units="seconds") * user_settings["time_in_program"]
) # when this user started in the program, relative to NOW
for topic in topics:
# Get all exercises related to the topic
exercises = get_topic_exercises(topic_id=topic)
# Problem:
# Not realistic for students to have lots of unfinished exercises.
# If they start them, they tend to get stuck, right?
#
# So, need to make it more probable that they will finish an exercise,
# and less probable that they start one.
#
# What we need is P(streak|started), not P(streak)
# Probability of doing any particular exercise
p_exercise = probability_of(qty="exercise", user_settings=user_settings)
logging.info(
"# exercises: %d; p(exercise)=%4.3f, user settings: %s\n"
% (len(exercises), p_exercise, json.dumps(user_settings))
)
# of exercises is related to
for j, exercise in enumerate(exercises):
if random.random() > p_exercise:
continue
# Probability of completing this exercise, and .. proportion of attempts
p_attempts = probability_of(qty="attempts", user_settings=user_settings)
attempts = int(random.random() * p_attempts * 30 + 10) # always enough to have completed
elog, created = ExerciseLog.objects.get_or_create(user=facility_user, exercise_id=exercise["id"])
alogs = []
for i in range(0, attempts):
alog = AttemptLog.objects.create(
user=facility_user, exercise_id=exercise["id"], timestamp=start_date + date_diff * i / attempts
)
alogs.append(alog)
if random.random() < user_settings["speed_of_learning"]:
alog.correct = True
alog.points = 10
alog.save()
elog.attempts = attempts
elog.latest_activity_timestamp = start_date + date_diff
elog.streak_progress = sum([log.correct for log in alogs][-10:]) * 10
elog.points = sum([log.points for log in alogs][-10:])
elog.save()
exercise_logs.append(elog)
ulog = UserLog(
user=facility_user,
activity_type=1,
start_datetime=start_date,
end_datetime=start_date + date_diff,
last_active_datetime=start_date + date_diff,
)
#.........这里部分代码省略.........
示例12: login
def login(request, facility):
facility_id = (facility and facility.id) or None
facilities = list(Facility.objects.all())
#Fix for #2047: prompt user to create an admin account if none exists
if not User.objects.exists():
messages.warning(request, _("No administrator account detected. Please run 'python manage.py createsuperuser' from the terminal to create one."))
# Fix for #1211: refresh cached facility info when it's free and relevant
refresh_session_facility_info(request, facility_count=len(facilities))
if request.method != 'POST': # render the unbound login form
referer = urlparse.urlparse(request.META["HTTP_REFERER"]).path if request.META.get("HTTP_REFERER") else None
# never use the homepage as the referer
if referer in [reverse("homepage"), reverse("add_facility_student")]:
referer = None
form = LoginForm(initial={"facility": facility_id, "callback_url": referer})
else: # process the login form
# log out any Django user or facility user
logout(request)
username = request.POST.get("username", "")
password = request.POST.get("password", "")
# first try logging in as a Django user
if not settings.CENTRAL_SERVER:
user = authenticate(username=username, password=password)
if user:
auth_login(request, user)
return HttpResponseRedirect(request.next or reverse("zone_redirect"))
# try logging in as a facility user
form = LoginForm(data=request.POST, request=request, initial={"facility": facility_id})
if not form.is_valid():
messages.error(
request,
_("There was an error logging you in. Please correct any errors listed below, and try again."),
)
else:
user = form.get_user()
try:
UserLog.begin_user_activity(user, activity_type="login", language=request.language) # Success! Log the event (ignoring validation failures)
except ValidationError as e:
logging.error("Failed to begin_user_activity upon login: %s" % e)
request.session["facility_user"] = user
messages.success(request, _("You've been logged in! We hope you enjoy your time with KA Lite ") +
_("-- be sure to log out when you finish."))
# Send them back from whence they came
landing_page = form.cleaned_data["callback_url"]
if not landing_page:
# Just going back to the homepage? We can do better than that.
landing_page = reverse("coach_reports") if form.get_user().is_teacher else None
landing_page = landing_page or (reverse("account_management") if False else reverse("homepage")) # TODO: pass the redirect as a parameter.
return HttpResponseRedirect(form.non_field_errors() or request.next or landing_page)
return {
"form": form,
"facilities": facilities,
"sign_up_url": reverse("add_facility_student"),
}
示例13: test_query_logout_student
def test_query_logout_student(self):
""""""
self.test_query_login_student()
with self.assertNumQueries(FuzzyInt(2, 11) + 11*UserLog.is_enabled()):
self.browser_logout_user()
示例14: login
def login(self, request, **kwargs):
self.method_check(request, allowed=['post'])
logout(request)
data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
facility = data.get('facility', '')
# first try logging in as a Django user
if not settings.CENTRAL_SERVER:
user = authenticate(username=username, password=password)
if user:
login(request, user)
return self.create_response(request, {
'success': True,
'redirect': reverse("zone_redirect")
})
# Find all matching users
users = FacilityUser.objects.filter(username=username, facility=facility)
if users.count() == 0:
if Facility.objects.count() > 1:
error_message = _("Username and password do not match. Make sure you choose the right facility.")
else:
error_message = _("Username and password do not match.")
return self.create_response(request, {
'messages': {'error': error_message},
'error_highlight': "password"
}, HttpUnauthorized )
for user in users:
if settings.SIMPLIFIED_LOGIN and not user.is_teacher:
# For simplified login, as long as it is a student account just take the first one!
break
# if we find a user whose password matches, stop looking
if user.check_password(password):
break
else:
user = None
if not user:
if Facility.objects.count() > 1:
error_message = _("Username and password do not match. Make sure you choose the right facility.")
else:
error_message = _("Username and password do not match.")
return self.create_response(request, {
'messages': {'error': error_message},
'error_highlight': "password"
}, HttpUnauthorized )
else:
try:
UserLog.begin_user_activity(user, activity_type="login", language=lcode_to_django_lang(request.language)) # Success! Log the event (ignoring validation failures)
except ValidationError as e:
logging.error("Failed to begin_user_activity upon login: %s" % e)
request.session["facility_user"] = user
messages.success(request, _("You've been logged in! We hope you enjoy your time with KA Lite ")
+ _("-- be sure to log out when you finish."))
extras = {'success': True}
if user.is_teacher:
extras.update({
"redirect": reverse("coach_reports", kwargs={"zone_id": getattr(Device.get_own_device().get_zone(), "id", "None")})
})
return self.create_response(request, extras)
示例15: _
{"key": "ex:attempts", "name": _("Attempts"), "type": "number", "description": _("Number of times submitting an answer to an exercise.")},
{"key": "ex:streak_progress", "name": _("Streak"), "type": "number", "description": _("Maximum number of consecutive correct answers on an exercise.")},
{"key": "ex:points", "name": _("Exercise points"), "type": "number", "description": _("[Pointless at the moment; tracks mastery linearly]")},
{ "key": "ex:completion_timestamp", "name": _("Time exercise completed"),"type": "datetime", "description": _("Day/time the exercise was completed.") },
{"key": "vid:points", "name": _("Video points"), "type": "number", "description": _("Points earned while watching a video (750 max / video).")},
{ "key": "vid:total_seconds_watched","name": _("Video time"), "type": "number", "description": _("Total seconds spent watching a video.") },
{ "key": "vid:completion_timestamp", "name": _("Time video completed"),"type": "datetime", "description": _("Day/time the video was completed.") },
]
user_log_stats_dict = [
{ "key": "usersum:total_seconds", "name": _("Time Active (s)"), "type": "number", "description": _("Total time spent actively logged in.")},
{ "key": "user:total_seconds", "name": _("Active Time Per Login"), "type": "number", "description": _("Duration of each login session."), "noscatter": True, "timeline": True},
{ "key": "user:last_active_datetime", "name": _("Time Session Completed"),"type": "datetime", "description": _("Day/time the login session finished.")},
]
if UserLog.is_enabled():
stats_dict.extend(user_log_stats_dict)
def get_data_form(request, *args, **kwargs):
"""Get the basic data form, by combining information from
keyword arguments and the request.REQUEST object.
Along the way, check permissions to make sure whatever's being requested is OK.
Request objects get priority over keyword args.
"""
assert not args, "all non-request args should be keyword args"
# Pull the form parameters out of the request or
data = dict()
# Default to empty string, as it makes template handling cleaner later.
for field in ["facility", "group", "user", "xaxis", "yaxis"]: