def create_training(self): """ Creates a new training associated with the recruitment {@self.recruitment_id} :return: """ print 'Creating Training....' recruitment = Recruitments.query.filter_by( id=self.recruitment_id).first() training = Training.query.filter_by( recruitment_id=self.recruitment_id).first() if not training: training = Training( id=str(uuid.uuid4()), training_name=recruitment.name, country=recruitment.country, district=recruitment.district, recruitment_id=recruitment.id, training_status_id=1, client_time=time.time(), ) if recruitment.country == 'KE': if recruitment.subcounty_id is not None: training.subcounty_id = recruitment.subcounty_id if recruitment.county_id is not None: training.county_id = recruitment.county_id else: if recruitment.location_id is not None: training.location_id = recruitment.location_id db.session.add(training) db.session.commit() return training
def training_user(): """Выводит все упражнения выбранной тренировки на экран""" if current_user.active_training == 1: training_id = TrainingList(user_id=current_user.id) i = training_id.get_training() exe = Training(id=i.training_id) exercises = exe.all_exe() return render_template('training_user.html', title='Тренировка', exercises=exercises)
def index(): exercises = [] form = CompleteExeForm() if current_user.active_training == 1: training_id = TrainingList(user_id=current_user.id) i = training_id.get_training() exe = Training(id=i.training_id) count = exe.count_day exercises = exe.day_exe(1) if form.validate_on_submit(): flash('Отлично! Приходи завтра, здесь будут новые упражнения!') return redirect(url_for('index')) return render_template('index.html', title='Home Page', exercises=exercises, form=form)
def select_training(): form = SelectTrainingForm() if form.validate_on_submit(): select_t = Training(tipe=form.tipe.data, muscle_group=form.muscle_group.data, name_sport=form.name_sport.data, gender=current_user.gender) if current_user.hd == 'Yes': t = select_t.hd_training() return render_template('select_training.html', training=t, form=form) else: if select_t.tipe == 'Нет': select_t.tipe = 'Для начинающих' if select_t.muscle_group == 'Нет': select_t.muscle_group = 'Все тело' t = select_t.search_training() # нужна проверка на возраст # db.session.add(select_t) # db.session.commit() return render_template('select_training.html', training=t, form=form) return render_template('select_training.html', title='Подбор тренировки', form=form)
def training_creation(request): if request.is_ajax(): if request.method == 'POST': user = request.user data = json.loads(request.body) year = int(data['date'].split('-')[0]) month = int(data['date'].split('-')[1]) day = int(data['date'].split('-')[2]) date = datetime.date(year, month, day) day = user.day_set.filter(date=date).first() if day is not None: activity = PhysicalActivity.objects.filter( id=int(data['activity'])).first() if activity is not None: training = Training() try: day.lose_kcal = round(day.lose_kcal + data['lose'], 1) day.activity_time = round(day.activity_time + data['time']) training.lose_kcal = data['lose'] training.notes = data['notes'] training.time = data['time'] training.day = day training.physical_activity = activity day.save() training.save() except: return HttpResponse('Server error occured', status=500) data = { 'id': training.id, 'activity_name': activity.name, 'met': activity.met, 'class_name': activity.image_class } data = json.dumps(data) return HttpResponse(data, content_type='application/json', status=200) return HttpResponse('Bad request', status=400) return HttpResponse('Method not allowed', status=405)
def new_data(): """Create a new data training.""" form = TrainingForm() if form.validate_on_submit(): datatraining = Training(name=form.name.data, k1=form.k1.data, k2=form.k2.data, k3=form.k3.data, k4=form.k4.data, k5=form.k5.data, k6=form.k6.data, k7=form.k7.data, c=form.c.data) db.session.add(datatraining) db.session.commit() flash( 'Data training {} successfully created'.format(datatraining.name), 'form-success') return render_template('training/new_data.html', form=form)
def import_datatraining(): """Import Data Data Training to Database""" file = os.path.abspath('app/resources') + "/datatraining.json" json_data = open(file).read() json_obj = json.loads(json_data) for row in json_obj: try: data = Training(name=row['name'], k1=row['k1'], k2=row['k2'], k3=row['k3'], k4=row['k4'], k5=row['k5'], k6=row['k6'], k7=row['k7'], c=row['c']) db.session.add(data) db.session.commit() print('Import data data training {} done.'.format(data.name)) except exc.IntegrityError: print('Data data training {} already exists'.format(data.name)) db.session.rollback()
def saveTraining(): try: user = verify_token(request.headers.get('token')) if user is None: return jsonify({ 'code': 401, 'message': 'Training can only be saved while logged in.' }) training = Training(notes=request.headers.get('notes'), is_public=request.headers.get('is_public'), date_created=datetime.date.today()) db.session.add(training) db.session.flush() for climb in request.headers.get('climbs'): send = Send( climb_id=climb['climb_id'], training_id=training.id, send_category=climb['send_category'], notes=climb['notes'], time_created=climb['time_created'], # TODO media url ) db.session.add(send) db.session.commit() return jsonify({ 'code': 200, 'message': 'Your training log has been saved successfully.' }) except: return jsonify({'code': 400, 'message': 'Something went wrong.'})
def update_training(json_body: dict, training_id) -> None: training_new = Training.create_from_json(json_body) training = db.session.query(Training).filter( Training._id == training_id).first() training.update(training_new) db.session.commit()
def check_date_format(date_format) -> str: "JS sometimes sends another date format, SQLite has problem with queries, this function is to avoid this." if re.match(DATE_YYYY_MM_DD_PATTERN, date_format): return date_format return Training.reformate_date(date_format)
def user(username): # Prevents users from accessing other's page. if current_user.id != User.query.filter_by(username=username).first().id: flash('You do not have access to this page!') return redirect(url_for('index')) # Query the database for user. user = User.query.filter_by(username=username).first() # Query the database for the users training projects. all_trainings = user.training.all() # Adds all trainings to list for user to see their projects. trainings = [] for each in all_trainings: trainings.append({ 'id': each.id, 'project': each.project, 'ready': each.ready, 'filename': each.filename }) # Load the upload form. form = UploadTraining() # If the form is valid, submit the form. if form.validate_on_submit(): # Load data into f variable and description into d variable. f = form.upload.data d = form.description.data # Creates new training entry for database. training = Training(project=d, user=current_user, ready=False) # Add and submit entry to database. db.session.add(training) db.session.commit() # Query the database for this training jpb. # This is to enable consistancy across input files, training is added # to the database first, then the id is obtained. training_id = Training.query.filter_by(user=current_user, project=d).first().id # Retrieves the filename for the input file. filename = secure_filename(f.filename) # Filenames are stored as "userid_trainingid_filename". filename = str( current_user.id) + '_' + str(training_id) + '_' + filename[:-4] # Save the file under instance/files/filename.csv. f.save(os.path.join(app.instance_path, 'files', filename + '.csv')) # Update the training database entry to include the new filename. training.filename = filename # Merge and commit the entry to the database. db.session.merge(training) db.session.commit() # Creates queue entry to process the uploaded data. # Calls the training function for the worker. running_job = q.enqueue_call(func=training_function, args=(training_id, url_for('user', username=user.username, _external=True)), result_ttl=5000) # Flash the user and return user to home. flash('File upload successful') return redirect(url_for('user', username=username)) # Render user/<username>. return render_template('user.html', user=user, trainings=trainings, form=form)
def create(): if 'username' in session: username = session['username'] if session['role'] == 2 or session[ 'role'] == 3: ##COMPROBAR SI ES ADMIN PARA ENTRAR form = TrainingForm() if request.method == 'POST': fechaStart = form.start.data fechaEnd = form.end.data fechaStart = fechaStart.replace('/', '-') fechaEnd = fechaEnd.replace('/', '-') if form.times.data == '1': fechaStart = fechaStart + ' 08:00:00' fechaEnd = fechaEnd + ' 13:00:00' elif form.times.data == '2': fechaStart = fechaStart + ' 13:00:00' fechaEnd = fechaEnd + ' 18:00:00' elif form.times.data == '3': fechaStart = fechaStart + ' 18:00:00' fechaEnd = fechaEnd + ' 22:00:00' fechaHoy = datetime.now().date() xfecha = fechaHoy.strftime("%Y/%m/%d") fechaA = datetime.strptime(form.start.data, "%Y/%m/%d") fechaB = datetime.strptime(form.end.data, "%Y/%m/%d") fechaC = datetime.strptime(xfecha, "%Y/%m/%d") if fechaA > fechaB: flash('La fecha final debe ser posterior a la inicial', 'error') elif fechaA < fechaC: flash( 'La fecha inicial debe ser posterior o igual a la de hoy', 'error') elif fechaB < fechaC: flash( 'La fecha final debe ser posterior o igual a la de hoy', 'error') else: training = Training(name=form.name.data, start=fechaStart, end=fechaEnd, finalizada=False, description=form.description.data, comments=form.comments.data, times=form.times.data, department=form.department.data) if not training.name: flash('El campo "Nombre" no puede estar vacio', 'error') elif not training.start: flash('El campo "Inicio" no puede estar vacio', 'error') elif not training.end: flash('El campo "Fin" no puede estar vacio', 'error') elif not training.description: flash('El campo "Descripcion" no puede estar vacio', 'error') elif not training.times: flash('El campo "Horarios" no puede estar vacio', 'error') elif not training.department: flash('El campo "Sector" no puede estar vacio', 'error') else: db.session.add(training) db.session.commit() flash('Capacitacion creada.', 'success') return redirect((url_for('select_students', id=training.id))) return render_template('capacitacion.html', title='Crear capacitacion', form=form) else: return redirect(url_for('forbidden')) return redirect(url_for('login'))