def post(self, request): response_data = {'retCode': error_constants.ERR_STATUS_SUCCESS[0], 'retMsg': error_constants.ERR_STATUS_SUCCESS[1]} try: section_id = int(request.POST.get('sectionId')) # faculty_id = int(request.POST.get('facultyId')) name = request.POST.get('name', '') mobile = request.POST.get('mobile', '') duty = request.POST.get('duty', '') channel = request.POST.get('channel', '') call_sign = request.POST.get('callSign', '') district_id = int(request.POST.get('districtId', 0)) # faculty_type 1 段长;2 执行段长 分局;3: 执行段长 交通;4:执行段长 武警 faculty_type = int(request.POST.get('facultyType')) except Exception as ex: print 'function name: ', __name__ print Exception, ":", ex return generate_error_response(error_constants.ERR_INVALID_PARAMETER, status.HTTP_400_BAD_REQUEST) cur_section = Section.objects.get(id=section_id) cur_faculty = Faculty.objects.filter(name=name, mobile=mobile) if cur_faculty.exists(): cur_faculty.update(enabled=True) cur_faculty = cur_faculty.first() else: cur_faculty = Faculty(name=name, mobile=mobile, duty=duty, main_name=cur_section.name, level=2, role=faculty_type, main_id=section_id, district_id=cur_section.district_id, channel=cur_section.channel, call_sign=cur_section.call_sign) # 岗位人数限制 count = check_faculty_count_particular_role(cur_faculty) if faculty_type == 1: count1 = cur_section.chief.filter(enabled=True).count() if faculty_type == 2: count1 = cur_section.exec_chief_sub_bureau.filter(enabled=True).count() if faculty_type == 3: count1 = cur_section.exec_chief_trans.filter(enabled=True).count() if faculty_type == 4: count1 = cur_section.exec_chief_armed_poli.filter(enabled=True).count() print 'section people_count:', count1 if count >= 4 or count1 >= 4: return generate_error_response(error_constants.ERR_FACULTY_EXCEED_COUNT, status.HTTP_400_BAD_REQUEST) else: try: with transaction.atomic(): cur_faculty.save() except Exception as ex: print 'function name: ', __name__ print Exception, ":", ex return generate_error_response(error_constants.ERR_SAVE_INFO_FAIL, status.HTTP_500_INTERNAL_SERVER_ERROR) if faculty_type == 1: cur_section.chief.add(cur_faculty) if faculty_type == 2: cur_section.exec_chief_sub_bureau.add(cur_faculty) if faculty_type == 3: cur_section.exec_chief_trans.add(cur_faculty) if faculty_type == 4: cur_section.exec_chief_armed_poli.add(cur_faculty) return Response(response_data, status.HTTP_200_OK)
def extract_results(html, year, season): soup = BeautifulSoup(html, 'html.parser').find_all(id='searchResultsPanel')[0] soup = soup.find_all('div', recursive=False)[1].find_all('table', limit=1)[0] semester = Semester(year, season) for row in soup.find_all('tr', recursive=False): tds = row.find_all('td', recursive=False) if not tds: continue department, number, section = extract_text(tds[1]).split() course = Course(Department.get(department), number) title = extract_text(tds[2]) units = int(extract_text(tds[3])) instructors = [] for tag in tds[4].find_all('abbr'): instructor_str = tag['title'] if instructor_str == 'Instructor Unassigned': instructors.append(None) else: instructors.append(Faculty(instructor_str, *Faculty.split_name(instructor_str))) meetings = [] for tr in tds[5].find_all('tr'): meetings.append(Meeting.from_str(*(extract_text(tag) for tag in tr.find_all('td')))) cores = list(set(Core.get(extract_text(tag)) for tag in tds[6].find_all('abbr'))) if not cores: cores = [] seats = int(extract_text(tds[7])) enrolled = int(extract_text(tds[8])) reserved = int(extract_text(tds[9])) reserved_open = int(extract_text(tds[10])) waitlisted = int(extract_text(tds[11])) Offering(semester, course, section, title, units, tuple(instructors), tuple(meetings), tuple(cores), seats, enrolled, reserved, reserved_open, waitlisted)
def testFaculty(self): fac = Faculty() decebal = Student(1, "Decebal", "Dacia") burebista = Student(2, "Burebista", "Dacia") fac.addStudent(decebal) fac.addStudent(burebista) fac.addAssignment(Assignment(1, "deshidratat romani", "102i.Hr", "4.0")) assert fac.getStudents() == [decebal, burebista]
def get(self, id=None): if id: try: faculty = Faculty.objects.get(id=id) except (DoesNotExist, VE): return 'No cuch faculty' return FacultySchema().dump(faculty) else: faculties = Faculty.objects() return FacultySchema().dump(faculties, many=True)
def FacultyAdd(request): user = request.user if user.is_authenticated(): facultyForm = FacultyForm(request.POST) # Проверяем - если браузер присылает данные (запрос) по методу Post if request.method == 'POST': # Создем экземпляр модели данных факультета (новый факультет) faculty = Faculty() #создаем экземпляр отображаемой формы (forms.py) #Возвращаем пользователю страничку в ответ на запрос (шаблон, form подменяем на созданную выше форму, остальное просто надо) if facultyForm.is_valid(): # Заполним содержимое факультета и сохраним его faculty.name = facultyForm.cleaned_data['name'] faculty.save() #lesson.lessonID=date+room #lesson.user = user return HttpResponseRedirect('/admin') return render_to_response('dokladedit.html', { 'form': facultyForm}, context_instance=RequestContext(request)) return HttpResponseRedirect('/admin')
def FacultyAdd(request): user = request.user if user.is_authenticated(): facultyForm = FacultyForm(request.POST) # Проверяем - если браузер присылает данные (запрос) по методу Post if request.method == 'POST': # Создем экземпляр модели данных факультета (новый факультет) faculty = Faculty() #создаем экземпляр отображаемой формы (forms.py) #Возвращаем пользователю страничку в ответ на запрос (шаблон, form подменяем на созданную выше форму, остальное просто надо) if facultyForm.is_valid(): # Заполним содержимое факультета и сохраним его faculty.name = facultyForm.cleaned_data['name'] faculty.save() #lesson.lessonID=date+room #lesson.user = user return HttpResponseRedirect('/admin') return render_to_response('dokladedit.html', {'form': facultyForm}, context_instance=RequestContext(request)) return HttpResponseRedirect('/admin')
def login(user_id, pin_number, user_role): if user_role == ROLES.get("admin"): administrator = Administrator.get_or_none(Administrator.user_id == user_id) if administrator and (administrator.pin_number == pin_number): session['user_id'] = administrator.id return True elif user_role == ROLES.get("moderator"): moderator = Moderator.get_or_none(Moderator.user_id == user_id) if moderator and (moderator.pin_number == pin_number): session['user_id'] = moderator.id return True elif user_role == ROLES.get("faculty"): faculty = Faculty.get_or_none(Faculty.user_id == user_id) if faculty and(faculty.pin_number == pin_number): session['user_id'] = faculty.id return True else: return False
def get_student_data(): return_ = {} faculty = random.choice(Faculty.objects()) return_['curator'] = random.choice(Curator.objects(faculty=faculty)) return_['academic_group'] = random.choice( AcademicGroup.objects(faculty=faculty)) return_['student_card'] = random.randint(0, 100000000000000) return_['student_name'] = get_random_word(random.randint(2, 10)).title() return_['student_surname'] = get_random_word(random.randint(2, 15)).title() return_['marks'] = [] lower_mark = random.randint(2, 5) for i in range(random.randint(5, 10)): mark = Mark() mark.mark = random.randint(lower_mark, 5) return_['marks'].append(mark) return return_
def post(self, request): response_data = { 'retCode': error_constants.ERR_STATUS_SUCCESS[0], 'retMsg': error_constants.ERR_STATUS_SUCCESS[1] } try: name = request.POST.get('name', '') mobile = request.POST.get('mobile', '') duty = request.POST.get('duty', '') district_id = int(request.POST.get('districtId', 0)) channel = request.POST.get('channel', '') call_sign = request.POST.get('callSign', '') level = int(request.POST.get('level', 0)) role = int(request.POST.get('role', 0)) road_section_station = int( request.POST.get('road_section_station', 0)) except Exception as ex: print 'function name: ', __name__ print Exception, ":", ex return generate_error_response( error_constants.ERR_INVALID_PARAMETER, status.HTTP_400_BAD_REQUEST) if not name or not mobile: return generate_error_response(error_constants.ERR_NO_NAME_MOBILE, status.HTTP_400_BAD_REQUEST) # cur_faculty = Faculty.objects.filter(name=name, mobile=mobile) # if cur_faculty.exists(): # cur_faculty.update(enabled=True) else: main_name = '' if level and road_section_station: if level == 1: main_name = Road.objects.get(id=road_section_station).name if level == 2: main_name = Section.objects.get( id=road_section_station).name if level == 3: main_name = Station.objects.get( id=road_section_station).name cur_faculty = Faculty(district_id=district_id, name=name, mobile=mobile, duty=duty, channel=channel, call_sign=call_sign, level=level, role=role, main_id=road_section_station, main_name=main_name) # 岗位人数限制 count = check_faculty_count_particular_role(cur_faculty) if count >= 4: return generate_error_response( error_constants.ERR_FACULTY_EXCEED_COUNT, status.HTTP_400_BAD_REQUEST) else: try: with transaction.atomic(): cur_faculty.save() except Exception as ex: print 'function name: ', __name__ print Exception, ":", ex return generate_error_response( error_constants.ERR_SAVE_INFO_FAIL, status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(response_data, status=status.HTTP_200_OK)
def validate_user_id(self, user_id): faculty = Faculty.select().where(user_id == user_id.data) if faculty is not None: raise ValidationError("Please user a different User Id")
def create_curator(**kwargs): requirede_fields = ('faculty', 'curator_name', 'curator_surname') [kwargs[arg] for arg in requirede_fields] return Curator.objects.create(**kwargs) def create_student(**kwargs): requirede_fields = ('academic_group', 'student_name', 'student_surname', 'student_card') [kwargs[arg] for arg in requirede_fields] return Student.objects.create(**kwargs) if __name__ == '__main__': for i in range(5): print(create_faculty(**get_faculty_data())) for fac in Faculty.objects(): for i in range(random.randint(1, 3)): print(create_academic_group(**get_academic_group_data(fac))) for fac in Faculty.objects(): for i in range(random.randint(2, 5)): print(create_curator(**get_curator_data(fac))) for i in range(100): print(create_student(**get_student_data()))