def get(self): """Handles GET requests.""" user = self.personalize_page_and_get_user() student = Student.get_by_email(user.email()) if not user: self.template_value['loginUrl'] = users.create_login_url('/') else: self.template_value['playlist'] = student.playlist self.template_value['playlist_urls'] = student.playlist_urls self.template_value['email'] = user.email() self.template_value['logoutUrl'] = users.create_logout_url('/') if len(student.playlist) > 0: #unit_id = str(student.playlist[0][0]) #lesson_id = str(student.playlist[0][2]) self.template_value['start_plist_url'] = str(student.playlist[0]) #('unit?unit=%s&lesson=%s' % (unit_id, lesson_id)) self.template_value['hasList'] = True else: self.template_value['hasList'] = False self.template_value['navbar'] = {'course': True} self.template_value['units'] = self.get_units() if user and Student.get_enrolled_student_by_email(user.email()): self.render('playlist.html') else: self.redirect('/preview')
def post(self): """Handles POST requests.""" user = self.personalize_page_and_get_user() if not user: self.redirect(users.create_login_url(self.request.uri), normalize=False) return if not self.assert_xsrf_token_or_fail(self.request, "register-post"): return can_register = self.app_context.get_environ()["reg_form"]["can_register"] if not can_register: self.redirect("/course#registration_closed") return if "name_from_profile" in self.request.POST.keys(): profile = StudentProfileDAO.get_profile_by_user_id(user.user_id()) name = profile.nick_name else: name = self.request.get("form01") Student.add_new_student_for_current_user(name, transforms.dumps(self.request.POST.items())) course = sites.get_course_for_current_request() if course.get_slug().split("_")[-1] == "DFR": self.redirect("/gDefier/register") else: self.redirect("/course#registration_confirmation")
def finish(self): leader_badge_slugs = ('expert.leader', 'expert.expertise.leader') leader_badges = dict((k, Badge.get_by_key_name(k)) for k in leader_badge_slugs) for group_id, (emails, count) in self.best_by_group.iteritems(): self.log.append('Considering group %s, best score is %d' % ( str(group_id), count)) if count < 1: self.log.append('... Best score is too low, skipping.') continue for email in emails: report = ExpertBadgeReport.on( db.Key.from_path(Student.kind(), email), course=self.course, force_re_run=self.re_run) base_badge_version = choose_expert_badge_version(report.completion()) if not base_badge_version: raise AssertionError('They should have passed, wat?') leader_badge_slug = base_badge_version + '.leader' if self.really: leader_badge = leader_badges[leader_badge_slug] b = Badge.issue(leader_badge, db.Key.from_path(Student.kind(), email), put=False) b.evidence = self.host_url + '/badges/expert_evidence?id=%d' % report.key().id() b.put() self.log.append('... ISSUED %s to %s, id=%d' % ( leader_badge_slug, email, b.key().id())) else: self.log.append('... WOULD ISSUE %s to %s' % ( leader_badge_slug, email)) self._batch_write()
def get(self): """Handles GET request.""" user = self.personalize_page_and_get_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return student = Student.get_enrolled_student_by_email(user.email()) if student: self.redirect("/course") return # Check global student data namespace = namespace_manager.get_namespace() try: namespace_manager.set_namespace("") student = Student.get_enrolled_student_by_email(user.email()) finally: namespace_manager.set_namespace(namespace) if student: create_or_enroll_student(user, student.name) self.template_value["navbar"] = {"registration": True} self.render("confirmation.html") return self.template_value["navbar"] = {"registration": True} self.template_value["register_xsrf_token"] = XsrfTokenManager.create_xsrf_token("register-post") self.render("register.html")
def post(self): """Handles POST requests.""" user = self.personalize_page_and_get_user() if not user: self.redirect( users.create_login_url(self.request.uri), normalize=False) return if not self.assert_xsrf_token_or_fail(self.request, 'register-post'): return can_register = self.app_context.get_environ( )['reg_form']['can_register'] if not can_register: self.redirect('/course#registration_closed') return if 'name_from_profile' in self.request.POST.keys(): profile = StudentProfileDAO.get_profile_by_user_id(user.user_id()) name = profile.nick_name else: name = self.request.get('form01') Student.add_new_student_for_current_user( name, transforms.dumps(self.request.POST.items())) # Render registration confirmation page self.redirect('/course#registration_confirmation')
def finish(self): if self.really: leader_badges = dict((key, Badge.get_by_key_name(key)) for key in self.leader_badge_keys) for group_id, (emails, count) in self.best_by_group.iteritems(): self.log.append('Considering group %s, best score is %d' % ( str(group_id), count)) if count < 1: self.log.append('... Best score is too low, skipping.') continue if self.really: for email in emails: report = PartReport.on( db.Key.from_path(Student.kind(), email), course=self.course, part=self.part, force_re_run=self.re_run) base_badge_version = choose_badge_version(report.slug, report.completion()) leader_badge_version = combine_badge_slug_parts(base_badge_version, 'leader') leader_badge = leader_badges[leader_badge_version] assert leader_badge, "Should be a badge called %s" % leader_badge_version b = Badge.issue(leader_badge, db.Key.from_path(Student.kind(), email), put=False) b.evidence = self.host_url + '/badges/evidence?id=%d' % report.key().id() b.put() self.log.append('... ISSUED leader badge %s to %s, id=%d' % ( leader_badge_version, email, b.key().id())) else: self.log.append('... WOULD ISSUE leader badge to %s' % ' '.join(emails)) self._batch_write()
def get(self): schedule_items = [] schedule_items.append(ScheduleItem(time_from='10.30', time_until='12.50', vak_code='ANL05', docent_code='paris', chamber='h.05.002')) schedule_items.append(ScheduleItem(time_from='13.30', time_until='15.50', vak_code='SLC', docent_code='muill', chamber='H.04.318')) schedule_item_keys = [] for i in schedule_items: schedule_item_keys.append(i.put()) schedule = Schedule(day='Wednesday', schedule_item=schedule_item_keys) schedule_key = [schedule.put()] grade = Grade(study_points=4, passed=True, grades=8.1, docent='Busker', concept=False, exam_date='1-5-2015', mutation_date='5-5-2015', weight=1) grade_key = grade.put() grades_list = GradesList(vak_code='dev06', grades=grade_key) grades_list_key = [grades_list.put()] student = Student( parent=student_key(key="0846735"), student_nr="0846735", password='******', first_name='Jeroen', last_name='Stravers', country='Nederland', birthday='12-08-1988', email='*****@*****.**', telephone_nr='0678945032', groups=['inf1F', 'inf2c'], zip_address='4435-GK', street='Kruisplein', schedule=schedule_key, grade_list=grades_list_key ) student.put() obj = {"test:", "done"} self.response.write(obj)
def post(self): user = self.personalizePageAndGetUser() if not user: self.redirect(users.create_login_url(self.request.uri)) return if (MAX_CLASS_SIZE and Student.all(keys_only=True).count() >= MAX_CLASS_SIZE): self.templateValue['course_status'] = 'full' else: # Create student record name = self.request.get('form01') # create new or re-enroll old student student = Student.get_by_email(user.email()) if student: if not student.is_enrolled: student.is_enrolled = True student.name = name else: student = Student(key_name=user.email(), name=name, is_enrolled=True) student.put() # Render registration confirmation page self.templateValue['navbar'] = {'registration': True} self.render('confirmation.html')
def post(self): args = parse.parse_args() s_name = args.get('s_name') student = Student() student.s_name = s_name if not student.save(): abort(400, msg='not') return {'msg': 'Hello World'}
def get(self): schedule_items = [] schedule_items.append( ScheduleItem(time_from='10.30', time_until='12.50', vak_code='ANL05', docent_code='paris', chamber='h.05.002')) schedule_items.append( ScheduleItem(time_from='13.30', time_until='15.50', vak_code='SLC', docent_code='muill', chamber='H.04.318')) schedule_item_keys = [] for i in schedule_items: schedule_item_keys.append(i.put()) schedule = Schedule(day='Wednesday', schedule_item=schedule_item_keys) schedule_key = [schedule.put()] grade = Grade(study_points=4, passed=True, grades=8.1, docent='Busker', concept=False, exam_date='1-5-2015', mutation_date='5-5-2015', weight=1) grade_key = grade.put() grades_list = GradesList(vak_code='dev06', grades=grade_key) grades_list_key = [grades_list.put()] student = Student(parent=student_key(key="0846735"), student_nr="0846735", password='******', first_name='Jeroen', last_name='Stravers', country='Nederland', birthday='12-08-1988', email='*****@*****.**', telephone_nr='0678945032', groups=['inf1F', 'inf2c'], zip_address='4435-GK', street='Kruisplein', schedule=schedule_key, grade_list=grades_list_key) student.put() obj = {"test:", "done"} self.response.write(obj)
def get(self): if not(Roles.is_course_admin(self.app_context)): self.redirect("preview") self.response.headers['Content-type'] = 'text/csv' self.response.headers['Content-disposition'] = 'attachment; filename=students.csv' course = self.get_course() assessments=[] for unit in course.get_units(): if (unit.type=="A"): assessments.append(str(unit.unit_id)) writer = UnicodeWriter(self.response.out) keys = Student.all(keys_only=True).run() rows=[] for key in keys: student=Student.get_by_key_name(key.name()) rec={"email": key.name(), "name": student.name, "enrolled": unicode(student.is_enrolled), "dateEnrolled": unicode(student.enrolled_on) } if (student.scores): scores=json.loads(student.scores) for assessmentName, score in scores.iteritems(): rec[assessmentName]=str(score) rows.append(rec) headerRow = ["Email", "Name", "Is Enrolled", "Enrolled On"] for assessmentName in assessments: headerRow.append(course.find_unit_by_id(assessmentName).title) writer.writerow(headerRow) for row in rows: renderedRow=[row["email"],row["name"],row["enrolled"],row["dateEnrolled"]] for assessmentName in assessments: if (assessmentName in row): renderedRow.append(row[assessmentName]) else: renderedRow.append("") writer.writerow(renderedRow)
def post(self): schedule_items = [] schedule_items.append(ScheduleItem(time_from='08.30', time_until='10.50', vak_code='Dev05', docent_code='paris', chamber='wd.03.002')) schedule_items.append(ScheduleItem(time_from='11.30', time_until='13.50', vak_code='Skils', docent_code='Yolo', chamber='H.04.318')) schedule_item_keys = [] for i in schedule_items: schedule_item_keys.append(i.put()) schedule = Schedule(day='Monday', schedule_item=schedule_item_keys) schedule_key = [schedule.put()] grade = Grade(study_points=3, passed=True, grades=7.0, docent='busker', concept=False, exam_date='1-5-2015', mutation_date='5-5-2015', weight=1) grade_key = grade.put() grades_list = GradesList(vak_code='dev04', grades=grade_key) grades_list_key = [grades_list.put()] student = Student( parent=student_key(key="0883374"), student_nr="0883374", password='******', first_name='Geddy', last_name='Schellevis', country='Nederland', birthday='05-03-1990', email='*****@*****.**', telephone_nr='0653380120', groups=['inf1F', 'inf2c'], zip_address='4444-LP', street='ergens', schedule=schedule_key, grade_list=grades_list_key ) student.put()
def post(self): """Handles POST requests.""" user = self.personalize_page_and_get_user() if not user: self.redirect( users.create_login_url(self.request.uri), normalize=False) return if not self.assert_xsrf_token_or_fail(self.request, 'register-post'): return can_register = self.app_context.get_environ( )['reg_form']['can_register'] if not can_register: self.redirect('/course#registration_closed') return if 'name_from_profile' in self.request.POST.keys(): profile = StudentProfileDAO.get_profile_by_user_id(user.user_id()) name = profile.nick_name else: name = self.request.get('form01') Student.add_new_student_for_current_user( name, transforms.dumps(self.request.POST.items())) # CGL-MOOC-Builder: Get user's Google App email and # course title, email body from course setting page. course = self.app_context.get_environ()['course'] if 'google_app_email' in course: sender_email = course['google_app_email'] else: sender_email = '' if 'title' in course: course_title = course['title'] else: course_title = '' if 'email_body' in course and course['email_body'] != '': email_body = course['email_body'] else: email_body = "<div style='background-color: #999999; color: #ffffff; padding: 0px 20px 20px 20px; font-family: 'Verdana', sans-serif;'> <div style='width: 500px; margin: 0 auto;'> <p style='background-color: #093359; height: 100px; margin: 0px; padding: 0px;'> <img src='http://cloudmooc.pti.indiana.edu:8080/assets/img/Logo.png'></img> </p> <div style='background-color: #CCC; color: black; padding: 15px;'> <p>Welcome " + name + ",</p> <p>Thank you for enrolling in this.</p> </div> <p style='background-color: #012256; height: 50px; margin: 0px; padding: 0px;'></p></div></div>" # CGL-MOOC-Builder starts: # Send an notification email after registration sender_address = course_title + " <"+sender_email+">" user_address = name + " <" + user.email() + ">" subject = "Welcome "+name+" to "+course_title body = "Welcome!" html = email_body mail.send_mail(sender_address, user_address, subject, body, html=html) # CGL-MOOC-Builder ends # Render registration confirmation page self.redirect('/course#registration_confirmation')
def post(self): """Handles POST requests.""" user = self.personalize_page_and_get_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return if not self.assert_xsrf_token_or_fail(self.request, 'register-post'): return can_register = self.app_context.get_environ( )['reg_form']['can_register'] if not can_register: self.template_value['course_status'] = 'full' else: name = self.request.get('form01') surname = self.request.get('form02') age = self.request.get('form03') # create new or re-enroll old student student = Student.get_by_email(user.email()) if not student: student = Student(key_name=user.email()) student.user_id = user.user_id() student.is_enrolled = False student.name = name student.surname = surname student.age = age student.put() # Render registration confirmation page self.template_value['navbar'] = {'registration': True} self.render('confirmation.html')
def post(self): schedule_items = [] schedule_items.append( ScheduleItem(time_from='08.30', time_until='10.50', vak_code='Dev05', docent_code='paris', chamber='wd.03.002')) schedule_items.append( ScheduleItem(time_from='11.30', time_until='13.50', vak_code='Skils', docent_code='Yolo', chamber='H.04.318')) schedule_item_keys = [] for i in schedule_items: schedule_item_keys.append(i.put()) schedule = Schedule(day='Monday', schedule_item=schedule_item_keys) schedule_key = [schedule.put()] grade = Grade(study_points=3, passed=True, grades=7.0, docent='busker', concept=False, exam_date='1-5-2015', mutation_date='5-5-2015', weight=1) grade_key = grade.put() grades_list = GradesList(vak_code='dev04', grades=grade_key) grades_list_key = [grades_list.put()] student = Student(parent=student_key(key="0883374"), student_nr="0883374", password='******', first_name='Geddy', last_name='Schellevis', country='Nederland', birthday='05-03-1990', email='*****@*****.**', telephone_nr='0653380120', groups=['inf1F', 'inf2c'], zip_address='4444-LP', street='ergens', schedule=schedule_key, grade_list=grades_list_key) student.put()
def add_students(self, prepod_id=None, count=10): for _ in range(count): student = Student(name=fake.first_name()) if prepod_id is None: prepod_id = self.add_prepod().id student.prepod_id = prepod_id self.connection.session.add(student) self.connection.session.commit()
def post_save(self): if not Roles.is_course_admin(self.app_context): self.abort(403, 'You are not an admin :(') user = self.personalize_page_and_get_enrolled() student_email = self.request.GET.get('email', None) if not student_email: self.abort(404, 'email= parameter required') student = Student.get_enrolled_student_by_email(student_email) if not student: self.abort(404, Markup('Could not find a student with email "%s"') % student_email) badge_slug = custom_badge_name(student) badge = Badge.get_or_insert(badge_slug) badge_form = BadgeForm(self.request.POST, badge) comments_form = CommentsForm(self.request.POST) if not (badge_form.validate() and comments_form.validate()): self.render_edit(badge_form, comments_form) return comments_form.validate() reviewer = Student.get_by_email(comments_form.review_source.data) if not reviewer: comments_form.review_source.errors.append("Could not find a user with that e-mail address") self.render_edit(badge_form, comments_form) return page = WikiPage.get_page(student, unit=UNIT_NUMBER) if not page: self.abort(404, Markup('Could not find unit %d wikifolio for student "%s"') % (UNIT_NUMBER, student_email)) old_reviews = Annotation.reviews(whose=student, unit=UNIT_NUMBER).run() db.delete(old_reviews) Annotation.review(page, who=reviewer, text=comments_form.public_comments.data) if not Annotation.endorsements(what=page, who=user).count(limit=1): Annotation.endorse(page, who=user, optional_done=True) badge_form.populate_obj(badge) badge.put() report = PartReport.on(student, self.get_course(), 4, force_re_run=True, put=False) for rep in report.unit_reports: rep._run() rep.put() report.slug = badge_slug report.put() assertion = Badge.issue(badge, student, put=False) assertion.evidence = urljoin(self.request.host_url, '/badges/evidence?id=%d' % report.key().id()) assertion.put() self.response.write( Markup("Issued badge %s to %s, evidence %s") % ( badge.key().name(), student_email, assertion.evidence))
def post(self): """Handles POST requests.""" student = self.personalize_page_and_get_enrolled() if not student: return if not self.assert_xsrf_token_or_fail(self.request, 'student-edit'): return Student.rename_current(self.request.get('name')) self.redirect('/student/home')
def post(self): """Handles POST requests.""" student = self.personalize_page_and_get_enrolled() if not student: return if not self.assert_xsrf_token_or_fail(self.request, 'student-unenroll'): return Student.set_enrollment_status_for_current(False) self.template_value['navbar'] = {'registration': True} self.render('unenroll_confirmation.html')
def post(self): """Handles POST requests.""" student = self.personalize_page_and_get_enrolled() if not student: return if not self.assert_xsrf_token_or_fail(self.request, 'student-unenroll'): return for hook in self.POST_HOOKS: hook(student, self.request) Student.set_enrollment_status_for_current(False) self.template_value['navbar'] = {} self.template_value['transient_student'] = True self.render('unenroll_confirmation.html')
def post(self): """Handles POST requests.""" user = self.personalize_page_and_get_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return if not self.assert_xsrf_token_or_fail(self.request, 'register-post'): return can_register = self.app_context.get_environ( )['reg_form']['can_register'] if not can_register: self.template_value['course_status'] = 'full' else: name = self.request.get('form01') # create new or re-enroll old student student = Student.get_by_email(user.email()) if not student: student = Student(key_name=user.email()) student.user_id = user.user_id() student.is_enrolled = True student.name = name student.put() # Render registration confirmation page self.template_value['navbar'] = {'registration': True} self.render('confirmation.html')
def post(self): """Handles POST requests.""" student = self.personalize_page_and_get_enrolled() if not student: return if not self.assert_xsrf_token_or_fail(self.request, "student-unenroll"): return Student.set_enrollment_status_for_current(False) self.template_value["navbar"] = {} self.template_value["transient_student"] = True self.render("unenroll_confirmation.html")
def __init__(self): if 'student' not in session: return redirect(url_for('index')) self.newStudent_interest = Student_interest() self.newCourse_interest = Course_interest() self.newInterest = Interest() self.newCourse = Course() self.newStudent_subscription = Student_subscription() self.newStudent = Student() self.newInstructor = Instructor() self.newLesson = Lesson() self.newStudent_question = Student_question() self.newQuestion_response = Question_response()
def __init__(self): if 'instructor' in session: self.loggedIn = True self.newStudent_interest = Student_interest() self.newCourse_interest = Course_interest() self.newInterest = Interest() self.newCourse = Course() self.newStudent_subscription = Student_subscription() self.newStudent = Student() self.newInstructor = Instructor() self.newLesson = Lesson() self.newStudent_question = Student_question() self.newQuestion_response = Question_response()
def add_students(self, prepod_id=None, count=10): for _ in range(count): # Создаем нового студента student = Student(name=fake.first_name()) if prepod_id is None: # Генерируем случайного препода, запоминаем его id prepod_id = self.add_prepod().id # Указываем преподавателя для студента student.prepod_id = prepod_id # Записываем созданную модуль в базу self.connection.session.add(student) self.connection.session.commit()
def post(self): """Handles POST requests.""" user = self.personalize_page_and_get_user() if not user: self.redirect(users.create_login_url(self.request.uri), normalize=False) return if not self.assert_xsrf_token_or_fail(self.request, 'register-post'): return can_register = self.app_context.get_environ( )['reg_form']['can_register'] if not can_register: self.redirect('/course#registration_closed') return if 'name_from_profile' in self.request.POST.keys(): profile = StudentProfileDAO.get_profile_by_user_id(user.user_id()) name = profile.nick_name else: name = self.request.get('form01') age = self.request.get('age') #Age city = self.request.get('city') #City state = self.request.get('state') #State country = self.request.get('country') #Country education = self.request.get('education') #Education profession = self.request.get('profession') #Profession organization = self.request.get('organization') #Organization motivation = self.request.get('motivation') #Motivation referral = self.request.get('referral') #Referral privacy = self.request.get('privacy') #Privacy Student.add_new_student_for_current_user( name, age, city, state, country, education, profession, organization, motivation, referral, privacy, transforms.dumps(self.request.POST.items())) # send a notification email sender_address = "MOOCbuilder <*****@*****.**>" user_address = name + " <" + user.email() + ">" subject = "Welcome to the Big Data Applications and Analytics MOOC" body = "Dear " + name + ", Example HTML content" html = "<div style='background-color: #666666; color: #ffffff; padding: 0px 20px 20px 20px; font-family: 'Verdana', sans-serif;'> <div style='width: 500px; margin: 0 auto;'> <p style='background-color: #012256; height: 100px; margin: 0px; padding: 0px;'><img src='http://cloudmooc.pti.indiana.edu:8080/assets/img/Logo.png'></img></p> <div style='background-color: #CCC; color: black; padding: 15px;'> <p>Welcome " + name + ",</p> <p>Thank you for enrolling in <a href='https://bigdatacourse.appspot.com' title='Big Data Applications and Analytics MOOC' target='_blank' style='color: #003366; '>Big Data Applications and Analytics MOOC</a>. This MOOC will take you on a journey to learn great things about Big Data and its case studies.</p> <p>This course is open for everyone, so watch a unit or two whenever you get time. You can also review homework assignments of your peers and view your feedback!</p><p>You can download the entire <a href='http://tinyurl.com/bigdatasyllabus' title='Big Data MOOC Course Syllabus' target='_blank'>syllabus</a>, <a href='https://www.dropbox.com/s/2p2zj9jbywcb76u/Course_Slides.pdf' title='Big Data MOOC Course Slides' target='_blank'>slides</a>, and the entire <a href='https://www.dropbox.com/s/htvr0l9d6g2gl71/Big_Data_Course_Material.zip' title='Big Data MOOC Course Material Zip File' target='_blank'>course material</a> directly.</p><p>Get Ready!<br> Geoffrey Fox and the Big Data MOOC Team</p> <p>Go to the <a href='https://bigdatacourse.appspot.com' title='Big Data Applications and Analytics MOOC' target='_blank' style='color: #003366;'>Course</a></p> <p>Share this MOOC with your friends!</p> </div> <p style='background-color: #012256; height: 50px; margin: 0px; padding: 0px;'></p> </div> </div>" mail.send_mail(sender_address, user_address, subject, body, html=html) # Render registration confirmation page self.redirect('/course#registration_confirmation')
def get(self): """Get a students progress.""" #teachers aren't course admins, so we probably shouldn't check for that # if not roles.Roles.is_course_admin(self.app_context): # transforms.send_json_response(self, 401, 'Access denied.', {}) # return key = self.request.get('student') errors = [] student = Student.get_by_email(key.strip()) course = self.get_course() if student: units = teacher_parsers.StudentProgressTracker.get_detailed_progress(student, course) else: errors.append('An error occurred retrieving student data. Contact your course administrator.') self.validation_error('\n'.join(errors)) return payload_dict = { 'units': units, 'student_name': student.name, 'student_email': student.email } transforms.send_json_response( self, 200, '', payload_dict=payload_dict, xsrf_token=crypto.XsrfTokenManager.create_xsrf_token( self.XSRF_TOKEN))
def get(self): """Get activity scores.""" request = transforms.loads(self.request.get('request')) payload = transforms.loads(request.get('payload')) errors = [] students = payload['students'] force_refresh = payload['forceRefresh'] course = self.get_course() temp_students = [] for student in students: if '@' in student: temp_students.append(Student.get_by_email(student).user_id) if len(temp_students) > 0: students = temp_students if len(students) > 0: scores = teacher_parsers.ActivityScoreParser.get_activity_scores(students, course, force_refresh) else: errors.append('An error occurred retrieving activity scores. Contact your course administrator.') self.validation_error('\n'.join(errors)) return payload_dict = { 'scores': scores['scores'], 'dateCached': scores['date'].strftime("%B %d, %Y %H:%M:%S") } transforms.send_json_response( self, 200, '', payload_dict=payload_dict, xsrf_token=crypto.XsrfTokenManager.create_xsrf_token( self.XSRF_TOKEN))
def get(self): student = Student.get_by_email(self.request.get('img_id')) if student.avatar: self.response.headers['Content-Type'] = 'image/png' self.response.out.write(student.avatar) else: self.error(404)
def update_assessment_transaction( self, email, assessment_type, new_answers, score): """Stores answer and updates user scores.""" student = Student.get_by_email(email) # It may be that old Student entities don't have user_id set; fix it. if not student.user_id: student.user_id = self.get_user().user_id() answers = StudentAnswersEntity.get_by_key_name(student.user_id) if not answers: answers = StudentAnswersEntity(key_name=student.user_id) answers.updated_on = datetime.datetime.now() utils.set_answer(answers, assessment_type, new_answers) assessment_type = store_score(student, assessment_type, score) student.put() answers.put() # Also record the event, which is useful for tracking multiple # submissions and history. models.EventEntity.record( 'submit-assessment', self.get_user(), json.dumps({ 'type': 'assessment-%s' % assessment_type, 'values': new_answers, 'location': 'AnswerHandler'})) return (student, assessment_type)
def get_list(self): """Shows a list of announcements.""" student = None user = self.personalize_page_and_get_user() transient_student = False if user is None: transient_student = True else: student = Student.get_enrolled_student_by_email(user.email()) if not student: transient_student = True self.template_value['transient_student'] = transient_student items = AnnouncementEntity.get_announcements() if not items and AnnouncementsRights.can_edit(self): items = self.put_sample_announcements() items = AnnouncementsRights.apply_rights(self, items) if not roles.Roles.is_course_admin(self.get_course().app_context): items = models.LabelDAO.apply_course_track_labels_to_student_labels( self.get_course(), student, items) self.template_value['announcements'] = self.format_items_for_template( items) self._render()
def get_list(self): """Shows a list of announcements.""" user = self.personalize_page_and_get_user() transient_student = False if user is None: transient_student = True else: student = Student.get_enrolled_student_by_email(user.email()) if not student: transient_student = True else: #progress bar total_progress = (self.get_progress_tracker(). get_overall_progress_score(student)) self.template_value['progress_value'] = total_progress.get( 'progress_score', 0) self.template_value['complete_value'] = total_progress.get( 'completed_score', 0) self.template_value['percentage'] = total_progress.get( 'percentage', '') self.template_value['transient_student'] = transient_student items = AnnouncementEntity.get_announcements() if not items and AnnouncementsRights.can_edit(self): items = self.put_sample_announcements() items = AnnouncementsRights.apply_rights(self, items) self.template_value['announcements'] = self.format_items_for_template( items) self.template_value['navbar'] = {'announcements': True} self.render('announcements.html')
def get(self): """Handles GET request.""" user = self.personalize_page_and_get_user() if not user: self.redirect( users.create_login_url(self.request.uri), normalize=False) return student = Student.get_enrolled_student_by_email(user.email()) if student: self.redirect('/course') return can_register = self.app_context.get_environ( )['reg_form']['can_register'] if not can_register: self.redirect('/course#registration_closed') return # pre-fill nick name from the profile if available self.template_value['current_name'] = '' profile = StudentProfileDAO.get_profile_by_user_id(user.user_id()) if profile and profile.nick_name: self.template_value['current_name'] = profile.nick_name self.template_value['navbar'] = {} self.template_value['transient_student'] = True self.template_value['register_xsrf_token'] = ( XsrfTokenManager.create_xsrf_token('register-post')) self.render('register.html')
def post(self): """ Handles a PayPal IPN post: https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNIntro/ """ import urllib from google.appengine.api import urlfetch parameters = None if self.request.POST: parameters = self.request.POST.copy() if self.request.GET: parameters = self.request.GET.copy() logging.debug('Received IPN message: ' + str(parameters)) # Check the IPN POST request came from real PayPal, not from a fraudster. if not parameters: return parameters['cmd'] = '_notify-validate' params = urllib.urlencode(parameters) status = urlfetch.fetch( url='https://www.sandbox.paypal.com/cgi-bin/webscr', method=urlfetch.POST, payload=params, ).content logging.debug('Verification status is: ' + status) if not status == "VERIFIED": logging.warning("Could not verify request: " + str(parameters) + ". Fraud?") #TODO: return an error message # Check funds go into the correct account if not parameters[ 'receiver_email'] == '*****@*****.**' and not parameters[ 'receiver_email'] == '*****@*****.**': logging.warning("Incorrect receiver email: " + parameters['receiver_email']) return if not parameters['mc_currency'] == 'CHF': logging.warning("Incorrect currency: " + parameters['mc_currency']) return student_email = parameters['custom'] # [hack] this handler will only work for the ns_sample namespace namespace_manager.set_namespace('ns_sample') # Check payment is completed, not Pending or Failed. if parameters['payment_status'] == 'Completed': student = Student.get_enrolled_student_by_email(student_email) #student = ( # models.StudentProfileDAO.get_enrolled_student_by_email_for( # student_email, self.app_context)) if not student: logging.warning('Could not process payment for student: ' + student_email) self.send_error_email(student_email) return logging.info( 'Student %s is now a full access student. Payment confirmed.' % student_email) student.has_paid = True student.access_code = 'PayPal' student.put()
def personalize_page_and_get_enrolled( self, supports_transient_student=False): """If the user is enrolled, add personalized fields to the navbar.""" user = self.personalize_page_and_get_user() if user is None: student = TRANSIENT_STUDENT else: student = Student.get_enrolled_student_by_email(user.email()) if not student: self.template_value['transient_student'] = True student = TRANSIENT_STUDENT if student.is_transient: if supports_transient_student and ( self.app_context.get_environ()['course']['browsable']): return TRANSIENT_STUDENT elif user is None: self.redirect( users.create_login_url(self.request.uri), normalize=False ) return None else: self.redirect('/preview') return None # Patch Student models which (for legacy reasons) do not have a user_id # attribute set. if not student.user_id: student.user_id = user.user_id() student.put() return student
def run(self): query = Student.all().filter('is_participant', True).run(limit=600) for student in query: yield { 'email': student.key().name(), 'group_id': student.group_id, }
def run(self): """Computes student statistics.""" enrollment = EnrollmentAggregator() scores = ScoresAggregator() student_scores = StudentAggregator() feedback = PostcourseAggregator() mapper = utils.QueryMapper( Student.all(), batch_size=500, report_every=1000) def map_fn(student): enrollment.visit(student) scores.visit(student) student_scores.visit(student) mapper.run(map_fn) mapper = utils.QueryMapper( StudentAnswersEntity.all(), batch_size=500, report_every=1000) def map_fn1(student): feedback.visit(student) mapper.run(map_fn1) data = { 'enrollment': { 'enrolled': enrollment.enrolled, 'unenrolled': enrollment.unenrolled}, 'scores': scores.name_to_tuple, 'students' : student_scores.name_to_tuple, 'feedback' : feedback.name_to_tuple} return data
def get(self): """Handles GET requests.""" user = self.personalize_page_and_get_user() transient_student = False if user is None: transient_student = True else: student = Student.get_enrolled_student_by_email(user.email()) if not student: transient_student = True else: #progress bar total_progress = (self.get_progress_tracker(). get_overall_progress_score(student)) self.template_value['progress_value'] = total_progress.get( 'progress_score', 0) self.template_value['complete_value'] = total_progress.get( 'completed_score', 0) self.template_value['percentage'] = total_progress.get( 'percentage', '') #student = self.personalize_page_and_get_enrolled( # supports_transient_student=True) self.template_value['transient_student'] = transient_student self.template_value['navbar'] = {'team': True} self.render('team.html')
def get(self): """Handles GET requests.""" user = users.get_current_user() if not user: self.template_value['loginUrl'] = ( users.create_login_url(self.request.uri)) # self.template_value['fedLoginUrl'] = ( # users.create_login_url(self.request.uri, None, 'http://dev-hidden.africanmanagers.org')) else: self.template_value['email'] = user.email() self.template_value['logoutUrl'] = ( users.create_logout_url(self.request.uri)) self.template_value['navbar'] = {'course': True} self.template_value['units'] = self.get_units() if user and Student.get_enrolled_student_by_email(user.email()): self.redirect('/course') else: self.template_value['enroll']=True; self.render('preview.html')
def get(self): param_map = {} for k in self.request.arguments(): param_map[k] = self.request.get(k) client_id = param_map.get('client_id', 0) logging.debug("vanilla request: " + str(param_map)) user = users.get_current_user() if Roles.is_course_admin(self.app_context): role= "administrator" else: role="member" logging.debug(str(user)) if user: student = Student.get_enrolled_student_by_email(user.email()) user = { "name": student.name, "email": user.email(), "uniqueid": user.user_id(), "photourl": "", } course = self.app_context.get_environ()['course'] client_id = course['VANILLA_CLIENT_ID'] secret_key = course['VANILLA_SECRET_KEY'] jsconn_str = get_jsconnect_string(user, param_map, client_id, secret_key) logging.debug("mooc-ed response: " + jsconn_str) self.response.out.write(jsconn_str)
def post(self): # Read in answers answer = json.dumps(self.request.POST.items()) assessment_type = self.request.get('assessment_type') num_correct = self.request.get('num_correct') num_questions = self.request.get('num_questions') # Check for enrollment status student = self.getStudent() if student: logging.info(student.key().name() + ':' + answer) # Find student entity and save answers student = Student.get_by_key_name(student.key().name().encode('utf8')) # FIXME: Currently the demonstration course is hardcoded to have # three assessments: 'precourse', 'midcourse', and 'postcourse'. # If you would like to have different types of assessments or # different score weights/thresholds, edit the code below ... if assessment_type == 'precourse': score = self.request.get('score') student.precourse_answer = answer student.precourse_score = int(float(score)) elif assessment_type == 'midcourse': score = self.request.get('score') student.midterm_answer = answer student.midterm_score = int(float(score)) elif assessment_type == 'postcourse': score = self.request.get('score') student.final_answer = answer student.final_score = int(float(score)) if not student.midterm_score: student.midterm_score = 0 student.overall_score = int((0.35 * student.midterm_score) + (0.65 * student.final_score)) self.templateValue['score'] = student.overall_score if student.overall_score >= 70: assessment_type = 'postcourse_pass' else: assessment_type = 'postcourse_fail' student.put() # Update student entity in memcache memcache.set(student.key().name(), student) # Set template values for nav-x bar navbar = {'course':True} self.templateValue['navbar'] = navbar # Set template values for user user = users.get_current_user() if user: self.templateValue['email'] = user.email() self.templateValue['logoutUrl'] = users.create_logout_url("/") # Render confirmation page self.templateValue['assessment'] = assessment_type self.render('test_confirmation.html') else: self.redirect('/register')
def get(self): param_map = {} for k in self.request.arguments(): param_map[k] = self.request.get(k) client_id = param_map.get('client_id', 0) logging.debug("vanilla request: " + str(param_map)) user = users.get_current_user() logging.debug(str(user)) if user: student = Student.get_enrolled_student_by_email(user.email()) user = { "name": student.name, "email": user.email(), "uniqueid": user.user_id(), "photourl": "", } course = self.app_context.get_environ()['course'] client_id = course['VANILLA_CLIENT_ID'] secret_key = course['VANILLA_SECRET_KEY'] jsconn_str = get_jsconnect_string(user, param_map, client_id, secret_key) logging.debug("mooc-ed response: " + jsconn_str) self.response.out.write(jsconn_str)
def run(self): query = StudentAnswersEntity.all().run(limit=600) for ans_ent in query: ans_dict = transforms.loads(ans_ent.data) for assessment, answers in ans_dict.iteritems(): student = Student.all().filter('user_id', ans_ent.key().name()).get() s_scores = transforms.loads(student.scores) d = { 'email': student.key().name(), 'assessment': assessment, 'score': s_scores.get(assessment, '?????? wtf'), } for answer in answers: k = 'q%d' % (answer['index'] + 1) if answer['correct']: d[k] = 'correct' else: if isinstance(answer['value'], int): d[k] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[ answer['value']] else: d[k] = '' yield d
def get_list(self): """Shows a list of announcements.""" user = self.personalize_page_and_get_user() transient_student = False if user is None: transient_student = True else: student = Student.get_enrolled_student_by_email(user.email()) if not student: transient_student = True else: # CGL-MOOC-Builder starts: # Set template value for progress bar that shows on the top navigation(header.html) total_progress = (self.get_progress_tracker().get_overall_progress_score(student)) self.template_value['progress_value'] = total_progress.get('progress_score', 0) self.template_value['complete_value'] = total_progress.get('completed_score', 0) self.template_value['percentage'] = total_progress.get('percentage', '') # CGL-MOOC-Builder ends self.template_value['transient_student'] = transient_student items = AnnouncementEntity.get_announcements() if not items and AnnouncementsRights.can_edit(self): items = self.put_sample_announcements() items = AnnouncementsRights.apply_rights(self, items) self.template_value['announcements'] = self.format_items_for_template( items) self.template_value['navbar'] = {'announcements': True} self.render('announcements.html')
def get_list(self): """Shows a list of announcements.""" student = None user = self.personalize_page_and_get_user() transient_student = False if user is None: transient_student = True else: student = Student.get_enrolled_student_by_email(user.email()) if not student: transient_student = True self.template_value['transient_student'] = transient_student items = AnnouncementEntity.get_announcements() items = AnnouncementsRights.apply_rights(self, items) if not roles.Roles.is_course_admin(self.get_course().app_context): items = models.LabelDAO.apply_course_track_labels_to_student_labels( self.get_course(), student, items) self.template_value['announcements'] = self.format_items_for_template( items) self.template_value['navbar'] = {'announcements': True} if student and len(items) > 0: additional_fields = transforms.nested_lists_as_string_to_dict( student.additional_fields) additional_fields[ 'annoucements_last_viewed'] = datetime.datetime.now().strftime( courses.ISO_8601_DATE_FORMAT) student.additional_fields = transforms.dict_to_nested_lists_as_string( additional_fields) student.put() self.template_value['force'] = self.request.get('force') self.render('announcements.html')
def update_simassessment_transaction(self, email, assessment_type, new_answers, score): """Stores answer and updates user scores. Args: email: the student's email address. assessment_type: the title of the assessment. new_answers: the latest set of answers supplied by the student. score: the numerical assessment score. Returns: the student instance. """ student = Student.get_enrolled_student_by_email(email) print student.is_transient course = self.get_course() # It may be that old Student entities don't have user_id set; fix it. if not student.user_id: student.user_id = self.get_user().user_id() answers = StudentAnswersEntity.get_by_key_name(student.user_id) if not answers: answers = StudentAnswersEntity(key_name=student.user_id) answers.updated_on = datetime.datetime.now() utils.set_answer(answers, assessment_type, new_answers) assessments.store_score(course, student, assessment_type, int(score)) student.put() answers.put()
def get_student_count(): count = generalcounter.get_count(PARTICIPANT_COUNT) if not count: count = Student.all(keys_only=True).filter("is_participant", True).count(limit=10000) generalcounter.increment(PARTICIPANT_COUNT, by=count) return count
def update_assessment_transaction(self, email, assessment_type, new_answers, score): """Stores answer and updates user scores.""" student = Student.get_by_email(email) # It may be that old Student entities don't have user_id set; fix it. if not student.user_id: student.user_id = self.get_user().user_id() answers = StudentAnswersEntity.get_by_key_name(student.user_id) if not answers: answers = StudentAnswersEntity(key_name=student.user_id) answers.updated_on = datetime.datetime.now() utils.set_answer(answers, assessment_type, new_answers) assessment_type = store_score(student, assessment_type, score) student.put() answers.put() # Also record the event, which is useful for tracking multiple # submissions and history. models.EventEntity.record( 'submit-assessment', self.get_user(), json.dumps({ 'type': 'assessment-%s' % assessment_type, 'values': new_answers, 'location': 'AnswerHandler' })) return (student, assessment_type)
def post(self): if not users.is_current_user_admin(): self.abort(403) if not XsrfTokenManager.is_xsrf_token_valid(self.request.POST.get('xsrf_token', ''), 'post'): self.abort(403, 'XSRF token failed.') form = self.Form(self.request.POST) if not form.validate(): self.response.write('<br>'.join(form.errors)) return student = Student.get_by_key_name(form.email.data) report = PartReport.on(student, course=self.get_course(), part=form.part.data, force_re_run=form.re_run.data, put=form.really_save.data) badge_version = choose_badge_version(part_config[form.part.data]['slug'], report.completion()) if badge_version: badge = Badge.get_by_key_name(badge_version) if not badge: self.response.write(' There is no badge with key_name %s (so I cannot issue a badge)' % badge_version) if form.really_save.data and badge: b = Badge.issue(badge, student, put=False) b.evidence = self.request.host_url + '/badges/evidence?id=%d' % report.key().id() b.put() self.response.write('Issued badge %s!' % badge_version) else: self.response.write('Would have issued badge %s!' % badge_version) else: self.response.write('Not issuing because at least one of: %s' % (', '.join(report.incomplete_reasons)))
def run(self): """Computes student statistics.""" enrollment = EnrollmentAggregator() scores = ScoresAggregator() names = NamesAggregator() mapper = utils.QueryMapper(Student.all(), batch_size=500, report_every=1000) def map_fn(student): enrollment.visit(student) scores.visit(student) names.visit(student) mapper.run(map_fn) data = { 'enrollment': { 'enrolled': enrollment.enrolled, 'unenrolled': enrollment.unenrolled }, 'scores': scores.name_to_tuple, 'id': names.st_id } return data
def name(self, email): name = self._names.get(email, None) if name: return name else: stud = Student.get_by_email(email) self._names[email] = stud.name return stud.name
def signup(self): form = SignupForm() if request.method == 'POST': if form.validate() == False: return render_template('signup.html', form=form) else: session['student'] = {} newStudent = Student() id = newStudent.add(form.name.data, form.email.data, form.password.data, form.phone.data) session['student']['id'] = id session['student']['name'] = form.name.data session['student']['email'] = form.email.data return redirect(url_for('select_interests')) return render_template('signup.html', form=form)