def create_goal(): form = GoalForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): data = Goal() form.populate_obj(data) data.userId = current_user.id db.session.add(data) db.session.commit() return data.to_dict() return 'invalid info'
def goals(): print(f"REQ: {request.form}") if request.method == 'POST': result = request.form.copy() result['user_id'] = session['USER_ID'] new_goal = Goal() new_goal.populate(result) db.session.add(new_goal) db.session.commit() stats = get_goal_stats(session['USER_ID']) print(f"GOAL: {stats}") return render_template('goals.html', stats=stats, users=get_users())
def goal_new(): form = GoalForm() if form.add_subgoal.data: form.subgoals.append_entry() form.validate = False elif any([sg.delete_subgoal.data for sg in form.subgoals.entries]): for sg in form.subgoals.entries: if sg.delete_subgoal.data: form.subgoals.remove(sg) form.validate = False else: if form.validate_on_submit(): goal = Goal(title=form.title.data, description=form.description.data, duedate=form.duedate.data, user_id=current_user.id) for sg in form.subgoals.entries: goal.subgoals.append( Subgoal(title=sg.title.data, duedate=sg.duedate.data)) db.session.add(goal) db.session.commit() flash("Goal has been successfully created!") return redirect(url_for('goal_view', goal_id=goal.id)) return render_template('goal_new.html', title="Master Lao - Create New Goal", form=form)
def set_goal(): """ sets a user's exercise goal :return: :rtype: """ form = GoalForm() is_add_goal = True if form.validate_on_submit(): goal = Goal(title=form.title.data, motivation=form.motivation.data, acceptance_criteria=form.acceptance_criteria.data, reward=form.reward.data, frequency=form.frequency.data, frequency_activity_type=form.frequency_activity_type.data, duration_activity_type=form.duration_activity_type.data, duration=form.duration.data, distance_activity_type=form.distance_activity_type.data, distance=form.distance.data, user_id=current_user.get_id()) db.session.add(goal) db.session.commit() flash('Well done on setting yourself a goal') return redirect(url_for('main.exercise_log')) return render_template('goal/edit_goal.html', title='Set a goal', form=form, is_add_goal=is_add_goal)
def test_goal(test_client, init_database): u = User.query.filter_by(username=conftest.TEST_USER_USERNAME).first() current_time = datetime.utcnow() goal = Goal(title="My Exercise", motivation="Why am i motivated to do this", acceptance_criteria="My acceptance criteria", reward="how will i reward myself", frequency=5, frequency_activity_type=1, timestamp=current_time, last_updated=current_time, user_id=u.id) db.session.add(goal) db.session.commit() load_goal = Goal.query.filter_by(user_id=u.id).first() assert Goal.query.filter_by(user_id=u.id).count() == 1 assert load_goal.title == goal.title assert load_goal.motivation == goal.motivation assert load_goal.acceptance_criteria == goal.acceptance_criteria assert load_goal.reward == goal.reward assert load_goal.frequency == goal.frequency assert load_goal.frequency_activity_type == goal.frequency_activity_type # ignore microseconds when comparing the timestamps assert "Goal" in repr(load_goal) assert "Goal" in str(load_goal)
def create_goal(db, title, user_id, description=None, duedate=None): goal = Goal(title=title, user_id=user_id, description=description, duedate=duedate) db.session.add(goal) db.session.commit() return goal
def init_db(): print("Start db init") db.session.remove() db.drop_all() db.create_all() u1 = User(username="******", first_name="Ivan", last_name="Fedorovsky", email="*****@*****.**") u2 = User(username="******", first_name="Dzimurhan", last_name="Zaliphan", email="*****@*****.**") u3 = User(username="******", first_name="Zope", last_name="Zope", email="*****@*****.**") u4 = User(username="******", first_name="Lashar", last_name="Lasharan", email="*****@*****.**") u1.set_password('Password') u2.set_password('Password') u3.set_password('Password') u4.set_password('Password') g1 = Goal(title="Goal1") g2 = Goal(title="Goal2", description="Description", duedate=datetime.utcnow() + relativedelta(months=1)) g3 = Goal(title="Goal3", description="Description", duedate=datetime.utcnow() + relativedelta(months=2)) s1 = Subgoal(title="Subgoal Test #1", duedate=datetime.utcnow()) s2 = Subgoal(title="Subgoal Test #2") s3 = Subgoal(title="Subgoal Test #3") g3.subgoals.append(s1) g3.subgoals.append(s2) g3.subgoals.append(s3) u1.goals.append(g1) u1.goals.append(g2) u1.goals.append(g3) db.session.add_all([u1, u2, u3, u4]) db.session.commit() assert User.query.count() == 4 print("Finish db init")
def new(request): current_goal = Goal.objects.filter(user=request.user).first() if current_goal: return redirect('app_goals_timeline', goal_id=current_goal.id) if request.method == 'GET': return render(request, 'goals/new.html', {'timezones': pytz.common_timezones}) if request.method != 'POST': return HttpResponseNotAllowed(['GET', 'POST']) is_valid = 'text' in request.POST and \ 'first_step' in request.POST and \ 'timezone' in request.POST if not is_valid: return HttpResponseBadRequest() start = timezone.now() goal = Goal(user=request.user, timezone=request.POST['timezone'], text=request.POST['text'], start=start) with transaction.atomic(): logger.info('Creating goal user=%s tz=%s' % (goal.user.email, goal.timezone)) goal.save() logger.info('Creating first step goal=%s user=%s' % (goal.id, request.user.email)) first_step = goal.create_step(request.POST['first_step'], goal.start, commit=True) new_goal.send('app.views.goals.new', goal=goal) new_step.send('app.views.goals.new', step=first_step) return redirect('app_steps_start', goal_id=goal.id, step_id=first_step.id)
def goals(): if request.method == 'POST': new_goal = Goal() new_goal.populate(request.form) db.session.add(new_goal) db.session.commit() return "True" elif request.method == 'GET': user_id = request.args.get('user_id') action = request.args.get('type') recent_goal = Goal.query.filter_by(user_id=user_id).order_by( Goal.set_time)[::-1] if not recent_goal: return "No goals found" recent_goal = recent_goal[0] print(recent_goal) if action == "steps": return str(recent_goal.steps) elif action == "distance": return str(recent_goal.distance) return "Incorrect parameters"
def add_goal(): u = User.query.filter_by(username=TEST_USER_USERNAME).first() current_time = datetime.utcnow() goal = Goal(title="My Exercise", motivation="Why am i motivated to do this", acceptance_criteria="My acceptance criteria", reward="how will i reward myself", frequency=5, frequency_activity_type=1, timestamp=current_time, last_updated=current_time, user_id=u.id) db.session.add(goal) db.session.commit()
def add_goal(): form = GoalForm() if form.validate_on_submit(): goal = Goal(weight=form.weight.data, days=form.days.data, start_date=form.start_date.data, person=current_user) db.session.add(goal) db.session.commit() flash('Your Goal has been created!', 'success') return redirect(url_for('display_goal')) return render_template('add_goal.html', title='New Goal', form=form, legend='New Goal')
def addGoal(current_user): data = request.json splitTargetDate = data['targetDate'].split('-') joinedTargetDate = ' '.join(splitTargetDate) datetimeOfTarget = datetime.strptime(joinedTargetDate, '%Y %m %d') userSketchbook = Sketchbook.query.filter( Sketchbook.owner_id == current_user.id).first() newGoal = Goal(owner_id=current_user.id, Sketchbook_id=userSketchbook.id, title=data['title'], description=data['description'], target=data['target'], targetdate=datetimeOfTarget, timestamp=datetime.now()) db.session.add(newGoal) db.session.commit() # check for goals that have passed finished date, and delete them goalsForCurrUser = Goal.query.filter( Goal.owner_id == current_user.id).all() currDate = datetime.now() for goal in goalsForCurrUser: if goal.targetdate < currDate: datapoints = Datapoint.query.filter( Datapoint.goal_id == goal.id).all() for datapoint in datapoints: db.session.delete(datapoint) db.session.delete(goal) db.session.commit() returnDict = { newGoal.Sketchbook_id: { newGoal.id: { 'id': newGoal.id, 'owner_id': newGoal.owner_id, 'sketchbook_id': newGoal.Sketchbook_id, 'title': newGoal.title, 'description': newGoal.description, 'target': newGoal.target, 'targetdate': newGoal.targetdate, 'timestamp': newGoal.timestamp } } } return returnDict
def sync(): upload_goals = request.get_json() goals = upload_goals.get('goals') for goal in goals: title = goal.get('title') timestamp = goal.get('timestamp') level = goal.get('level') parent = goal.get('parent') start = goal.get('start') over = goal.get('over') items = goal.get('items') username = goal.get('username') user_name = username mGoal = Goal(level, parent, title, start, over, timestamp, 9, items, username) existGoal = Goal.query.filter_by(title=title, username=username).first() if goal.get('status') == 1: if existGoal is not None: db.session.delete(existGoal) # 增 db.session.add(mGoal) # 增 elif goal.get('status') == 2: if existGoal is not None: db.session.delete(existGoal) # 删除 elif goal.get('status') == 3: if existGoal is not None: if existGoal.timestamp < timestamp: db.session.delete(existGoal) db.session.add(mGoal) # 改 db.session.commit() goals_in_db = Goal.query.filter_by( username=upload_goals.get('username')).all() contList = [] for goal in goals_in_db: contList.append(goal.serialize()) return formattingData(200, "success", contList)
def load_goals(user_id): if (request.method == 'GET'): goals = db.session.query(Goal).filter(Goal.user_id == user_id) goals_dict = {} for goal in goals: goals_dict[goal.id] = goal.to_dict() return {'goals': goals_dict}, 200 elif (request.method == 'POST'): data = request.get_json() goal = Goal(description=data['description'], amount=data['amount'], completion_year=data['completion_year'], completion_month=data['completion_month'], user_id=user_id) db.session.add(goal) db.session.commit() goals = db.session.query(Goal).filter(Goal.user_id == user_id) goals_dict = {} for goal in goals: goals_dict[goal.id] = goal.to_dict() return {'goals': goals_dict}, 200 elif (request.method == 'PATCH'): data = request.get_json() id = data['id'] goal = Goal.query.get(id) goal.is_complete = not goal.is_complete db.session.add(goal) db.session.commit() goals = db.session.query(Goal).filter(Goal.user_id == user_id) goals_dict = {} for goal in goals: goals_dict[goal.id] = goal.to_dict() return {'goals': goals_dict}, 200 elif (request.method == 'DELETE'): data = request.get_json() id = data['id'] goal = Goal.query.get(id) db.session.delete(goal) db.session.commit() goals = db.session.query(Goal).filter(Goal.user_id == user_id) goals_dict = {} for goal in goals: goals_dict[goal.id] = goal.to_dict() return {'goals': goals_dict}, 200
""" run one time to load data from json file teachers.json to database test.db """ import json from app.models import Teacher, Goal, db from app import app db.init_app(app) app.app_context().push() for goal, rus, favicon in (("travel", "путешествй", '⛱'), ("study", "учебы", '🏫'), ("work", "рабoты", '🏢'), ("relocate", "переезда", '🚜')): gl = Goal(title=goal, title_rus=f"Для {rus}", image_location=f"{goal}.png", favicon=favicon) db.session.add(gl) with open("json_data/teachers.json", "r") as f: teachers = json.load(f) for t in teachers: teacher = Teacher( name=t["name"], about=t["about"], rating=t["rating"], picture=t["picture"], price=t["price"], )
with open("data.json", "r", encoding="utf-8") as f: data = json.loads(f.read()) with open("data.json", "r", encoding="utf-8") as f: data = json.loads(f.read()) # Импорт целей db.session.execute(text("DELETE FROM goals;")) goals = [] g = [] ind = 0 for i, val in data["goals"].items(): goals.append( Goal(id=ind, name=i, desc=val, style=data["goalstyle"][i], icon=data["goalicon"][i])) g.append(i) db.session.add(goals[ind]) ind += 1 # Импорт справочника Дни i = 1 s = "INSERT INTO days(id, day, day_desc)\n VALUES" for d, desc in data["days"].items(): s += f"({i}, '{d}', '{desc}'),\n" i += 1 db.session.execute(text("DELETE FROM days;")) db.session.execute(text(s[0:-2] + ";"))
assert total_distance_by_exercise_type == { 1: 0, 2: 0, 3: 0, 4: 10, 5: 0, 6: 0 } weekly_totals_test_data = [ ([ Goal(title="My Exercise", motivation="Why am i motivated to do this", acceptance_criteria="My acceptance criteria", reward="how will i reward myself", frequency=5, frequency_activity_type=-1, user_id=1) ], [ Activity(id=1, type=1, title='title', duration=20, iso_timestamp='2020-06-16T04:58:33.302785+05:00') ], [(20, 0, 0)]), ([ Goal(title="My Exercise", motivation="Why am i motivated to do this", acceptance_criteria="My acceptance criteria", reward="how will i reward myself",
def build_goal_from_json(json): return Goal(title=json["title"])
dotenv_path = os.path.join(os.path.dirname(__file__), ".env") if os.path.exists(dotenv_path): load_dotenv(dotenv_path) engine = create_engine(os.getenv("DEVELOPMENT_DATABASE_URI")) session = sessionmaker() session.configure(bind=engine) s = session() goal_in_db = dict() for g_key, g_value in goals.items(): # Model GOAL g = Goal(name=g_key, name_ru=g_value) s.add(g) goal_in_db[g_key] = g for teacher in teachers: # Model TEACHER t = Teacher( name=teacher["name"], about=teacher["about"], rating=teacher["rating"], picture=teacher["picture"], price=teacher["price"], ) # Model Teacher_goal