def __init__(self, file, start_day: datetime, professor: Professor, session: Session): self.doc = Document(str(file)) self.session = session self.professor = professor self.start_day = start_day lessons: List[Lesson] = [] columns = {} rows = {} for table in self.doc.tables[0:1]: for row_index, row in enumerate(table.rows): for column_index, cell in enumerate(table.row_cells(row_index)): if row_index == 0 and column_index == 0: continue elif row_index == 0: columns[column_index] = self._week_day(cell.text) elif column_index == 0: rows[row_index] = self._time(cell.text) else: lessons_info: List[Tuple] = self.unit_regex.findall(cell.text) for lesson_info in lessons_info: for week in [int(i) for i in lesson_info[2].split(',')]: discipline = Discipline.get_or_create(self.session, name=lesson_info[0].replace('\n', '')) time = rows[row_index].split(':') date = start_day + timedelta(week * 7 + columns[column_index], int(time[0]) * 3600 + int(time[1]) * 60) room = lesson_info[4] lesson = Lesson.get_or_create( self.session, discipline=discipline, professor_id=professor.id, date=date ) lesson.room_id = room lesson.type = self._lesson_type(lesson_info[1]) for group_name in lesson_info[3].split(','): if group_name not in list(map(lambda x: x.name, lesson.groups)): lesson.groups.append( Group.get_or_create(self.session, name=group_name) ) session.flush() lessons.append(lesson) self.lessons = lessons
def auth(**kwargs): self.session = Session() if 'POST' in methods: if request.method == 'POST': response = Response(request_type) data = self._read(request) if data is not None: authentication = None try: if self.__auth_require__: authentication = Auth.log_in(**data['user']) result = self.post(data=data.get('data'), auth=authentication, **kwargs) response.set_data(result) except Exception as e: response.set_error(f'{str(type(e))}: {str(e)}') finally: if authentication is not None: authentication.user.session().close() else: response.set_error("you send no data: {}".format( request.value)) return response() if 'GET' in methods: pass
async def look(): def is_time_to_prepare(contact): if contact.last_auto and contact.interval_auto_hours: is_time = contact.last_auto + timedelta( 0, contact.interval_auto_hours * 3600) <= next_loop has_lessons = receiver.has_lessons_since(contact.last_auto) return contact.auto and is_time and has_lessons return contact.auto while 1: tasks = [] now = datetime.now() next_loop = datetime.now() \ + timedelta(0, ((55 if now.minute < 55 else 115) - now.minute - 1) * 60 + (60 - now.second)) session = Session() stats = dict() search_start = datetime.now() for class_ in _DBEmailObject.email_subclasses(): if len(class_.__subclasses__()) == 0: receivers: List[_DBEmailObject] = session.query( class_).all() stats[class_.__name__] = dict(total=0, prepared=[]) stats[class_.__name__]['total'] = len(receivers) for receiver in receivers: contact: ContactInfo = receiver.contact if not contact: continue if is_time_to_prepare(contact): logger.info( f'receiver {receiver.full_name()} is active') tasks.append(loop.create_task(send(receiver))) for task in tasks: await task sleep = (next_loop - datetime.now()).total_seconds() logger.debug(stats) logger.info( f'elapsed time on seek {(datetime.now() - search_start).total_seconds()}s., sleep for {sleep}s.' ) if sleep > 0: await asyncio.sleep(sleep) else: await asyncio.sleep(0)
def new_professor(): print('new_professor') response = Response('new_professor') data = JsonParser.read(request.data.decode('utf8').replace("'", '"')) session = Session() duplicate_login = session.query(Auth).filter( Auth.login == data['data']['login']).all() if len(duplicate_login) == 1: response.set_error('login') return response() professor = Professor.new(session, first_name=data['data']['first_name'], last_name=data['data']['last_name'], middle_name=data['data']['middle_name']) contact = ContactInfo.new(session, email=data['data']['email']) professor.contact = contact session.commit() auth = Auth.new(session, login=data['data']['login'], password=data['data']['password'], user_type=UserType.PROFESSOR, user_id=professor.id) session.commit() response.set_data({'ok': 'ok'}, NewProfessorResponse) return response()
def post(self, data: dict, auth: Auth, **kwargs): print('new_professor') session = Session() duplicate_login = session.query(Auth).filter( Auth.login == data['login']).all() if len(duplicate_login) == 1: raise Exception('login') professor = Professor.new(session, first_name=data['first_name'], last_name=data['last_name'], middle_name=data['middle_name']) contact = ContactInfo.new(session, email=data['email']) professor.contact = contact session.commit() auth = Auth.new(session, login=data['login'], password=data['password'], user_type=UserType.PROFESSOR, user_id=professor.id) session.commit() return {'ok': 'ok'}
def on_response(self, received_data: Dict, progress_bar): def create_row(item_data: Dict, class_: Type[_DBObject]): if not class_.get(session, **item_data): class_.new(session, **item_data) session.flush() progress_bar.increment() session = Session() received_data = ServerFirstLoadData(**received_data) TOTAL_LENGTH = progress_bar.last() progress_bar.set_part(TOTAL_LENGTH, len(received_data.data), "Загрузка данных") received_data.data.foreach(create_row) Auth.new(session, **received_data.auth) professor = Professor.new(session, **Map.item_type(received_data.professor[0], Professor)) professor._last_update_in = datetime.now() professor._last_update_out = datetime.now() session.commit()
def __init__(self, professor, flags=None): super().__init__(flags) self.professor = professor self.loading_session = Session() self.setWindowTitle("Загрузка данных") self.setMinimumSize(900, 500) wizard_widget = LoadingWizardWidget(professor) wizard_widget.start_loader.connect(self.on_start_load) wizard_widget.start_loader.connect(print) self.setCentralWidget(wizard_widget)
def apply(data): def create_row(item_data: Dict, class_: Type[_DBObject]): if not class_.get(session, **item_data): class_.new(session, **item_data) session.flush() received_data = ServerFirstLoadData(**data) session = Session() auth = Auth.new(session, **received_data.auth) received_data.data.foreach(create_row) professor = Professor.new( session, **Map.item_type(received_data.professor[0], Professor)) professor._last_update_in = datetime.now() professor._last_update_out = datetime.now() session.commit() if on_finish: on_finish()