def creating_tasks(cnt_task): session = db_session.create_session() tour = session.query(Tournament).first() text_file = Document(tour.text) for para in text_file.paragraphs: dop = para.text.strip() if dop != "": ind = dop.find('.') num = dop[1:ind].strip() text = dop[ind + 1:].strip() task = Task(num=num, text=text, cnt=cnt_task) session.add(task) session.commit() os.remove(tour.text) answers_file = Document(tour.answers) for para in answers_file.paragraphs: dop = para.text.strip() if dop != "": ind = dop.find('.') num = dop[1:ind].strip() answer = dop[ind + 1:].strip() task = session.query(Task).filter(Task.num == num).first() try: task.answer = answer session.commit() except AttributeError: pass os.remove(tour.answers)
def get(self, user): try: tasks = Task.select().where(Task.user_id == 1) except: pass return {'data': tasks}
def post(self): args = parser.parse_args() session = db_session.create_session() task = Task(name=args['name'], about=args['about'], is_finished=args['is_finished'], author=args['author']) session.add(task) session.commit() return jsonify({'success': 'OK'})
def delete(self, task_id, user): try: task = Task.get(Task.id == task_id) except: return api.abort(404) try: task.delete_instance() except: return api.abort(500)
def post(self): args = reqparse.parse_args() session = db_session.create_session() task = Task( title=args['title'], content=args['content'], subject=args['subject'], rating=args['rating'], ) session.add(task) session.commit() return jsonify({'success': 'OK'})
def post(self): args = parser.parse_args() session = db_session.create_session() task = Task(title=args['title'], content=args['content'], date=args['date'], start_time=args['start_time'], end_time=args['end_time'], user_id=args['user_id'], category_id=args['category_id'], is_done=args['is_done']) session.add(task) session.commit() return jsonify({'success': 'OK'})
def post(self, user): # Get supplied arguments args = task_parser.parse_args() title = args['title'] description = args['description'] # Create task try: new_task = Task.create(user_id=user.id, title=title, description=description, date_created=datetime.utcnow()) return {'data': [new_task]} except: app.logger.error('Error creating new task') api.abort(500)
def put(self, task_id, user): try: task = Task.get(Task.id == task_id) except: return api.abort(404) try: # Get supplied arguments args = task_parser.parse_args() title = args['title'] description = args['description'] task.title = title task.description = description task.date_modified = datetime.utcnow() task.save() return {'data': [task]} except: return api.abort(500)
def add_task(): form = TaskForm() if form.validate_on_submit(): session = db_session.create_session() task = Task() task.title = form.title.data task.content = form.content.data task.subject = form.subject.data task.rating = form.rating.data current_user.task.append(task) session.merge(current_user) session.commit() return redirect('/edit') return render_template('task_page.html', title='Добавить задачу', form=form)
def add_task(): form = TaskForm() db_sess = db_session.create_session() categories = db_sess.query(Category).filter( Category.user_id == current_user.id).all() form.category.choices = [(i.id, i) for i in categories] form.category.default = [ i for i in categories if i.name == 'Без категории' ][0].id if form.validate_on_submit(): if request.form.get('category') is None: return render_template('task_add.html', title='Добавление задачи', form=form, message='Необходимо выбрать категорию', date=datetime.datetime.now()) elif form.date.data is not None and form.date.data < datetime.date.today( ): form.category.default = int(request.form.get('category')) return render_template('task_add.html', title='Добавление задачи', form=form, message='Выбрана дата из прошлого', date=datetime.datetime.now()) elif form.start_time.data is not None and form.end_time.data is not None and form.start_time.data > form.end_time.data: form.category.default = int(request.form.get('category')) return render_template( 'task_add.html', title='Добавление задачи', form=form, message='Время начала позже времени окончания', date=datetime.datetime.now()) elif form.start_time.data is not None and form.end_time.data is None: form.category.default = int(request.form.get('category')) return render_template('task_add.html', title='Добавление задачи', form=form, message='Добавьте время окончания', date=datetime.datetime.now()) elif form.start_time.data is None and form.end_time.data is not None: form.category.default = int(request.form.get('category')) return render_template( 'task_add.html', title='Добавление задачи', form=form, message='Время начала позже времени окончания', date=datetime.datetime.now()) elif len(form.title.data) > 100 or len(form.title.data) < 1: form.category.default = int(request.form.get('category')) return render_template( 'task_add.html', title='Добавление задачи', form=form, message='Заголовок задачи должен быть от 1 до 100 символов', date=datetime.datetime.now()) task = Task() task.title = form.title.data task.content = form.content.data task.date = form.date.data task.start_time = form.start_time.data task.end_time = form.end_time.data task.category_id = int(request.form.get('category')) current_user.tasks.append(task) db_sess.merge(current_user) db_sess.commit() return redirect('/tasks') return render_template('task_add.html', title='Добавление задачи', form=form, date=datetime.datetime.now())
def add_task(): db_sess = db_session.create_session() form = TaskForm() form.country.choices = [(country.id, country.name) for country in db_sess.query(Country).all()] form.type.choices = [(types.id, types.title) for types in db_sess.query(Type).all()] form.country.choices.insert( 0, form.country.choices.pop( form.country.choices.index( (current_user.country_from, db_sess.query(Country).get(current_user.country_from).name)))) if current_user.friends: friends = [ db_sess.query(User).get(friend_id) for friend_id in current_user.get_friends_list() ] form.friend_invited.choices = [(str(friend.id), f'{friend.name} {friend.surname}') for friend in friends] if form.validate_on_submit(): task = Task() task.creator_id = current_user.id task.creator = current_user task.title = form.title.data task.description = form.description.data task.type = form.type.data task.set_participates(form.friend_invited.data) task.country = form.country.data task.address = form.address.data task.date = form.date.data task.is_private = form.is_private.data task.is_address_displayed = form.is_address_displayed.data db_sess.add(task) picked_type = db_sess.query(Type).get(form.type.data) picked_type.tasks.append(task) picked_country = db_sess.query(Country).get(form.country.data) picked_country.tasks.append(task) for friend in [ db_sess.query(User).get(int(friend_id)) for friend_id in form.friend_invited.data ]: friend.tasks.append(task) current_user.tasks.append(task) db_sess.commit() if task.is_address_displayed: get_map_picture(task.id, task.address) return redirect('/') return render_template('tasks.html', title='Добавить мероприятие', form=form)
def get(self, task_id, user): try: task = Task.get(Task.id == task_id) except: return api.abort(404) return {'data': [task]}
def profile(): global PROOF_CODE, AUTHORIZE AUTHORIZE = 'Профиль' tasksDict = dict() if current_user.type == 'teacher': db_sess = db_session.create_session() for item in db_sess.query(Task_Kinds).all(): tasksDict[item.name] = loads(item.type) if request.method == "GET": return render_template("profile.html", autho=AUTHORIZE, user=current_user, tasksDict=tasksDict) elif request.method == "POST": if request.form['submit_button'] == HOME: return redirect(url_for("index")) if request.form['submit_button'] == AUTHORIZE: if AUTHORIZE == 'Профиль': return redirect(url_for("profile")) elif AUTHORIZE == 'Авторизация': return redirect(url_for("login")) return redirect(url_for("profile")) if request.form['submit_button'] == "Приступить": if current_user.type == 'student': return redirect(url_for("testBuild")) return redirect(url_for("testBuild")) if request.form['submit_button'] == "Создать": if request.form.getlist('themeOfTask') and request.form.getlist( 'answers')[0]: task_atts = {} if '//' in request.form['themeOfTask']: task_atts['fase'] = 'oldKind oldType' task_atts['kind'], task_atts['type'] = request.form[ 'themeOfTask'].split('//') elif request.form['themeOfTask'] == "New kind and type": task_atts['fase'] = 'newKind newType' if request.form.getlist('New kind')[0] and \ request.form.getlist('New type')[0]: task_atts['kind'] = request.form['New kind'] task_atts['type'] = request.form['New type'] else: task_atts['fase'] = 'oldKind newType' if request.form.getlist('New type old kind')[0]: db_sess = db_session.create_session() _1 = request.form['New type old kind'] _2 = request.form['themeOfTask'] if db_sess.query(Task_Kinds).filter( Task_Kinds.type == _1, Task_Kinds.name == _2).first(): return render_template("profile.html", autho=AUTHORIZE, user=current_user, tasksDict=tasksDict, message='Такая подтема ' 'уже существует') task_atts['kind'] = request.form['themeOfTask'] task_atts['type'] = request.form['New type old kind'] if not(task_atts.get('kind', False) and task_atts.get('type', False)): return render_template("profile.html", autho=AUTHORIZE, user=current_user, tasksDict=tasksDict, message='Подтема задания ' 'не отмечена') task_atts['question'] = request.form.getlist('question')[0] task_atts['text'] = request.form.getlist('text')[0] task_atts['answers'] = list(filter(lambda x: x, request.form.getlist( 'answers')[0].split( '\r\n'))) if task_atts['fase'] == 'newKind newType': task_type = Task_Kinds(name=task_atts['kind'], type=dumps([task_atts['type']])) db_sess = db_session.create_session() db_sess.add(task_type) db_sess.commit() if task_atts['fase'] == 'oldKind newType': db_sess = db_session.create_session() task_type = db_sess.query( Task_Kinds).filter( Task_Kinds.name == task_atts['kind']).first() a = loads(task_type.type) + [task_atts['type']] task_type.type = dumps(a) db_sess.commit() db_sess = db_session.create_session() task_type = db_sess.query( Task_Kinds).filter( Task_Kinds.name == task_atts['kind']).first() task = Task( kind=task_atts['kind'], type=task_atts['type'], question=task_atts['question'], text=task_atts['text'], answers=dumps(task_atts['answers']), user_id=current_user.id ) db_sess = db_session.create_session() db_sess.add(task) db_sess.commit() return redirect(url_for('profile')) return render_template("profile.html", autho=AUTHORIZE, user=current_user, tasksDict=tasksDict, message='Обозначение темы и ответов ' 'задания обязательны') if request.form['submit_button'] == "Генерировать ключ": if request.form.getlist('type') and \ request.form.getlist('email')[0]: db_sess = db_session.create_session() if any(map(lambda x: x.email == request.form['email'], db_sess.query(User).all())): return render_template("profile.html", autho=AUTHORIZE, user=current_user, gener_message='Такой ' 'пользователь ' 'уже существует') bad = ['`', '%', '^', '<', '>', '[', ']', "/", '=', chr(92), ':', ';'] key = [chr(i) for i in range(48, 123) if chr(i) not in bad] key = ''.join(sample(key, randint(10, 16))) with open('config/admin passes.txt', mode='w+', encoding='utf-8')as passes: passes.write(f"{request.form['type']} " f"{request.form['email']} " f"{generate_password_hash(key)}") return render_template("profile.html", autho=AUTHORIZE, key=key, user=current_user) else: return render_template("profile.html", autho=AUTHORIZE, user=current_user, gener_message='Поля не заполнены') return render_template("profile.html", autho=AUTHORIZE, user=current_user) if request.form['submit_button'] == "Удалить": if not(request.form.getlist('deleteEmail')[0]): PROOF_CODE = 0 return render_template("profile.html", autho=AUTHORIZE, user=current_user, message='Чтобы удалить кого-то, ' 'надо ввести почту',) else: deleteEmail = request.form['deleteEmail'] if PROOF_CODE: if request.form['proof'] == str(PROOF_CODE) and \ deleteEmail != current_user.email: db_sess = db_session.create_session() if any(map( lambda x: x.email == deleteEmail, db_sess.query(User).all())): db_sess.query(User).filter( User.email == deleteEmail).delete() db_sess.commit() PROOF_CODE = 0 return render_template("profile.html", autho=AUTHORIZE, user=current_user, message='Пользователь ' 'успешно удалён', proofCode='', deleted='') else: PROOF_CODE = 0 return render_template("profile.html", autho=AUTHORIZE, user=current_user, message='Пользователя ' 'с такой почтой ' 'не существует') PROOF_CODE = 0 return render_template("profile.html", autho=AUTHORIZE, user=current_user, message='Неправильно ' 'введены поля', proofCode='', deleted='') else: deleteEmail = request.form['deleteEmail'] db_sess = db_session.create_session() if deleteEmail == current_user.email: return render_template("profile.html", autho=AUTHORIZE, user=current_user, message='Нельзя удалять ' 'себя. Это жестоко') if all(map(lambda x: x.email != deleteEmail, db_sess.query(User).filter( User.email != current_user.email))): return render_template("profile.html", autho=AUTHORIZE, user=current_user, message='Пользователя с ' 'такой почтой не ' 'существует') PROOF_CODE = randint(1000, 10000) return render_template("profile.html", autho=AUTHORIZE, user=current_user, proofCode=PROOF_CODE, deleted=deleteEmail) if request.form['submit_button'] == "Выйти": AUTHORIZE = 'Авторизация' return redirect(url_for('logout')) return render_template("profile.html", autho=AUTHORIZE, tasksDict=tasksDict, user=current_user)