class StudentDAO: studentTable = { "thong": Student("ST2", "Dinh Dat Thong", True, "18-09-1997"), "son": Student("ST3", "Nguyen Ngoc Son", False, "04-05-1996") } location = "database/studentTable" def createTable(self): # if file existed if Path(self.location).is_file(): return f = open(self.location, "wb") f.write(pickle.dumps(self.studentTable)) f.close() def readFromFile(self): f = open(self.location, "rb") table = pickle.loads(f.read()) return table def selectAll(self): return self.readFromFile() def selectOne(self, id): table = self.readFromFile() if id in table: student = table[id] return student return None
def get_students(): for i, row in enumerate(open('data/student_counts.csv')): data = row.rstrip().split(",") (district_name, county_name, total_count, shelter_count, sharing_count, unsheltered_count, motel_count, year) = data for i in range(int(shelter_count)-1): student = Student(county=county_name, living_situation="shelter", year=year) db.session.add(student) for i in range(int(sharing_count)-1): student = Student(county=county_name, living_situation="sharing", year=year) db.session.add(student) for i in range(int(unsheltered_count)-1): student = Student(county=county_name, living_situation="unsheltered", year=year) db.session.add(student) for i in range(int(motel_count)-1): student = Student(county=county_name, living_situation="motel", year=year) db.session.add(student) db.session.commit()
def post(self): subject=self.get_argument('subject') student=self.get_argument('student',default="") s=Subject.objects(id=ObjectId(subject)).first() if not s: return self.write({'err':'课题不存在'}) if s.professor.username!=self.current_user.username: return self.write({'err':'不是你的课题'}) if s.selected_by==[]: return self.write({'err':'不可改选上阶段选好的课题'}) # Clear previous approvement if s.applied_to: u=Student.objects(username=s.applied_to.username).first() u.applied_to=None u.save() s.applied_to=None if student: for u_embedded in s.selected_by: u=Student.objects(username=u_embedded.username).first() if u.username==student: # You are the one! s.applied_to=u u.applied_to=s u.save() s.save() self.write({})
def dels(): if request.method == "POST": student = Student(request.form['idn'], '', '', '', '', '') student.delete_student() return render_template('home.html') else: return render_template('delstudent.html')
def submit_all(): result = askquestion(title="Confirmation", message= "Do you want to process?") if result == "yes": person = Person() person.lname = input_lastname.get(1.0, "end-1c") person.fname = input_firstname.get(1.0, "end-1c") person.birthday = datetime.date(birthYear.get(), months.index(birthMonth.get()) + 1, birthDay.get()) person.nationality = selected_nationality.get() person.gender = selected_gender.get() person.streetNumber = str(input_houseNo.get(1.0, "end-1c")) + str(input_houseNo2.get(1.0, "end-1c")) person.streetname = input_street.get(1.0, "end-1c") person.city = input_city.get(1.0, "end-1c") person.postalCode = str(input_postal.get(1.0, "end-1c")) + str(input_postal2.get(1.0, "end-1c")) person.phone = input_phoneNumber.get(1.0, "end-1c") person.email = input_email.get(1.0, "end-1c") person.insert() student = Student() student.personID = person.personID student.studentID = int(input_studentID.get(1.0, "end-1c")) student.startYear = datetime.date(startYear.get(), 1, 1) student.enrolled = selected_study.get() counseler_index = counsellornames.index(selected_counsellor.get()) student.studyCouncelor = counsellors[counseler_index].teacherID student.insert() person.userName = (person.lname + str(student.studentID)) person.userPass = "******" person.update() ui.AdminWindowStudents.admin_window_students(window, return_function) #avoid circular import
def getStudent(self): global g_Database rows = g_Database.fetchAll('SELECT * FROM student WHERE personID=' + str(self.personID)) if (not len(rows)): return None student = Student() student.read_row(rows[0]) return student
def updates(): if request.method == "POST": student = Student(IDnum=request.form['idn'], firstName=request.form['fname'], middleName=request.form['mname'], lastName=request.form['lname'], Sex=request.form['sex'], Course=request.form['c']) student.update_student() return render_template('home.html') else: return render_template('updatestudent.html')
def get(self): name = self.request.get('name', "") if name != "": s_id = Student().get_student_id(name_to_search=name) classes = ClassRoom().get_students_in_class_by_name( id_to_search=s_id) print "I AM HERE " print s_id else: people = {} people['students'] = Student.query().fetch(10) people['instructors'] = Instructor.query().fetch(10) self.response.write([people])
def join(): content = request.get_json(silent=True) hashid = cgi.escape(content['hashid']) fullName = cgi.escape(content['username']) userId = request.cookies.get('remote_userid') if 'remote_userid' in request.cookies else generate_user_id() userColor = request.cookies.get('remote_usercolor') if 'remote_usercolor' in request.cookies else generate_color() resp = make_response(hashid) # Ensure course exists courseId = DEFAULT_COURSE_PREFIX + hashid course = ndb.Key('Course', courseId).get() # Add user to course key = courseId + userId user = Student.get_or_insert(key, courseId=courseId, studentId=userId, fullName=fullName, color=userColor) userInitials = user.initials user.put() if not user.opentokSessionId: opentok_sdk = OpenTok(OPENTOK_API_KEY, OPENTOK_API_SECRET) # use tokbox server to route media streams; # if you want to use p2p - change media_mode to MediaModes.relayed opentok_session = opentok_sdk.create_session(media_mode = MediaModes.routed) opentok_token = opentok_sdk.generate_token(opentok_session.session_id) user.opentokSessionId = opentok_session.session_id user.opentokToken = opentok_token user.put() teacher = Student.get_teacher_by_course(courseId) # Set user cookies (student role) auth = json.loads(request.cookies.get('remote_auth')) if 'remote_auth' in request.cookies else {} auth[hashid] = { 'role': 'Student', 'opentok_api_key': OPENTOK_API_KEY, 'opentok_session_id': user.opentokSessionId, 'opentok_token': user.opentokToken, 'teacher_session_id': teacher.opentokSessionId, 'teacher_token': teacher.opentokToken } resp.set_cookie('remote_userfullname', fullName) resp.set_cookie('remote_auth', json.dumps(auth)) resp.set_cookie('remote_userid', userId) resp.set_cookie('remote_usercolor', userColor) resp.set_cookie('remote_userinitials', userInitials) configChanged(courseId, 'config', 'users') return resp
def many_to_many_table_add_data(self): """ 多对多表新增 """ course_1 = Course(course_name='语文') course_2 = Course(course_name='数学') course_1.student_list = [ Student(student_name="张三"), Student(student_name="李四"), ] course_2.student_list = [ Student(student_name="王二") ] self.session.add_all([course_1, course_2]) self.session.commit()
def add_student(): """adds a new student to the db""" fname = request.form.get("fname").strip().capitalize() lname = request.form.get("lname").strip().capitalize() user_id = session["user_id"] birthdate = request.form.get("birthdate") phone_number = request.form.get("phone") photo = request.form.get("photo") if (fname is '') or (lname is '') or (phone_number is '') or (birthdate is ''): flash("Please complete all fields of the student profile.", category='danger') return redirect(f"/user_info/{user_id}") student = Student(fname=fname, lname=lname, user_id=user_id, birthdate=birthdate, phone_number=phone_number, photo=photo) db.session.add(student) db.session.commit() return redirect(f"/user_info/{user_id}")
async def getAllCousWS(): # 载入 Course # courses = [] # 初始化 SQL rs = await handler.getAllCouse() # 将结果 模型化并返回 res = [] if rs is not None: for i in rs: res.append(Course(**i)) # 将 course list 转变为 Cws list cous = [] for item in res: cous.append(CourseWithStudents(course=item, students=[])) # 载入 Students for item in cous: # 初始化 SQL rs = await handler.getStuGrade(item.course.cno) # 将结果 模型化并返回 if rs is not None: for i in rs: item.students.append(Student(**i)) # 返回 Cws return cous
def add_student(name, year, finished_lab,methods=["GET","POST"]): """ """ if request.method=="GET": return render_template('student.html', student=query_by_id(student_id)) else: name=request.form["name"] year=request.form["year"] save_to_database(name,year) return render_template("home.html", n=name, y=year) student_object = Student( name=name, year=year, finished_lab=finished_lab) session.add(student_object) session.commit()
def delete(self): name = self.request.get('name', "") instructor = Instructor().get_instructor_by_name(name_to_search=name) student = Student().get_student_by_name(name_to_search=name) conf = "" print student if student == None and instructor == None: print("No Object was found. No action taken") conf = "No Object was found. No action taken" elif student != None: print("A Student object was found ") conf = Student().delete_student(student) elif instructor != None: print("An Instructor object was found: " + instructor.key) conf = Instructor().delete_instructor(instructor.key) self.response.write(conf)
def student_create(): if request.method == "GET": return render_template('student_create.html') elif request.method == "POST": student = Student( first_name=request.form['first_name'], last_name=request.form['last_name'], alias=request.form['alias'], grad_year=request.form['grad_year'], email=request.form['email'], ) student.save() if "create_and_add" in request.form: return render_template('student_create.html') elif "create" in request.form: return redirect(url_for('student_view', student_pk=student.pk))
def extract_student_fromSIS_fordb(): """extract student info from SIS and add to StepUp DB table, Student""" student = request.args.get('student') (firstname, lastname) = student.split(" ") #test with this info and then add all other student info for model query = """ SELECT student_number, last_name, first_name, dob, schoolID FROM students where first_name='""" + (firstname) + """ 'AND last_name='""" + ( lastname) + """'""" query_results = c.execute(query) #results = pd.read_sql(query,con) df = pd.DataFrame(results) #display student name, dob and school id for user to select #onclick, add to #need to unpack df results to get info to look for student in Student table student = Student.query.filter_by(student_number=student_number, dob=dob) #need to unpack results to get info to add student if not student: student = Student(student_number=student_number, stu_fname=first_name, stu_lname=last_name, dob=dob, schoolid=schoolID) db.session.add(student) db.session.commit() return (results.to_json(orient='records'))
def get_current_user(): """Returns an object of Student or Teacher class, whose credentials are currently saved in session.""" if session['logged_in']: if session['type'] == 'S': return Student.get(Student.username == session['username']) elif session['type'] == 'T': return Teacher.get(Teacher.username == session['username'])
def example_data(): """creates sample data for testing""" # Add sample data test_user = User(user_name="test_user", password="******", user_id=1) db.session.add(test_user) test_student = Student(fname="test", lname="student", birthdate=datetime(2000, 9, 7), phone_number="3132589798", user_id=test_user.user_id, student_id=1) db.session.add(test_student) test_behavior = Behavior(behavior_name="test_behavior", behavior_description="tests stuff", behavior_id=1) db.session.add(test_behavior) test_intervention = Intervention(intervention_name="test_intervention", intervention_id=1) db.session.add(test_intervention) test_progress = Progress(student_id=test_student.student_id, behavior_id=test_behavior.behavior_id, intervention_id=test_intervention.intervention_id, date=datetime(2018, 8, 30), rating="5", comment="test comment", user_id=test_user.user_id) db.session.add(test_progress) # db.session.add_all([test_user, test_student, test_behavior, test_intervention, test_progress]) db.session.commit()
def teacher_add_student(class_id): """Teacher adds student.""" fname = request.form["fname"] lname = request.form["lname"] username = fname[0].lower() + lname.lower() password = '******' #Create new student object new_student = Student(username=username, password=password, fname=fname, lname=lname, class_id=class_id) #Add to database and commit db.session.add(new_student) db.session.commit() #Flash registration confirmation, log student in, and redirect to student profile flash("Student {} {} added.".format(fname, lname)) flash("Student username = {}, password = password".format(username)) flash( "Please tell student to change their password the first time they log in." ) return redirect("/classes")
def public_gradebook(): students = Student.all(order='alias') assignments = [a for a in Assignment.all() if a.is_public] for student in students: # Set the grades following the order specified by assignment_pks grades = student.get_grades() grades_by_assignment_pk = dict([(g.assignment_pk, g) for g in grades]) student.points_by_assignment_pk = {} for assignment in assignments: grade = grades_by_assignment_pk.get(assignment.pk) if grade: grade.assignment = assignment points = grade.points if grade else 0 student.points_by_assignment_pk[assignment.pk] = points student.grades = grades student.has_comments = any((grade.comment for grade in grades)) now = datetime.now() return render_template( "public_gradebook.html", assignments=assignments, students=students, now=now )
def delete(): try: no = int(raw_input("输入学员编号:")) except TypeError: print '编号类型错误' delete() try: student = Student() student.id = no result = manager.delete(student) if result: print '删除[%s]成功' % no except KeyError: print '编号不存在' delete()
def student_delete(student_pk): student = Student.get(pk=student_pk) if request.method == 'GET': return render_template('student_delete.html', student=student) if request.method == 'POST': student.delete() return redirect(url_for('students'))
def post(self): subject=self.get_argument('subject') student=self.get_argument('student') s=Subject.objects(id=ObjectId(subject)).first() if not s: return self.write({'err':'课题不存在'}) if s.applied_to: return self.write({'err':'课题已被分配给'+s.applied_to.realname.encode('utf-8')}) u=Student.objects(username=student).first() if not u: return self.write({'err':'学生不存在'}) if u.applied_to: return self.write({'err':'学生已被分配'+u.applied_to.name.encode('utf-8')+'课题'}) # Match Straightly s.selected_by=[] s.applied_to=u u.selected=None u.applied_to=s s.save() u.save() self.write({})
def add_student(name, year): student_object = Student( name=name, year=year) #finished_lab=finished_lab) session.add(student_object) session.commit()
def load_students(): """load fake students into the database""" fake = Faker() # this is a file of random pics from the random image generator API json_string = open("random_pics.json").read() pic_dict = json.loads(json_string) for student in range(500): fname = fake.first_name() lname = fake.last_name() birthdate = fake.date_of_birth(tzinfo=None, minimum_age=5, maximum_age=18) user_id = random.randint(1, 20) phone_number = '3132589798' # this loads a random pic from the file to assign as a student image. pic = random.choice(pic_dict['results']) photo = pic['picture']['thumbnail'] del pic # photo = '/static/images/cage.jpg' student = Student(fname=fname, lname=lname, birthdate=birthdate, phone_number=phone_number, photo=photo, user_id=user_id) db.session.add(student) db.session.commit()
def create(): if request.method == 'POST': content = request.get_json(silent=True) fullName = cgi.escape(content['username']) className = cgi.escape(content['classname']) hashids = Hashids(salt=settings.HASHID_SALT,min_length=6) increment() count = get_count() hashid = hashids.encode(count) courseId = DEFAULT_COURSE_PREFIX + hashid userId = request.cookies.get('remote_userid') if 'remote_userid' in request.cookies else generate_user_id() userColor = request.cookies.get('remote_usercolor') if 'remote_usercolor' in request.cookies else generate_color() host = app.config.get('host') resp = make_response(hashid) # Add course to database key = courseId course = Course.get_or_insert(key, courseId=courseId, teacherName=fullName) course.put() # Add teacher to course # Create OpenTok session opentok_sdk = OpenTok(OPENTOK_API_KEY, OPENTOK_API_SECRET) # use tokbox server to route media streams; # if you want to use p2p - change media_mode to MediaModes.relayed opentok_session = opentok_sdk.create_session(media_mode = MediaModes.routed) opentok_token = opentok_sdk.generate_token(opentok_session.session_id) key = courseId + userId user = Student.get_or_insert(key, courseId = courseId, studentId = userId, fullName = fullName, color = userColor, role = 'TEACHER', opentokSessionId = opentok_session.session_id, opentokToken = opentok_token ) user.put() # Set user cookies (teacher role) auth = json.loads(request.cookies.get('remote_auth')) if 'remote_auth' in request.cookies else {} auth[hashid] = { 'role': 'Instructor', 'opentok_api_key': OPENTOK_API_KEY, 'opentok_session_id': user.opentokSessionId, 'opentok_token': user.opentokToken } resp.set_cookie('remote_userfullname', fullName) resp.set_cookie('remote_auth', json.dumps(auth)) resp.set_cookie('remote_userid', userId) resp.set_cookie('remote_usercolor', userColor) #resp.set_cookie('remote_userinitials', userInitials) return resp return redirect('/main#/create')
def clear_lesson(self, lesson, write_response=True): from model import Student, StudentActivity from google.appengine.ext import db db.delete(StudentActivity.fetch_all("lesson =", lesson)) db.delete(Student.fetch_all("lesson =", lesson)) self.log_out_all_students(lesson, False); if write_response: self.write_response_plain_text("OK")
def add_new_user(bot, update, user_data): '''Логин студента приходит в update message text''' new_user = update.message.text # TODO: Проверка, что такого пользователя нет new_student = Student(username=new_user, role='student') user_data['teacher1'].append( new_user) # Добавляем нового ученика в user_data db_session.add(new_user) # Добавляем студента в базу
def add_student_to_db(student_details): if student_details: row = Student(name=student_details['name'], age=student_details['age'], gender=student_details['gender']) session.add(row) session.commit() return 'Data added succcessfully'
def get(self): file = open('header.html') self.response.write(file.read()) std_all = Student.query() values = {"std_info":std_all} template = JINJA_ENVIRONMENT.get_template('viewstd.html') html = template.render(values) self.response.write(html)
def post(self): class_found = False # Grab all the properties that are accepted via the API name = self.request.get('name', "") role = self.request.get('role', "student") class_name = self.request.get('class', "") # We first check to see if we are adding an Instructor or Student class_room_name = ClassRoom().get_class_by_name( name_to_search=class_name) if class_room_name != None: class_found = True class_room = class_room_name.key.get() if role == "instructor": instructor = Instructor().get_instructor_by_name( name_to_search=name) if instructor != None: print("Instructor Found") instructor_key = instructor.key else: new_instructor = Instructor(name=name) instructor = new_instructor.put() instructor_key = instructor if class_found: class_room.instructors.append(instructor_key) print("Class Already Exists and adding", instructor_key) else: class_room = ClassRoom(name=class_name, instructors=[instructor_key]) elif role == "student": student = Student().get_student_by_name(name_to_search=name) if student != None: print("Student Found") else: new_student = Student(name=name) student = new_student.put() student_key = student if class_found: class_room.students.append(student_key) print("Class " + "Already Exists and adding", student_key, class_room) else: class_room = ClassRoom(name=class_name, students=[student_key]) print("This is a new ClassRoom") class_room.put() self.redirect('/people')
def generateStudent(): person = generatePerson() student = Student() student.startYear = datetime.date(random.randint(2012, 2024), 1, 1) student.studyCouncelor = random.choice(counselers).teacherID student.enrolled = random.choice(studies).studyname student.personID = person.personID student.insert() person.userName = (person.lname + str(student.studentID)) person.userPass = "******" person.update() for course in random.sample(courses, 4): student.enrollInCourse(course.courseID) return student
def add_student(name, year, finished_lab): """ Add a student to the database, given their name, year, and whether they have finished the lab. """ student_object = Student(name=name, year=year, finished_lab=finished_lab) session.add(student_object) session.commit()
async def getAllStu(): rs = await handler.getAllStudent() # 将结果 模型化并返回 res = [] if rs is not None: for i in rs: res.append(Student(**i)) return res
def assignment_view(assignment_pk): assignment = Assignment.get(pk=assignment_pk) students = Student.all() grades = assignment.get_grades() g_by_student_pk = dict([(g.student_pk, g) for g in grades]) for s in students: s.grade = g_by_student_pk.get(s.pk) return render_template('assignment_view.html', assignment=assignment, students=students)
def assignment_view(assignment_pk): assignment = Assignment.get(pk=assignment_pk) students = Student.all() grades = assignment.get_grades() g_by_student_pk = dict([(g.student_pk, g) for g in grades]) for s in students: s.grade = g_by_student_pk.get(s.pk) return render_template( 'assignment_view.html', assignment=assignment, students=students )
def get(self): from model import Student import datetime import settings students = tuple(Student.all().filter("latest_logout_timestamp =", None)) for student in students: if datetime.datetime.now() > student.latest_login_timestamp + settings.STUDENT_SESSION_TIMEOUT: student.log_out(True) from helpers import log log('=> LOGGED OUT {0} FROM LESSON {1} BECAUSE SESSION TIMED OUT'.format(student.nickname,student.lesson.lesson_code))
def add_grade_(): form = AddGradeForm() if form.validate_on_submit(): try: with db.transaction(): grade = Grade.create( student=Student.get(Student.username == form.student_select.data), subject=Subject.get(Subject.name == form.subject_select.data), teacher=get_current_user(), grade=form.grade.data ) except DatabaseError: flash('An error occurred while adding a grade') else: flash('Grade ' + str(grade.grade) + ' assigned to student ' + str(grade.student)) return redirect(url_for('groups', group=grade.student.username)) flash_errors(form) students = Student.select() subjects = Subject.select() return render_template('add_grade.html', students=students, subjects=subjects, form=form)
def student_update(student_pk): student = Student.get(pk=student_pk) if request.method == 'GET': return render_template('student_update.html', student=student) elif request.method == 'POST': student.first_name = request.form['first_name'] student.last_name = request.form['last_name'] student.alias = request.form['alias'] student.grad_year = request.form['grad_year'] student.email = request.form['email'] student.save() return redirect(url_for('student_view', student_pk=student_pk))
def assignment_grades_update(assignment_pk): assignment = Assignment.get(pk=assignment_pk) students = Student.all() grades = assignment.get_grades() # We decorate the student's with their grades. # Ideally, this would be done with a select_related type thing in the # model. At the SQL level. TODO g_by_student_pk = dict([(grade.student_pk, grade) for grade in grades]) for s in students: s.grade = g_by_student_pk.get(s.pk) if request.method == 'GET': return render_template( "assignment_grades_update.html", assignment=assignment, students=students ) # TODO: This POSt method seems cumbersome. Can it be fixed? if request.method == 'POST': for student in students: # These keys are first generated in the template as input tag # name attributes. points_key = "student_{0}_points".format(student.pk) comment_key = "student_{0}_comment".format(student.pk) try: points = request.form[points_key].strip() comment = request.form[comment_key].strip() except KeyError: # This will prevent a 400 status code from being returned if we # try to get data from the form about a student that didn't # exist when the form was created. continue try: points = int(points.strip()) except ValueError: points = None comment = comment.strip() if student.grade is None: student.grade = Grade( student_pk=student.pk, assignment_pk=assignment.pk, points=points, comment=comment ) else: student.grade.points = points student.grade.comment = comment student.grade.save() return redirect(url_for('assignment_view', assignment_pk=assignment_pk))
def gradebook(): students = Student.all() assignments = Assignment.all() assignment_pks = [a.pk for a in assignments] for student in students: # Set the grades following the order specified by assignment_pks grades = student.get_grades() by_assignment_pk = dict([(g.assignment_pk, g) for g in grades]) student.grades = [by_assignment_pk.get(pk) for pk in assignment_pks] return render_template( "gradebook.html", assignments=assignments, students=students )
def student_details(self): self.g_term = cherrypy.session.get('g_term') self.g_user = cherrypy.session.get('g_user') roles = ['admin'] self.page_for(roles) self.s_data = {} errors = {} s_data = {} if(self.g_term == ""): self.g_term = cherrypy.session.get('g_term'); sql = "SELECT s.*, u.user_name FROM Student s, User u WHERE \ s.user_id=u.user_id AND s.term='%s'" % (self.g_term) db = mysql.DB() results = db.do_query(sql) for row in results: tmp_row = {'user_id':row['user_id'], 'dept':row['dept'],'year':row['year'], 'term':row['term']} try: student = Student(**tmp_row) student.set_name(row['user_name']) s_data[student.user_id] = student except Invalid, e: errors = e.unpack_errors()
def log_out_all_students(self, lesson=None, write_response=True): assert self.is_teacher, "Must be logged in as teacher" if lesson is None: allLessonsForAllTeachers = self.request.get("which_lessons", "0") == "1" if allLessonsForAllTeachers: assert self.is_teacher and self.person.admin, "Must be admin to logout students from all lessons for all teachers." from model import Student if lesson is not None: students = tuple(Student.all().filter("lesson =", lesson)) elif allLessonsForAllTeachers: students = Student.all() else: students = tuple(Student.all().filter("teacher =", self.person)) for student in students: if student.is_logged_in or len(student.client_ids) > 0: from helpers import log log("Teacher logged out {0} from lesson {1}".format(student.nickname, student.lesson.lesson_code)) self.log_out_student(student, False) if write_response: self.write_response_plain_text("OK")
def get(self): self.load_search_party_context(user_type="teacher") try: if not self.is_teacher: raise NotAnAuthenticatedTeacherError() else: lesson = None form_item = lambda key:self.request.get(key, "").strip() if form_item is not None: lesson_code = form_item("lesson_code") if lesson_code != "": from model import Lesson lesson = Lesson.get_by_key_name(lesson_code) action = form_item("action") if action=="create": self.create_edit_lesson(form_item) elif action=="clone": self.clone_lesson(lesson) elif action=="edit": self.create_edit_lesson(form_item) elif action=="start": self.start_lesson(lesson) elif action=="stop": self.stop_lesson(lesson) elif action=="stopall": self.stop_all_lessons() elif action=="clear": self.clear_lesson(lesson) elif action=="delete": self.delete_lesson(lesson) elif action=="deleteall": self.delete_all_lessons() elif action=="logoutstudent": from model import Student student_nickname = form_item("student_nickname") student_key = "::".join((student_nickname, lesson_code)) student = Student.get_by_key_name(student_key) self.log_out_student(student) elif action=="logoutallstudents": self.log_out_all_students(lesson) else: self.show_dashboard() except NotAnAuthenticatedTeacherError: self.redirect_to_teacher_login()
def load_user(self): self.client_id = self.request.get('from', None) import client_id_utils self.person_type = client_id_utils.person_type_for_client_id(self.client_id) assert self.person_type in ("student", "teacher") self.person = None person_key = client_id_utils.person_key_for_client_id(self.client_id) if self.person_type == "teacher": from model import Teacher self.person = Teacher.get_by_key_name(person_key) else: from model import Student lesson_code = client_id_utils.lesson_code_for_client_id(self.client_id) student_key = "::".join((person_key, lesson_code)) self.person = Student.get_by_key_name(student_key) if self.person is None: from helpers import log log("***** ERROR: Person not found for client_id {0}".format(self.client_id))
def student_login_(): form = StudentLoginForm() if form.validate_on_submit(): try: student = Student.get(username=form.username.data) # adequate salt is stored in the password itself stored_password = student.password.encode('utf-8') password_to_check = form.password.data.encode('utf-8') password = hashpw(password_to_check, stored_password) if password != stored_password: raise WrongPassword('Wrong password') except WrongPassword: flash('Wrong password') except Student.DoesNotExist: flash('Wrong username or password') else: authorize_student(student) return redirect(url_for('student_profile')) flash_errors(form) return render_template('student_login.html', form=form)
def get(self): student=self.get_argument('student',"") u=Student.objects(username=student).first() if not u or not u.resume: raise HTTPError(404) # Guess browser and write Content-Disposition # FIXME: an ugly hack here due to a MongoEngine bug # must use `u.resume.name' for filename while write using `filename' # FIXME: filename will break on android with its internal browser e=quote(u.resume.name.encode('utf-8')).replace('+','%20') ua=self.request.headers['User-Agent'].lower() if "msie" in ua: cd='filename="%s"'%e elif "firefox" in ua: cd="filename*=UTF-8''%s"%e else: cd='filename="%s"'%u.resume.name self.set_header('Content-Disposition','attachment;'+cd) self.set_header('Content-Type','application/octet-stream') self.write(u.resume.read())
def _send_tab_delimited_report(self, lesson_code, utc_offset): import StringIO from model import Student, StudentActivity, Lesson import helpers encoding = "UTF-8" lesson = Lesson.get_by_key_name(lesson_code) assert lesson is not None if lesson is None or lesson.teacher_key != self.teacher_key: self.write_response_plain_text("ERROR: Lesson code appears to be incorrect.") else: students = Student.fetch_all("lesson =", lesson) task_titles = tuple(task_info[0] for task_info in lesson.tasks) student_key_to_nickname = dict((s.key().name(), s.nickname) for s in students) activities = StudentActivity.fetch_all("lesson =", lesson) report_buffer = StringIO.StringIO() excel_writer = UnicodeWriter(report_buffer, "excel-tab", "utf8") headers = ( # "Lesson_Code", "Timestamp", "Student", "Task_Number", "Task_Name", "Activity_Type", "Query", "Link_URL", "Link_Title", "Is_Helpful", "Answer_Text", "Answer_Explanation" ) excel_writer.writerow(headers) for activity in activities: student_key = activity.student_key.name() student_nickname = student_key_to_nickname[student_key] timestamp = (activity.timestamp - utc_offset).strftime("%m/%d/%Y %H:%M:%S") task_idx = activity.task_idx task_title = task_titles[task_idx] task_num = task_idx + 1 line_parts = ( # lesson_code, timestamp, student_nickname, task_num, task_title, activity.activity_type, activity.search, activity.link, activity.link_title, activity.is_helpful, activity.answer_text, activity.answer_explanation ) # line_parts = tuple(unicode(p).encode("utf8") for p in line_parts) excel_writer.writerow(line_parts) report_text = report_buffer.getvalue() report_buffer.close() content_type = "text/tab-separated-values" filename = "search_party_lesson_%s_activity_as_of_%s.txt"%(lesson_code, helpers.timestamp()) self.write_response_as_file(encoded_content=report_text, content_type=content_type, filename=filename, encoding=encoding)
def enrollNewStudent(params, reg, id): """ Generate a new 9th grade Freshman """ # generate cheasy names and student data skippable = params["skippable"] age = 14 if random.random() < params["lowAge"] else 15 lname = random.choice(randomNames) + ("s" if random.random() > 0.25 else "") s = Student(id, random.choice(randomNames), lname, age, 9) s.beginNewYear() s.enroll(reg.getCourse(name="PE")) enrolledCount = 1 if random.random() < params["band"]: s.enroll(reg.getCourse(name="Band")) enrolledCount += 1 req, opts = suggestClasses(reg, s, ignoreElectives=False) honorsChance = params["honors"] def asHonors(c): nonlocal honorsChance res = c.hasHonors and random.random() < honorsChance if res: honorsChance *= 1 + params["honorsCompound"] return res while enrolledCount < params["maxCourses"] and len(req) > 0: selected = req.pop() if selected.name in skippable: honorsResult = random.random() < honorsChance honorsChance *= (1 + params["honorsCompound"])**honorsResult if honorsResult: # give student credit for the course s.passed(selected, True, overrideHonors=True) selected = next(i for i in reg.getCoursesRequiring(selected) if i.canEnroll(s)) # enroll them in the next course s.enroll(selected, random.random() >= params["honorsFallOut"]) enrolledCount += 1 continue honorsResult = asHonors(selected) s.enroll(selected, honorsResult) enrolledCount += 1 while enrolledCount < params["maxCourses"] and len(opts) > 0: selected = opts.pop(randint(0, len(opts)-1)) # electives probably won't have honors versions, but just in case s.enroll(selected, asHonors(selected)) enrolledCount += 1 return s
def _attempt_to_identify_as_student(self): from model import Student from helpers import log # Initialize student # We still store changes to student record only, if any, but we don't want to store # the record needlessly, since that consumes billable resources. student = None student_is_dirty = False # There are two ways to identify a student: nickname + lesson code sent via CGI, # or the session ID. We will try them in that order. # Get CGI form values lesson_code = self.request.get("lesson_code", None) student_nickname = self.request.get("student_nickname", None) if lesson_code is not None and student_nickname is not None: # 1. Fetch student by nickname+lesson student_nickname = self.htmlunquote(student_nickname) key_name = Student.make_key_name(student_nickname=student_nickname, lesson_code=lesson_code) student = Student.get_by_key_name(key_name) log("=> SEARCHING BY NAME AND LESSON CODE: {0}, {1}, {2}".format(student_nickname, lesson_code, key_name)) if student is not None and self.session.sid != student.session_sid: if student.is_logged_in: # Prevent login if student already logged in to another session # GAE limits # of channels so we don't want to allow too many student windows from all_exceptions import StudentLoginException raise StudentLoginException( "Please choose another name. Someone is already logged in as %s." % (student_nickname.encode("ascii", "xmlcharrefreplace")), "Session ID doesn't match.", student.session_sid, self.session.sid, student.latest_login_timestamp, student.latest_logout_timestamp, ) # else: # # Need to update session id if student was logged into another browser previously (and then logged out) # student.session_sid = self.session.sid # student_is_dirty = True else: # 2. Fetch student by session id student = Student.all().filter("session_sid =", self.session.sid).get() log("=> SEARCHING FOR STUDENT BY SESSION ID {0}".format(self.session.sid)) if student is not None and not student.is_logged_in: # Passively log student in again. # At some point this student logged into this browser but logged out passively. from datetime import datetime student.latest_login_timestamp = datetime.now() student.latest_logout_timestamp = None student_is_dirty = True log("=> PASSIVE STUDENT LOGIN AFTER PASSIVE LOGOUT") if student_is_dirty: # Store changes to student record, if any. student.put() if student is not None and not student.is_logged_in: log("=> STUDENT IS **NOT** LOGGED IN") return student
def post(self): import json from model import Student, Lesson from all_exceptions import StudentLoginException from datetime import datetime from helpers import log try: self.load_search_party_context(user_type="student") # Get CGI form fields. lesson_code = self.request.get('lesson_code') student_nickname = self.request.get('student_nickname') ext = int(self.request.get('ext', 0)) # Normalize whitespace in student name. # Replace any string of >=1 whitespace with a single space (equivalent to s/\s+/ /g). student_nickname = " ".join(student_nickname.split()) if not lesson_code: # No lesson code raise StudentLoginException("Please enter a lesson code.", "lesson_code==%r"%lesson_code) # If no student nickname, generate an anonymous one anonymous = False if not student_nickname: import random, string alphabet = string.letters + string.digits anonymous_student = None for i in range(8): random_nickname = "".join(random.choice(alphabet) for i in range(10)) key_name = Student.make_key_name(student_nickname=random_nickname, lesson_code=lesson_code) anonymous_student = Student.get_by_key_name(key_name) if anonymous_student is None: student_nickname = random_nickname anonymous = True break if anonymous and not student_nickname: # No student name raise StudentLoginException("Could not login as anonymous student.", "student_nickname==%r"%student_nickname) # if not lesson_code and not student_nickname: # # Blank form # raise StudentLoginException("Please enter a lesson code and a student name.", # "lesson_code==%r, student_nickname==%r"%(lesson_code, student_nickname)) # elif not lesson_code: # # No lesson code # raise StudentLoginException("Please enter a lesson code.", # "lesson_code==%r"%lesson_code) # elif not student_nickname: # # No student name # raise StudentLoginException("Please enter a student name.", # "student_nickname==%r"%student_nickname) lesson = Lesson.get_by_key_name(lesson_code) # Retrieve lesson from DB # - If lesson does not exist, this will return None. # - If lesson existed but is disabled, it will return the lesson, but lesson.is_active will be False. # - If lesson existed but was deleted (hidden), it will return the lesson, but lesson.is_deleted will be True. # (Deleting lessons is done lazily. Actually, they are merely hidden from the teacher's view.) if lesson is None or lesson.is_deleted: # Lesson does not exist or was deleted (hidden). raise StudentLoginException("Please check the lesson code.", "lesson retrieved from datastore with lesson_code %r is None"%lesson_code) elif not lesson.is_active: # Lesson has been disabled by teacher. Students are not allowed to work on it anymore. raise StudentLoginException("This lesson is finished. You cannot work on it now.", "lesson_code %r has is_active=False"%lesson_code) # Fetch student from DB. # - Might return None if nobody has ever logged in with this nickname+lesson combination. key_name = Student.make_key_name(student_nickname=student_nickname, lesson_code=lesson_code) student = Student.get_by_key_name(key_name) login_timestamp = datetime.now() if student is not None: # Found the student. student.session_sid=self.session.sid student.latest_login_timestamp = login_timestamp student.latest_logout_timestamp = None if not student.first_login_timestamp: student.first_login_timestamp = login_timestamp else: student = Student( key_name=key_name, nickname=student_nickname, teacher=lesson.teacher_key, lesson=lesson, task_idx=self.INITIAL_TASK_IDX, first_login_timestamp=login_timestamp, latest_login_timestamp=login_timestamp, latest_logout_timestamp=None, session_sid=self.session.sid, anonymous=anonymous, client_ids=[] ) assert student.session_sid is not None student.put() self.set_person(student) displayName = "Anonymous" if self.is_student and self.person.anonymous else self.person.nickname self.session['msg'] = "Student logged in: Hello " + displayName self.response.headers.add_header('Content-Type', 'application/json', charset='utf-8') self.response.out.write(json.dumps({"status":"logged_in", "ext":ext})) log( "=> LOGIN SUCCESS" ) except StudentLoginException, e: e.log() self.set_person(None) msg = e.args[0] self.session['msg'] = msg self.response.headers.add_header('Content-Type', 'application/json', charset='utf-8') self.response.out.write(json.dumps({"status":"logged_out", "error":msg})) log( "=> LOGIN FAILURE: %s"%msg )
def make_student_structure(self, lesson, student=None): # If student is None, then this will return info for all students who # worked on this lesson. from model import Student, StudentActivity if student is not None: students = (student,) filter_key = "student =" filter_value = student else: students = tuple( Student.all().filter("lesson =", lesson) ) # PERFORMANCE: Generator might be inefficient filter_key = "lesson =" filter_value = lesson student_structure = {} if len(students) > 0: num_tasks = len(lesson.tasks) for student in students: tasks_info = [{"searches":[], "answer":{"text":"", "explanation":""}, "history":[]} for _ in range(num_tasks)] student_structure[student.nickname] = { "task_idx" : student.task_idx, "logged_in" : student.is_logged_in, "tasks" : tasks_info } # Policy: Don't report same (query,student,task_idx) more than once. # This dictionary enforces that. searches_dict = {} # (student_nickname,task_idx,link_url) -> ([link_info,...], is_helpful) link_infos_and_ratings = {} activities = StudentActivity.fetch_all(filter_key, filter_value) for activity in activities: student_nickname = activity.student.nickname task_idx = activity.task_idx activity_type = activity.activity_type if activity_type in (StudentActivity.ACTIVITY_TYPE_LINK, StudentActivity.ACTIVITY_TYPE_LINK_RATING, StudentActivity.ACTIVITY_TYPE_SEARCH): link_url = activity.link key = (student_nickname,task_idx,link_url) link_infos_and_rating = link_infos_and_ratings.setdefault(key, [[],None]) if activity_type in (StudentActivity.ACTIVITY_TYPE_LINK, StudentActivity.ACTIVITY_TYPE_SEARCH): query = activity.search search_key = (student_nickname, task_idx, query) try: search_info = searches_dict[search_key] except KeyError: search_info = {"query":query, "links_followed":[]} student_structure[student_nickname]["tasks"][task_idx]["searches"].append(search_info) searches_dict[search_key] = search_info if activity_type==StudentActivity.ACTIVITY_TYPE_LINK: link_title = activity.link_title link_info = {"url":link_url, "title":link_title, "is_helpful":None} search_info["links_followed"].append(link_info) link_infos_and_rating[0].append(link_info) elif activity_type==StudentActivity.ACTIVITY_TYPE_LINK_RATING: link_infos_and_rating[1] = activity.is_helpful elif activity_type==StudentActivity.ACTIVITY_TYPE_ANSWER: # This will end up with the most recent answer because it is in ascending time order, so # later answers will overwrite the older ones. answer_info = student_structure[student_nickname]["tasks"][task_idx]["answer"] answer_info["text"] = activity.answer_text answer_info["explanation"] = activity.answer_explanation student_structure[student_nickname]["tasks"][task_idx]["history"].append(activity) for k,v in link_infos_and_ratings.items(): (student_nickname,task_idx,link_url) = k link_infos, is_helpful = v for link_info in link_infos: link_info["is_helpful"] = is_helpful return student_structure
def student_view(student_pk): student = Student.get(pk=student_pk) return render_template("student_view.html", student=student)
def students(): students = Student.all() return render_template('student_list.html', students=students)
def groups_(): student_groups = Student.select(Student.group).distinct().order_by(Student.group.asc()) return render_template('groups.html', student_groups=student_groups)
def group_(): group_number = get_current_user().group students = Student.select().where(Student.group == group_number) return render_template('group.html', group=group_number, students=students)
def group_foreign_(group_number): students = Student.select().where(Student.group == group_number) return render_template('group.html', group=group_number, students=students)
def student_profile_foreign_(username): student = Student.get(Student.username == username) subjects = Subject.select() grades = Grade.select().where(Grade.student == student) return render_template('student_profile.html', student=student, subjects=subjects, grades=grades)