def __do_run(): """ Resume a suspended batch job if it exists, or create a new one if not. """ logging.info("Loading batch job") job = BatchJob.get_or_create() config = DeploymentConfig.get_instance() if not job.student_data_loaded: logging.info("Loading students to DB") load_students_to_db(config) job.student_data_loaded = True job.put() # The report generation step might take awhile for large data sets, # requeue here just in case to reset the task queue timer. # (Because of the sorting, it has to be completed atomically) queue() return if not job.reports_complete: logging.info("Generating reports") print_reports(config) job.reports_complete = True job.put() logging.info("Cleaning up temporary records") Student.delete_all() logging.info("Anonymizer run complete, terminating batch job") job.key.delete()
def delete(self, student_id=None): '''DELETE /students/{id} -> delete student with id=id ''' if student_id is not None: Student.get(id=student_id).delete() return {'message': 'Student has been deleted'} abort(404)
def delete(self, id): Student.delete(id) return { 'code': 200, 'message': 'Student data successfully deleted' }, 200
def example_simulation_one(self): engineering_classroom = ClassRoom("Principles", 34.069140, -118.442689) geology_classroom = ClassRoom("Sedimentary Petrology", 34.069585, -118.441878) psychology_classroom = ClassRoom("Introductory Psychobiology", 34.069742, 118.441312) music_classroom = ClassRoom("Art of Listening", 34.070223, -118.440193) humanities_classroom = ClassRoom("Art Hitory", 34.071528, -118.441211) class_rooms = [] class_rooms.append(humanities_classroom) class_rooms.append(geology_classroom) class_rooms.append(engineering_classroom) class_rooms.append(music_classroom) class_rooms.append(psychology_classroom) john_student = Student("John Wilson", 34.069149, -118.442639) jane_student = Student("Jane Graham", 34.069601, -118.441862) pam_student = Student("Pame Bam", 34.071513, -118.441181) pom_student = Student("Bam Bam", 34.071501, -118.441170) students = [] students.append(john_student) students.append(jane_student) students.append(pam_student) students.append(pom_student) self.print_clouster_students( self.student_clusters_in_classes(students, class_rooms))
def start_controller(): """ Contain main logic of controller, call functions to perform task choosen by user Raises: FileNotFoundError: if file to open is not present """ try: Student.read_users() except FileNotFoundError as err: view.print_msg(err) pass try: Mentor.read_users() except FileNotFoundError as err: view.print_msg(err) else: user_id = view.get_user_id() user_password = view.get_user_password() try: user = login_user(user_id, user_password) except ValueError as err: view.print_msg(err) else: if user.__class__.__name__ == "Student": student_controller.start_controller(user) elif user.__class__.__name__ == "Mentor": mentor_controller.start_controller(user)
def load_database(): ''' Initialize all objects stored in data/.. Close program if there is not enough database to function properly. Parameters, Returns: None Initialize: Student objs. Mentor objs. Employee objs. Manager objs. Assigments objs. Logins.list_of_logins ''' Assignment.get_assignments_from_file('assignments.csv') Attendance.get_attendance_from_file('attendance.csv') Student.get_codecoolers_from_file('students.csv') Employee.get_codecoolers_from_file('employees.csv') Mentor.get_codecoolers_from_file('mentors.csv') Manager.get_codecoolers_from_file('managers.csv') if len(Manager.list_of_managers) < 1 or len( Employee.list_of_employees) < 1: err_msg = 'There is no database stored. Contact our support at [email protected]' view.print_message(err_msg) sys.exit() Logins.from_codecoolers(Student.list_of_students, Employee.list_of_employees, Manager.list_of_managers, Mentor.list_of_mentors)
def initialize(): DATABASE.connect() DATABASE.create_tables([Classes, Student, Studentclass], safe=True) try: fake = Faker() for i in range(10): Student.create( name=fake.name(), email=fake.email(), age=20 ) except IntegrityError: pass try: Classes.create( title="Python", description="Learning the beautiful language" ) Classes.create( title="Javascript", description="Language of the web" ) except IntegrityError: pass DATABASE.close()
def test_add_students(self): # Add single student self.course1.add_students(Student('test1', 1)) self.assertEqual(len(self.course1.students), 1) # Add multiple students self.course1.add_students([Student('test2', 2), Student('test3', 3)]) self.assertEqual(len(self.course1.students), 3)
def __unstick(): """ DO NOT call this method directly, use queue_unstick() instead. """ logging.info("Clearing stuck batch job") logging.info("Wiping temporary records from student table") Student.delete_all() logging.info("Deleting batch job entity") BatchJob.get_or_create().key.delete() logging.info("Batch job cleared")
def setUp(self): self.student = Student('test1', 123) self.course1 = Course(1, 'test_course1') self.course2 = Course(2, 'test_course2') self.course3 = Course(3, 'test_course3') self.course4 = Course(4, 'test_course4') self.enrollment1 = Enrollment(self.student, self.course1) self.enrollment2 = Enrollment(self.student, self.course2) self.enrollment3 = Enrollment(self.student, self.course3)
def test_student_can_be_edited(self): """Test API can edit an existing student. (PUT request)""" res = self.studentService.create_user(self.student) self.assertEqual('stratege', res['username']) student = Student(self.student['username'], self.student['password'], self.student['fullname'], self.student['register']) student.username = "******" rv = self.studentService.update_user_by_id(res['id'], student) self.assertIn('otis', rv['username'])
def get(self, student_id=None): ''' GET /students/ -> get all students GET /students/{id}/ -> get student with id=id ''' if student_id is not None: return Student.get(id=student_id).json() or abort(404) else: return [student.json() for student in Student.get()]
def change_password(student): ''' Change old password to new. Args: student - object ''' codecooler_controller.change_password(student) Student.save_codecoolers_to_file('students.csv', Student.list_of_students)
def create_student(): Student.create(name="Valeria", lastname="Echevarría", address="Av. Vice #1084", gender="F", dni="49578120", phone="957831328", email="*****@*****.**") s = Student.get(Student.dni == "49578120") return s.name
def add_education(student_id): student = Student.by_id(student_id) edu = request.form.to_dict() education = Education(**edu) students = Student.objects(id=student_id) for student in students: student.education.append(education) return save_model(student) return "Not found", 404
def post(self): '''POST /students/ -> add a new student ''' data = StudentResource.parser.parse_args() student_name = data.get('name') student_age = data.get('age') student = Student(student_name, student_age) student.save() return student.json(), 201
def post(self): data = StudentsResource.parser.parse_args() student = Student(_id=None, name=data['name'], school_id=data['school_id']) student.save() return { 'code': 201, 'message': 'Student data created successfully' }, 201
def create(self): params = self.request.body validator=Validator(params,'create',StudentHandler.valid_model) if new_student_data: new_student=Student( name = new_student_data['name'], email = new_student_data['email'] ) new_student.put() self.response.write(json.dumps(new_student.dict())) else: self.response.write(json.dumps(validator.error_message()))
def students_registered_students(student): active_student = Student.select().where(Student.email**student).get() classes_ids = Studentclass.select().where( Studentclass.classes_id == active_classes.id) results = [] for classes_id in classes_ids: student = Student.select().where(Classes.id == classes_id).get() results.append({ 'description': classes.description, 'title': classes.title }) return jsonify(results)
def seedStudents(): students = [] for i in range(0,10): name = 'Student_%s' % i #grade = i * 12 email = str(i * 6) s = Student( name = name, email = email ) s.put() students.append(s) return students
def registerStudent(): form = RegisterStudentForm() if form.is_submitted(): student = Student(name=form.studentName.data, aggregate=form.aggregate.data, first_choice=form.first_choice.data, second_choice=form.second_choice.data, third_choice=form.third_choice.data, fourth_choice=form.fourth_choice.data) if contains(str(form.studentName.data), Student): flash('Student Exists', 'error') else: student.save() flash('Student Registered!', 'success') return render_template('studentpage.html', form=form, schools=getSchools())
def test_unstick(self): # Simulate a broken batch job with a database footprint create_stuck_batch_job() self.assertTrue(BatchJob.get()) self.assertTrue(Student.get_all_id_numbers()) # Queue and fire the unstick task driver.queue_unstick() tasks = self.taskqueue_stub.get_filtered_tasks() self.assertEqual(len(tasks), 1) result = deferred.run(tasks[0].payload) # Ensure relevant DB tables have been cleared self.assertFalse(BatchJob.get()) self.assertFalse(Student.get_all_id_numbers())
def get(self): token = self.get_argument("token") session = session_manager.get_session(token) student = self.db_session.query(Student).get(SESSION_DICT[token]["username"]) if student: self.write(student.to_dict()) else: student_info = get_student_info(session) student = Student(**student_info) try: self.db_session.add(student) self.db_session.commit() except: self.db_session.rollback() finally: self.write(student.to_dict())
def setUp(self): student = Student('test', 1) course = Course(1, 'test_course') datetime_format = '%Y-%m-%dT%H:%M:%SZ' assignment = Assignment(1, 'hw1', '2018-01-02T23:59:00Z', course, datetime_format) self.grade = Grade(student, course, assignment, 0.85)
def create_students(choice_list=None, choices={}): students = [] choice_list.readline() num_student = 0 for line in choice_list: cells = line.split(",") email = cells[1].strip("\"") last_name = cells[2].strip("\"") first_name = cells[3].strip("\"") students.append( Student(email=email, first_name=first_name, last_name=last_name)) # Add and create new choices student_choices = cells[4:] for i in range(len(student_choices)): choice = student_choices[i] # Strip newlines and quotes choice = choice[0:len(choice) - 1] if choice[len(choice) - 1] == '\n' else choice choice = choice[1:len(choice) - 1] students[num_student].add_choice(choice=choice, rank=i) if not choice in choices: choices[choice] = 0 num_student += 1 return students
def update(): student = Student.get_by_id(get_jwt_identity()) params = request.json if student: payment = Payment.get_by_id(params.get("payment_id")) payment.status = 'complete' payment.status_timestamp = datetime.now() if payment.save(): responseObject = ( { "message" : "Payment received." , "status" : "success!", "payment" : { "id" : payment.id, "amount" : payment.amount, "status" : payment.status, "status_timestamp" : payment.status_timestamp, "student_tutor_session" : payment.student_tutor_session_id } } ) return make_response(jsonify(responseObject)), 200 else: return make_response(jsonify([err for err in payment.errors])), 400
def _load_fake_data(session: Session): lessons_names = ['Математика', 'Программирование', 'Философствуем за кружечкой пенного', 'Алгоритмы и структуры данных', 'Линейная алгебра', 'Мат. статистика', 'Физкультура'] group1 = Group(group_name='1-МДА-7') group2 = Group(group_name='1-МДА-9') session.add(group1) session.add(group2) for key, it in enumerate(lessons_names): lesson = Lesson(lesson_title=it) lesson.groups.append(group1) if key % 2 == 0: lesson.groups.append(group2) session.add(lesson) faker = Faker('ru_RU') group_list = [group1, group2] session.commit() for _ in range(50): full_name = faker.name().split(' ') age = faker.random.randint(16, 25) address = faker.address() group = faker.random.choice(group_list) student = Student(full_name, age, address, group.id) session.add(student) session.commit() session.close()
def import_student(file): student_data = pd.read_excel(file, engine="openpyxl") # read excel student_data.fillna("", inplace=True) student_data = student_data.to_dict() number_of_students = len(list(student_data.values())[0]) key_list = [] for key in student_data: key_list.append(key) students = [] for j in range(number_of_students): s = Student( username=student_data[key_list[0]][j], password="******", full_name=student_data[key_list[1]][j], gender=student_data[key_list[2]][j], enrollment_type=student_data[key_list[3]][j], year_of_enrollment=student_data[key_list[4]][j], sc_status=student_data[key_list[5]][j], pr_status=student_data[key_list[6]][j], nationality=student_data[key_list[7]][j], phone_number=student_data[key_list[8]][j], email_sutd=student_data[key_list[9]][j], email_personal=student_data[key_list[10]][j], local_addr_post_code=student_data[key_list[11]][j], local_addr_street=student_data[key_list[12]][j], local_addr_unit=student_data[key_list[13]][j], ) students.append(s) return students
def from_json(cls, json_map): if type(json_map) is str: json_map = json.loads(json_map) c = cls(Student.from_json(json_map["student"]), Book.from_json(json_map["book"]), json_map["created_at"], json_map["redeemed"], json_map["redemption_key"]) return c
def new(): student = Student.get_by_id(get_jwt_identity()) params = request.json if student: student_tutor_session = Student_tutor_session.get_by_id(params.get("student_tutor_session")) tutor_session = Tutor_session.get_by_id(student_tutor_session.tutor_session_id) # duration = tutor_session.duration # amount = tutor_session.price * duration # price per hour * hrs amount = tutor_session.price new_payment = Payment( student_tutor_session_id = student_tutor_session.id, amount = amount, status = 'complete', status_timestamp = datetime.now() ) if new_payment.save(): responseObject = ( { "message" : "Payment completed." , "status" : "success!", "payment" : { "id" : new_payment.id, "amount" : new_payment.amount, "status" : new_payment.status, "status_timestamp" : new_payment.status_timestamp, "student_tutor_session" : new_payment.student_tutor_session_id } } ) return make_response(jsonify(responseObject)), 201 else: return make_response(jsonify([err for err in new_payment.errors])), 400
def save_student_masterdata(): body = request.get_json() if body['student'] is None or body['student']['student_id'] is None: res = CustomResponse(Status.ERR_GLOBAL_MISSING_PARAMETERS.value, None) return res.getres( ), Status.ERR_GLOBAL_MISSING_PARAMETERS.value['http']['status'] student_fromdb = Student.objects(student_id=body['student']['student_id']) if student_fromdb is not None and len(student_fromdb) > 0: res = CustomResponse(Status.USER_ALREADY_EXISTS.value, None) return res.getres(), Status.USER_ALREADY_EXISTS.value['http']['status'] else: student = Student(student_id=body['student']['student_id'], student_name=body['student']['student_name']) student.save() res = CustomResponse(Status.SUCCESS.value, None) return res.getres()
def delete(self,student_id): validator = Validator(student_id,'delete',StudentHandler.valid_model) student = Student.get_by_id(int(student_id)) if student: student.key.delete() self.response.write(json.dumps(validator.success_message())) else: self.response.write(json.dumps(validator.error_message()))
def show(self,student_id): student = Student.get_by_id(int(student_id)) if student: self.response.write(json.dumps(student.dict())) else: """ Interesting thing here is validator doesn't really need to be called... """ validator = Validator(student_id,"show",StudentHandler.valid_model) self.response.write(json.dumps(validator.error_message()))
def me(): student = Student.get_by_id(get_jwt_identity()) if student: student_data = model_to_dict(student) return make_response(jsonify(student_data)), 200 else: return abort(404)
def new_user(): encripted_passwd = bytes(req.form['password'], encoding='utf-8') s = Student(username=req.form['username'], name=req.form['name'], birthday=req.form['birthday'], password=bcrypt.hashpw(encripted_passwd, bcrypt.gensalt())) StudentDao(db).sign_up(s) return redirect(url_for('login'))
def find_by_username(self, username): self.__db.cur.execute(SIGN_IN, username) student = self.__db.cur.fetchone() if student != None: id, username, name, birthday, password = student return Student(id=id, username=username, name=name, birthday=birthday, password=password) else: return None
def load_students_to_db(config): """ Students are saved to the DB as we go -- we load a batch from the input file, convert them to students, perform cleanup, then pass them to the exporter. Any students that already existed in the DB when the task started are ignored -- this allows us to make forward progress even if the task times out during import. There's a minor chance of data leakage if the task terminates while the unique visitors are still processing a student. That won't cause issues though -- when the job resumes, that student will receive a fresh unique ID and the "zombie" record will simply be an unused number with no database footprint. """ if config.estimated_student_count == STUDENT_COUNT_NOT_INITIALIZED: logging.info("Initializing student count") initialize_student_count(config) importer = ImporterFactory.get(config) exporter = AsyncNdbExporter.get_or_create(config) visitors = VisitorFactory.get_cleanup_visitors(config) existing_sids = Student.get_all_id_numbers() if len(existing_sids) > 0: logging.info("{} students already loaded, the importer will skip those records".format( len(existing_sids))) for student_batch in importer.generate_multi(): # First, check if the student is already in the datastore (this means they've # already been cleaned up and are ready for export). # Then load their data from the stored cache (creating a fresh csd object if # this is a new student). students_not_in_db = [stu for stu in student_batch if stu.sid not in existing_sids] cached_student_data = CachedStudentData.get_or_create_multi( [stu.sid for stu in students_not_in_db]) for student in students_not_in_db: student.copy_from_cache(cached_student_data[student.sid]) # Now perform data cleanup and (when done) save the students to DB for i in visitors: i.accept_multi(students_not_in_db) for student in [stu for stu in students_not_in_db if stu.cache_is_dirty]: cache = cached_student_data[student.sid] student.copy_to_cache(cache) exporter.append(cache) for student in students_not_in_db: student.cleanup_complete = True exporter.append(student) # Manual flush after each batch instead of at the end of the run; the # uniquifier will also be dumping entities into the exporter, so we need # to make sure that everything's been committed before starting a fresh # batch (those entities are only cached within the scope of an # accept_multi run) exporter.flush() for i in visitors: i.close() logging.info("Filter results: {} accepted, {} rejected".format( importer.import_count(), importer.reject_count())) logging.info("All students loaded to database")
def create_or_edit_student(self, id): if id: student = Student.get_by_id(long(id)) if not student: self.redirect("/aluno/" + id) return else: student = Student() try: r = self.request first_contact = datetime.datetime.strptime(r.get("first_contact"), "%d/%m/%Y").date() student.populate( name=r.get("name"), surname=r.get("surname"), first_contact=first_contact, telephone=r.get("telephone"), email=r.get("email"), ) student.put() m = messages.STUDENT_UPDATE_SUCCESS if id else messages.STUDENT_CREATE_SUCCESS self.redirect("/aluno/" + str(student.key.id()) + "?" + urllib.urlencode({"m": m})) except ValueError as ex: logging.warning("ValueError: " + ex.message) m = messages.STUDENT_UPDATE_ERROR if id else messages.STUDENT_CREATE_ERROR self.redirect("/aluno/?" + urllib.urlencode({"m": m}))
def generate(self, multi): #pylint: disable=no-self-use for shard in StudentShard.linear_shard_generator(): batch = Student.query(ancestor=shard.key).fetch() if multi: self.imported += len(batch) yield batch else: for student in batch: self.imported += 1 yield student
def update(self,student_id): student = Student.get_by_id(int(student_id)) params = self.request.body validator=Validator(params,'update',StudentHandler.valid_model) student_update_data = validator.good_update_request() if student and student_update_data: if 'name' in student_update_data.keys(): student.name = student_update_data['name'] if 'email' in student_update_data.keys(): student.email = student_update_data['email'] student.put() self.response.write(json.dumps(student.dict())) else: self.response.write(json.dumps(validator.error_message()))
def test_student_put(self): # Ensure empty starting DB result = Student().query().fetch(limit=None) self.assertFalse(result) # Test basic db put stu1 = get_dummy_student(1) stu1.put() result = Student().query().fetch(limit=None) self.assertEqual(1, len(result)) # Test get_all and delete_all stu2 = get_dummy_student(2) stu3 = get_dummy_student(3) stu4 = get_dummy_student(4) stu2.put() stu3.put() stu4.put() id_set1 = Student.get_all_id_numbers() id_set2 = set(get_dummy_ids()) self.assertEqual(id_set1, id_set2) Student.delete_all() result = Student().query().fetch(limit=None) self.assertFalse(result) # Same as above, with circular sharding setup_dummy_students("circular") id_set1 = Student.get_all_id_numbers() id_set2 = set(get_dummy_ids()) self.assertEqual(id_set1, id_set2) Student.delete_all() result = Student().query().fetch(limit=None) self.assertFalse(result) # Same as above, with linear sharding setup_dummy_students("linear") id_set1 = Student.get_all_id_numbers() id_set2 = set(get_dummy_ids()) self.assertEqual(id_set1, id_set2) Student.delete_all() result = Student().query().fetch(limit=None) self.assertFalse(result)
def test_sharded_student_importer(self): dummy_count = self.config.estimated_student_count self.write_stub_student_file(dummy_count) exp = AsyncNdbExporter(dummy_count) # Prep work: load student stubs to database with sharding enabled imp = StubCsvImporter(self.config, use_shards=True) for stu in imp.generate_single(): exp.append(stu) exp.flush() self.assertEqual(dummy_count, len(Student.get_all_id_numbers())) imp = ShardedStudentImporter() self.check_importer_count(dummy_count, imp, multi=True) imp = ShardedStudentImporter() self.check_importer_count(dummy_count, imp, multi=False)
def create(self): params = self.request.body validator = Validator(params, "create", GradeHandler.valid_model) new_grade_data = validator.good_create_request() if new_grade_data: # grade = Grade.create(new_grade_data) # if grade: # return ... new_grade = Grade(score=new_grade_data["score"]) s_key = new_grade_data.get("student_key") if s_key: student = Student.get_by_id(s_key) if student: new_grade.student = student.key new_grade.put() self.response.write(json.dumps(new_grade.dict())) else: self.response.write(json.dumps(validator.error_message()))
def get_dummy_student(version, shard_gen=None): inst = None fname = None lname = None school_num = None grade = None sid = None if version == 1: fname = "Janet" lname = "Bishop" school_num = "11" grade = "12" sid = "1" elif version == 2: fname = "Norma" lname = "Watkins" school_num = "1" grade = "12" sid = "2" elif version == 3: fname = "Angela" lname = "Hart" school_num = "5" grade = "6" sid = "3" elif version == 4: fname = "Nicholas" lname = "Dixon" school_num = "2" grade = "4" sid = "4" else: raise ValueError("Unsupported version: {}".format(version)) if shard_gen: shard = next(shard_gen) inst = Student(id=sid, parent=shard.key) else: inst = Student(id=sid) inst.fname = fname inst.lname = lname inst.school_num = school_num inst.grade = grade inst.sid = sid return inst
def get(self, eventId, guardianId): '''The visitor is not an authenticated guardian''' if not SubscriptionLoginHandler.isAuthenticatedGuardian(): self.redirect('/inschrijven/') return '''The guardian is not authorized to see the page with the given eventId/guardianId''' if not self.isAuthorized(eventId, guardianId): SubscriptionLoginHandler.redirectToSubscriptionPage(self) return '''The guardian is an authorized guardian, so show the form''' event = Event.get_by_id(int(eventId)) days = Day.gql("WHERE event = :1", event).fetch(999) guardian = Guardian.get_by_key_name(guardianId) notifications = [] templVal = { 'notifications': notifications } subscriptionDetailsList = SubscriptionDetails.gql("WHERE event = :1 AND guardian = :2", event, guardian).fetch(1, 0) if not subscriptionDetailsList: notifications.append('Pagina niet gevonden.') self.showError(templVal) return subscriptionDetails = subscriptionDetailsList[0] if subscriptionDetails and subscriptionDetails.requested: notifications.append('U kunt geen verzoeken meer indienen.') self.showError(templVal) return students = Student.gql("WHERE guardian = :1", guardian).fetch(999, 0) students_subjects = self.getStudentsSubjects(students) if event and guardian and students and days: templVal = { 'event': event, 'days': days, 'guardian': guardian, 'students': students_subjects } path = os.path.join(os.path.dirname(__file__), '../templates/subscription/subscription.html') self.response.out.write(template.render(path, templVal))
def convert_row(self, row, shard=None): if not row or len(row) < 2: raise NotAStudentError("Not a student record, possibly a title or summary line?\n{}".format(row)) sid = row[1].strip() if not sid: raise StudentIdError("SID is missing or blank for row: {}".format(row)) instance = None if shard: instance = Student(id=sid, parent=shard.key) else: instance = Student(id=sid) try: instance.fname = row[12].strip() instance.lname = row[13].strip() instance.school_num = row[0].strip() instance.grade = row[2].strip() instance.sid = sid return instance except IndexError: raise NotAStudentError("Not a student record, possibly a title or summary line?\n{}".format(row))
def deleteAll(): ndb.delete_multi(Assignment.query().fetch(keys_only=True)) ndb.delete_multi(Course.query().fetch(keys_only=True)) ndb.delete_multi(Grade.query().fetch(keys_only=True)) ndb.delete_multi(Student.query().fetch(keys_only=True))
from models.student import Student from models.course import Course data = {} if request.action == "list": data['ss'] = Student.find().limit(50).sort({'name': 1}) local.views.students(data) else: myStudent = Student.findOne(request.s__id, True) if request.action == "Delete": myStudent.remove() response.sendRedirectTemporary("/students") else: data['courses'] = Course.find().toArray() if request.action == "Save": Forms.fillInObject("s_", myStudent, request) if myStudent._new: myStudent._new = False myStudent.save() data['msg'] = "Saved" if request.action == "Add" and 'course_for' in request \ and 'score' in request: course_id = request.course_for
def post(self, eventId, guardianId): '''The visitor is not an authenticated guardian''' if not SubscriptionLoginHandler.isAuthenticatedGuardian(): self.redirect('/inschrijven/') return '''The guardian is not authorized to the given''' if not self.isAuthorized(eventId, guardianId): SubscriptionLoginHandler.redirectToSubscriptionPage(self) return event = Event.get_by_id(int(eventId)) days = Day.gql("WHERE event = :1", event).fetch(999) guardian = Guardian.get_by_key_name(guardianId) students = Student.gql("WHERE guardian = :1", guardian).fetch(999, 0) students_subjects = self.getStudentsSubjects(students) notifications = [] templVal = { 'event': event, 'days': days, 'guardian': guardian, 'students': students_subjects, 'notifications': notifications } if not (event and days and guardian and students): notifications.append('U probeert een onmogelijke bewerking uit te voeren.') self.showError(templVal) return subscriptionDetailsList = SubscriptionDetails.gql("WHERE event = :1 AND guardian = :2", event, guardian).fetch(1, 0) if not subscriptionDetailsList: notifications.append('Pagina niet gevonden.') self.showError(templVal) return subscriptionDetails = subscriptionDetailsList[0] if subscriptionDetails and subscriptionDetails.requested: notifications.append('U kunt geen verzoeken meer indienen.') self.showError(templVal) return studentKeys = [str(k.replace('subject_', '')) for k in self.request.arguments() if re.match("subject_.+", k)] requests = [] dayPrefs = [] for s in students[:]: if str(s.key().name()) not in studentKeys: students.remove(s) if not students: notifications.append('U kunt geen verzoek indienen als u geen enkel vak geselecteerd heeft. ') for student in students[:]: subjectCodes = [c for c in self.request.get_all("subject_" + str(student.key().name()))] subjects = Subject.get_by_key_name(subjectCodes) if len(subjectCodes) > 3: notifications.append('U kunt maximaal 3 vakken per leerling bespreken.') if len(subjectCodes) != len(subjects): notifications.append('U probeert een onmogelijke bewerking uit te voeren.') for subject in subjects: combination = Combination.gql("WHERE class_id = :1 AND subject = :2", student.class_id, subject).fetch(1,0)[0] if not combination: notifications.append('U probeert een onmogelijke bewerking uit te voeren.') self.showError(templVal) return request = Request() request.event = event request.guardian = guardian request.student = student request.combination = combination requests.append(request) '''Process timepreference''' timePref = TimePreference() timePref.event = event timePref.guardian = guardian timePref.preference = 0 if not (self.request.get('time_pref') and (int(self.request.get('time_pref')) in [0,1,2])): notifications.append('U moet een voorkeur voor tijd aangeven.') else: timePref.preference = int(self.request.get('time_pref')) '''Check if dates from the form match the dates from the event ''' dayKeys = [long(k.replace('date_', '')) for k in self.request.arguments() if re.match("date_.+", k)] dayKeysFromStore= [day.key().id() for day in days] daysOk = True for dayKey in dayKeys: if dayKey not in dayKeysFromStore: daysOk = False notifications.append('U probeert een onmogelijke bewerking uit te voeren.') self.showError(templVal) return '''Check if the daypreference are correct filled in''' dayPrefsList = [int(self.request.get(k)) for k in self.request.arguments() if re.match("date_.+", k)] dayPrefsList.sort() dayPrefsOk = True if dayPrefsList != [1,2,3]: dayPrefsOk = False notifications.append('U moet een eerste, een tweede en een derde voorkeur aangeven') '''Process daypreferences''' if daysOk and dayPrefsOk: for day in days: dayPref = DayPreference() dayPref.day = day dayPref.guardian = guardian dayPref.rank = int(self.request.get("date_" + str(day.key().id()))) dayPrefs.append(dayPref) if notifications: path = os.path.join(os.path.dirname(__file__), '../templates/subscription/subscription.html') self.response.out.write(template.render(path, templVal)) return '''Store the requests''' for request in requests: request.put() for dayPref in dayPrefs: dayPref.put() timePref.put() subscriptionDetails.requested = True subscriptionDetails.put() SubscriptionLogoutHandler.logoutGuardian() path = os.path.join(os.path.dirname(__file__), '../templates/subscription/subscription-success.html') self.response.out.write(template.render(path, templVal)) return
def index(self): students = Student.query() student_arr = [] for student in students: student_arr.append(student.dict()) self.response.write(json.dumps(student_arr))
from models.student import Student from models.course import Course from core.content.forms import Forms from _10gen import request, local, response data = {} action = request.get('action', None) if action == "list": data['ss'] = Student.find().limit(50).sort({'name': 1}) local.views.students(data) else: myStudent = Student.findOne(request.get("s__id", None), True) if action == "Delete": myStudent.remove() response.sendRedirectTemporary("/students") else: data['courses'] = Course.find().toArray() if action == "Save": Forms.fillInObject("s_", myStudent, request) if hasattr(myStudent, "_new"): myStudent._new = False myStudent.save() data['msg'] = "Saved"
def get(self): # Load all Guardians path = os.path.join(os.path.dirname(__file__), 'data/voogdouder.txt') my_file = open(path) fileReader = csv.reader(my_file, delimiter=";") for row in fileReader: new_guardian = Guardian(key_name=row[0].strip()) new_guardian.title=row[1].strip() new_guardian.initials=row[2].strip() new_guardian.preposition=row[3].strip() new_guardian.lastname=row[4].strip() new_guardian.streetname=row[6].strip() new_guardian.housenumber=row[7].strip() new_guardian.city=row[8].strip() new_guardian.postalcode=row[9].strip() new_guardian.email=row[12].strip() new_guardian.save() print "Guardian " + new_guardian.key().id_or_name() + " stored" # Load all Students path = os.path.join(os.path.dirname(__file__), 'data/leerlingen.txt') my_file = open(path) fileReader = csv.reader(my_file, delimiter=";") for row in fileReader: new_student = Student(key_name=row[0].strip()) new_student.firstname=row[1].strip() new_student.preposition=row[2].strip() new_student.lastname=row[3].strip() new_student.gender=row[4].strip() new_student.class_id=row[5].strip() new_student.guardian=Guardian.all().filter("__key__ >=", Key.from_path('Guardian', row[6].strip())).get() new_student.save() print "Student " + new_student.key().id_or_name() + " stored" # Load all Teachers path = os.path.join(os.path.dirname(__file__), 'data/docenten.txt') my_file = open(path) fileReader = csv.reader(my_file, delimiter=";") for row in fileReader: new_teacher = Teacher(key_name=row[0].strip()) new_teacher.name=row[1].strip() new_teacher.boxnumber=int(row[2].strip()) new_teacher.email=row[3].strip() new_teacher.save() print "Teacher " + new_teacher.key().id_or_name() + " stored" # Load all Subjects path = os.path.join(os.path.dirname(__file__), 'data/vakken.txt') my_file = open(path) fileReader = csv.reader(my_file, delimiter=";") for row in fileReader: new_subject = Subject(key_name=row[0].strip()) new_subject.name=row[1].strip() new_subject.save() print "Subject " + new_subject.key().id_or_name() + " stored" # Load all Students path = os.path.join(os.path.dirname(__file__), 'data/docent_vak.txt') my_file = open(path) fileReader = csv.reader(my_file, delimiter=";") for row in fileReader: new_combination = Combination() new_combination.class_id=row[0].strip() new_combination.subject=Subject.all().filter("__key__ >=", Key.from_path('Subject', row[1].strip())).get() new_combination.teacher=Teacher.all().filter("__key__ >=", Key.from_path('Teacher', row[2].strip())).get() new_combination.save() print "Combination " + str(new_combination.key().id_or_name()) + " stored" self.redirect("/fix")