Example #1
0
def add_exercise():
    reqbody = request.get_json() or {}
    if ('user_id' not in reqbody or 
            'description' not in reqbody or 
            'duration' not in reqbody or 
            'date' not in reqbody):
        return bad_request("Exercise must include user_id, description, duration, and date fields")
    
    # parse the date sent by the client
    try:
        #datefield = reqbody['date']
        d = parser.parse(reqbody['date'])
        #dateparts = datefield.split('-')
        #d = date(int(dateparts[0]),int(dateparts[1]),int(dateparts[2]))
        
    except:
        return bad_request("Date field not formatted correctly")
    reqbody['date'] = d
    
    exercise = Exercise()
    exercise.from_dict(reqbody)
    db.session.add(exercise)
    db.session.commit()
    result = Exercise.query.filter_by(user_id=exercise.user_id).all()
    response = jsonify(result.to_dict())
    response.status_code = 201
    return response
Example #2
0
    def test_follow_posts(self):
        # create four users
        u1 = User(username='******', email='*****@*****.**')
        u2 = User(username='******', email='*****@*****.**')
        u3 = User(username='******', email='*****@*****.**')
        u4 = User(username='******', email='*****@*****.**')
        db.session.add_all([u1, u2, u3, u4])

        # create four exercise posts
        now = datetime.utcnow()
        e1 = Exercise(style="run",
                      time="5",
                      distance="1",
                      user=u1,
                      timestamp=now + timedelta(seconds=1))
        e2 = Exercise(style="walk",
                      time="50",
                      distance="4",
                      user=u2,
                      timestamp=now + timedelta(seconds=4))
        e3 = Exercise(style="swim",
                      time="30",
                      distance="2",
                      user=u3,
                      timestamp=now + timedelta(seconds=3))
        e4 = Exercise(style="run",
                      time="17",
                      distance="5",
                      user=u4,
                      timestamp=now + timedelta(seconds=2))
        db.session.add_all([e1, e2, e3, e4])
        db.session.commit()

        # set up the followers
        u1.follow(u2)  # elise follows dan
        u1.follow(u4)  # elise follows james
        u2.follow(u3)  # dan follows sarah
        u3.follow(u4)  # sarah follows james
        db.session.commit()

        # check the followed exercise posts of each user
        f1 = u1.followed_posts().all()
        f2 = u2.followed_posts().all()
        f3 = u3.followed_posts().all()
        f4 = u4.followed_posts().all()
        self.assertEqual(f1, [e2, e4, e1])
        self.assertEqual(f2, [e2, e3])
        self.assertEqual(f3, [e3, e4])
        self.assertEqual(f4, [e4])
Example #3
0
def test_avarage_rating(session):
    u0 = User(username='******', password='******')
    u1 = User(username='******', password='******')
    ex = Exercise(title='title1', description='desc0')
    FUNRATING0 = 4
    EFFECTIVERATING0 = 2
    CLEARRATING0 = 1
    AV0 = (FUNRATING0 + EFFECTIVERATING0 + CLEARRATING0) / 3.0

    FUNRATING1 = 1
    EFFECTIVERATING1 = 5
    CLEARRATING1 = 3
    AV1 = (FUNRATING1 + EFFECTIVERATING1 + CLEARRATING1) / 3.0
    AV = (AV0 + AV1) / 2.0

    session.add_all([u0, u1, ex])
    session.commit()
    rating0 = Rating(fun=FUNRATING0,
                     clear=CLEARRATING0,
                     effective=EFFECTIVERATING0,
                     exercise_id=ex.id,
                     user_id=u0.id)
    rating1 = Rating(fun=FUNRATING1,
                     clear=CLEARRATING1,
                     effective=EFFECTIVERATING1,
                     exercise_id=ex.id,
                     user_id=u1.id)
    session.add_all([rating0, rating1])
    session.commit()

    ex_id, avg_rating = session.query(Exercise.id, Exercise.avg_rating).first()

    # ghetto way of ignoring the last bunch of decimal points. SQL
    # rounds differently than python.
    assert ex_id == ex.id and int(avg_rating * 1000) == int(AV * 1000)
Example #4
0
def test_give_rating(session):
    u0 = User(username='******', password='******')
    u1 = User(username='******', password='******')
    ex = Exercise(title='title1', description='desc0')
    FUNRATING0 = 4
    EFFECTIVERATING0 = 2
    CLEARRATING0 = 1

    session.add_all([u0, u1, ex])
    session.commit()
    rating = Rating(fun=FUNRATING0,
                    clear=CLEARRATING0,
                    effective=EFFECTIVERATING0,
                    exercise_id=ex.id,
                    user_id=u0.id)
    session.add(rating)
    session.commit()

    ex_id, rating = session.query(Exercise.id, Rating.rating).\
        join(Rating).\
        filter(Rating.exercise_id == ex.id).\
        first()

    r = (FUNRATING0 + EFFECTIVERATING0 + CLEARRATING0) / 3.0

    # ghetto way of ignoring the last bunch of decimal points. SQL
    # rounds differently than python.
    assert ex_id == ex.id and int(rating * 1000) == int(r * 1000)
Example #5
0
def get_exercises():
    user_id = request.args.get('user_id', None, type=int)
    if user_id is None:
        return bad_request("user_id must be included in request")
    
    fd = request.args.get('from', "1970-01-01")
    td = request.args.get('to', "3000-01-01")
   
    try:
        parser.parse(fd)
    except:
        return bad_request("Date field not formatted correctly")
    fromdate = parser.parse(fd)
    
    try:
        parser.parse(td)
    except:
        return bad_request("Date field not formatted correctly")
    todate = parser.parse(td)

    lim = request.args.get('limit', 10 , type=int)

    exerciselog = Exercise.query.filter(Exercise.user_id==user_id,
                                        Exercise.date >= fromdate,
                                        Exercise.date <= todate).\
                                        order_by(Exercise.date.desc()).limit(lim).all()
    log = Exercise.to_log_dict(exerciselog)
    response = jsonify(log)
    return response
Example #6
0
def quiz():
    user = User.query.filter_by(username=current_user.username).first_or_404()
    form = ExerciseForm()
    if form.validate_on_submit():
        style = form.style.data
        time = form.time.data
        exercise_date = form.date.data
        distance = form.distance.data
        mins_per_k = round(form.time.data / form.distance.data, 2)
        rating = form.rate_exercise.data
        comment = form.exercise_comments.data
        exercise = Exercise(style=form.style.data,
                            time=form.time.data,
                            exercise_date=form.date.data,
                            distance=form.distance.data,
                            rate_exercise=form.rate_exercise.data,
                            exercise_comments=form.exercise_comments.data,
                            user=current_user)
        db.session.add(exercise)
        db.session.commit()
        return render_template("results.html",
                               title="Results Page",
                               style=style,
                               time=time,
                               exercise_date=exercise_date,
                               distance=distance,
                               mins_per_k=mins_per_k,
                               rating=rating,
                               comment=comment,
                               user=user)
    return render_template("quiz.html",
                           title="Quiz Page",
                           form=form,
                           user=user)
Example #7
0
    def post(self):
        """API endpoint for creating an exercise

        :return: status code 405 - invalid JSON or invalid request type
        :return: status code 400 - unsupported Content-Type
        :return: status code 201 - successful submission
        """

        # Ensure post's Content-Type is supported
        if request.is_json:
            # Ensure data is a valid JSON
            json_request = request.get_json(silent=True)

            if json_request:
                exercise, errors = Ex.load(json_request)

                if errors:
                    current_app.logger.info(
                        'Error deserializing json to Exercise [{}]'.format(
                            json_request))
                    return make_response(jsonify(errors), 405)

                exercise.save()
                current_app.logger.info(
                    'Created new exercise \'{}\' [{}]'.format(
                        exercise.name, exercise.id))
                return exercise.dump().data, 201

            current_app.logger.info('Invalid JSON')
            return make_response(jsonify(error="Invalid JSON!"), 405)

        current_app.logger.info('Unsupported Content-Type')
        return make_response(jsonify(error="Unsupported Content-Type!"), 400)
Example #8
0
def post_exercises():
    '''Post new exercise.'''
    serializer = Serializer(ExerciseSchema, request.args)
    data = dict(author_id=auth.current_user.id,
                **serializer.load(request.get_json()))
    exercise = Exercise.create(db.session, data)
    rv = serializer.dump(exercise)
    return rv, 201, get_location_header('.get_exercise', id=exercise.id)
 def addExercise(ace_id, name, muscle, equipment, difficulty, instructions):
     commit(
         Exercise(ace_id=ace_id,
                  name=name,
                  muscle=muscle,
                  equipment=equipment,
                  difficulty=difficulty,
                  instructions=instructions))
Example #10
0
 def test_create_exercise(self):
     exercise1 = Exercise(description='Pushups',
                          duration=15,
                          date=datetime.utcnow(),
                          user_id=1)
     db.session.add(exercise1)
     db.session.commit()
     exerciselog = Exercise.query.filter_by(user_id=1).first()
     self.assertEqual(exercise1, exerciselog)
Example #11
0
    def get(self, limit, offset):
        """API endpoint for getting a list of exercises

        :param limit: limit number of exercises to retrieve
        :param offset: offset query from the top

        :return: status code 200 - sucessful retrieval
        """

        exercise_list = (Ex.query.all())

        exercises, errors = Ex.dump_list(exercise_list)

        if errors:
            return make_response(jsonify(error='Internal Server Error'), 500)

        return exercises, 200
Example #12
0
    def add_workout(self, json_dict):
        workout = Workout(owner=json_dict['owner'], name=json_dict['name'])
        db.session.add(workout)
        
        exercises = json_dict["exercises"]
        for element in exercises:
            exercise = Exercise(description = element["description"], workouts = workout)
            db.session.add(exercise)
        
        db.session.commit()    
        print(workout.exercises.all())

        json = {
            'id': workout.id,
            'owner': workout.owner,
            'name': workout.name
        }

        return json
def get_workout_from_dom(dom: str) -> WorkoutSchema:
    soup = BeautifulSoup(dom, 'html.parser')
    all_dom_rounds = soup.select('.card')
    rounds = []
    for dom_round in all_dom_rounds:
        dom_exercises = dom_round.find_all('a')
        exercises = []
        for dom_exercise in dom_exercises:
            exercises.append(
                Exercise(title=dom_exercise.find('h6').string,
                         quantity=dom_exercise.find('p').string))
        rounds.append(
            Round(
                title=dom_round.find('h5').string,
                exercises=exercises,
            ))
    return Workout(
        title=soup.find('h3').string,
        rounds=rounds,
    )
Example #14
0
def entry():
    print("You are in entry now")
    dateString = datetime.now().strftime("%d-%b-%Y")
    team_roster = current_user.athlete_userids[1:-1].split(
        ","
    )  #Take the athlete_userids string and split it into a list of athletes
    athlete_names = [(i, i) for i in team_roster]
    exercise_names = Exercise.get_names()
    form = EntryForm(exercise_names, athlete_names)

    if form.validate_on_submit():
        ex_name = form.exercise_name.data
        athlete_id = form.athlete_id.data.lstrip(
            ' ')  #strips leading whitespaces from athlete_id
        return redirect(
            url_for('second', exercise_name=ex_name, athlete_id=athlete_id))
    return render_template('entry.html',
                           title="Exercise Entry Form",
                           date=dateString,
                           form=form)
Example #15
0
# Run this file with:
# python manage.py shell < jsonToDatabase.py

# Add Exercises from json file to database
import json
from app.models import Exercise
with open('Exercises.json') as f:
    exer_json = json.load(f)

for exe in exer_json:
    exercise = Exercise(name=exe['name'], group=exe['group'], group_code=exe['group_code'], description=exe['description'], image_link=exe['image_link'], ex_id=exe['ex_id'])
    exercise.save()
Example #16
0
def seed_exercises():

    pushups = Exercise(title="Push Ups",
                       muscle_group="Resistance",
                       difficulty="1",
                       description='''Get down on all fours, placing your
                                    hands slightly wider than your shoulders.
                                    Straighten your arms and legs. Lower your
                                    body until your chest nearly touches the
                                    floor. Pause, then push yourself back up.
                                    Repeat.''',
                       video_url="https://www.youtube.com/watch?v=IODxDxX7oi4")

    mountainClimbers = Exercise(title="Mountain Climbers",
                                muscle_group="Resistance",
                                difficulty="1",
                                description='''The plank (also called a front
                                hold, hover, or abdominal bridge) is an
                                isometric core strength exercise that involves
                                maintaining a position similar to a push-up
                                for the maximum possible time.''',
                                video_url="https://www.youtube.com/watch?v=cnyTQDSE884")

    pullups = Exercise(title="Pull-ups",
                       muscle_group="Resistance",
                       difficulty="3",
                       description='''Hold a pull-up bar with an overhand grip,
                                    hands shoulder-width apart. Brace your
                                    core, then pull yourself up until your
                                    lower chest touches the bar. Lower until
                                    your arms are straight again.''',
                       video_url="https://www.youtube.com/watch?v=3YvfRx31xDE")

    planks = Exercise(title="Planks",
                      muscle_group="Resistance",
                      difficulty="1",
                      description='''Plant hands directly under shoulders
                                    (slightly wider than shoulder width) like
                                    you’re about to do a push-up.
                                    Ground toes into the floor and squeeze
                                    glutes to stabilize your body. Your legs
                                    should be working, too — be careful not to
                                    lock or hyperextend your knees.
                                    Neutralize your neck and spine by looking
                                    at a spot on the floor about a foot beyond
                                    your hands. Your head should be in line
                                    with your back.
                                    Hold the position for 20 seconds. As you
                                    get more comfortable with the move, hold
                                    your plank for as long as possible without
                                    compromising your form or breath.''',
                      video_url="https://www.youtube.com/watch?v=ASdvN_XEl_c")

    jumpingJacks = Exercise(title="Jumping Jacks",
                            muscle_group="Resistance",
                            difficulty="1",
                            description="Just flail around. Vigorously.",
                            video_url="https://www.youtube.com/watch?v=1b98WrRrmUs")

    squatJumps = Exercise(title="Squat Jumps",
                          muscle_group="GLUTES",
                          difficulty="2",
                          description='''Bend over, and then don't bend
                                        over. Then do that again.''',
                          video_url="https://www.youtube.com/watch?v=A-cFYWvaHr0")

    situps = Exercise(title="Situps",
                      muscle_group="Resistance",
                      difficulty="2",
                      description='''Sit on the ground, lean back,
                                    then sit. up.''',
                      video_url="https://www.youtube.com/watch?v=jDwoBqPH0jk")

    crunches = Exercise(title="Crunches",
                        muscle_group="Resistance",
                        difficulty="1",
                        description='''They're like situps,
                                    but this time, CRUNCH IT.''',
                        video_url="https://www.youtube.com/watch?v=Xyd_fa5zoEU")

    lunges = Exercise(title="Lunges",
                      muscle_group='''Resistance''',
                      difficulty="2",
                      description='''Lunge to the right, keeping the left leg
                      straight, shifting the hips over the right foot. Make
                      sure to send the hips back to engage the glutes. At the
                      same time, lift the weight straight up to shoulder level.
                      Lower the weight, go back to start and repeat to the
                      other side.''',
                      video_url="https://www.youtube.com/watch?v=QOVaHwm-Q6U")

    benchPress = Exercise(title="Bench Press",
                          muscle_group="Added Weight",
                          difficulty="3",
                          description="Lift things up and put them down.",
                          video_url="https://www.youtube.com/watch?v=-MAABwVKxok")

    latPulldowns = Exercise(title="Lat Pulldowns",
                            muscle_group="Added Weight",
                            difficulty="2",
                            description="Pull it down and let it go.",
                            video_url="https://www.youtube.com/watch?v=CAwf7n6Luuc")

    dumbBellPress = Exercise(title="Dumbbell Press",
                             muscle_group="Added Weight",
                             difficulty="3",
                             description='''Like bench press, but with
                                        dumbbells.''',
                             video_url="https://www.youtube.com/watch?v=xphvjGDZeYE")

    legExtensions = Exercise(title="Leg Extensions",
                             muscle_group="Added Weight",
                             difficulty="2",
                             description='''The leg press is a compound weight
                             training exercise in which the individual pushes
                             a weight or resistance away from them using their
                             legs. The term leg press machine refers to the
                             apparatus used to perform this exercise.''',
                             video_url="https://www.youtube.com/watch?v=tTbJBUKnWU8")

    bicepCurls = Exercise(title="Bicep Curls",
                          muscle_group="Added Weight",
                          difficulty="2",
                          description="Those guns should be illegal.",
                          video_url="https://www.youtube.com/watch?v=in7PaeYlhrM")

    tricepsPushdowns = Exercise(title="Triceps Pushdowns",
                                muscle_group="Added Weight",
                                difficulty="2",
                                description='''A pushdown is a strength
                                training exercise used for strengthening the
                                triceps muscles. The exercise is completed by
                                pushing an object downward against resistance.
                                This exercise is an example of the primary
                                function of the triceps, extension of the
                                elbow joint.''',
                                video_url="https://www.youtube.com/watch?v=NtsMXK8rxX0")

    tricepsDip = Exercise(title="Tricep Dips",
                          muscle_group="Resistance",
                          difficulty="4",
                          description='''hold your entire body weight up with
                          your arms extended and feet hovering over the floor,
                          ankles crossed. Lower your body until your elbows
                          reach a 90-degree angle before returning to your
                          starting position.''',
                          video_url="https://www.youtube.com/watch?v=6kALZikXxLc")

    bentOverRow = Exercise(title="Bent Over Row",
                           muscle_group="Added Weight",
                           difficulty="2",
                           description="Bend over and row.",
                           video_url="https://www.youtube.com/watch?v=HE5IBnWYEq4")

    squats = Exercise(title="Squats",
                      muscle_group="Added Weight",
                      difficulty="3",
                      description="Bend over.",
                      video_url="https://www.youtube.com/watch?v=U3HlEF_E9fo")

    cleanJerk = Exercise(title="Clean and Jerk",
                         muscle_group="Added Weight",
                         difficulty="5",
                         description='''Do you yell at the gym a lot? Do you
                         want to? If you answered 'yes' to either of those
                         questions, then this is the exercise for you!''',
                         video_url="https://www.youtube.com/watch?v=IcCGLoNqN2U")

    latRaise = Exercise(title="Lat Raise",
                        muscle_group="Added Weight",
                        difficulty="3",
                        description='''Stand or sit with a dumbbell in each
                                    hand at your sides. Keep your back
                                    straight, brace your core, and then slowly
                                    lift the weights out to the side until
                                    your arms are parallel with the floor,
                                    with the elbow slightly bent. Then lower
                                    them back down, again in measured fashion.
                                    ''',
                        video_url="https://www.youtube.com/watch?v=WJm9zA2NY8E")

    overheadDumbbellPress = Exercise(title="Overhead Dumbbell Press",
                                     muscle_group="Added Weight",
                                     difficulty="3",
                                     description='''Stand or sit with a
                                     dumbbell in each hand at your sides. Keep
                                     your back straight, brace your core, and
                                     then slowly lift the weights out to the
                                     side until your arms are parallel with
                                     the floor, with the elbow slightly bent.
                                     Then lower them back down, again in
                                     measured fashion.''',
                                     video_url="https://www.youtube.com/watch?v=M2rwvNhTOu0")

    dumbbellFlys = Exercise(title="Dumbbell Chest Flys",
                            muscle_group="Added Weight",
                            difficulty="3",
                            description='''Lie on a flat surface, whether it’s
                                        the floor or a bench. Hold a dumbbell
                                        in each hand, above you. Your palms
                                        should be facing each other, but the
                                        dumbbells shouldn’t be touching. If
                                        you’re on the floor, then bend at the
                                        knees so that your feet are flat on
                                        the floor. Lower the weight slowly by
                                        opening your arms to either side. Go
                                        as far as comfortable but don’t worry
                                        about going too deep. The magic
                                        happens at the top of the exercise,
                                        not the bottom.''',
                            video_url="https://www.youtube.com/watch?v=QENKPHhQVi4")

    cableCrossover = Exercise(title="Cable Crossover",
                              muscle_group="Added Weight",
                              difficulty="3",
                              description='''Lie on a flat surface, whether
                                            it’s the floor or a bench. Hold a
                                            dumbbell in each hand, above you.
                                            Your palms should be facing each
                                            other, but the dumbbells shouldn’t
                                            be touching. If you’re on the
                                            floor, then bend at the knees so
                                            that your feet are flat on the
                                            floor. Lower the weight slowly by
                                            opening your arms to either side.
                                            Go as far as comfortable but don’t
                                            worry about going too deep. The
                                            magic happens at the top of the
                                            exercise, not the bottom.''',
                              video_url="https://www.youtube.com/watch?v=taI4XduLpTk")

    burpees = Exercise(title="Burpees",
                       muscle_group="Resistance",
                       difficulty="2",
                       description='''Start by standing upright with your feet
                       shoulder-width apart and your arms down at your sides.
                       With your hands out in front of you, start to squat
                       down. When your hands reach the ground, pop your legs
                       straight back into a pushup position. Jump your feet up
                       to your palms by hinging at the waist. Get your feet as
                       close to your hands as you can get, landing them
                       outside your hands if necessary. Stand up straight,
                       bringing your arms above your head and jump. This is
                       one rep. Complete 3 sets of 10 reps as a beginner.''',
                       video_url="https://www.youtube.com/watch?v=qLBImHhCXSw")

    skullCrushers = Exercise(title="Skull Crushers",
                             muscle_group="Added Weight",
                             difficulty="2",
                             description='''Start by standing upright with
                             your feet shoulder-width apart and your arms down
                             at your sides. With your hands out in front of
                             you, start to squat down. When your hands reach
                             the ground, pop your legs straight back into a
                             pushup position. Jump your feet up to your palms
                             by hinging at the waist. Get your feet as close
                             to your hands as you can get, landing them
                             outside your hands if necessary. Stand up
                             straight, bringing your arms above your head and
                             jump. This is one rep. Complete 3 sets of 10 reps
                             as a beginner.''',
                             video_url="https://www.youtube.com/watch?v=VP9Qp72zZ_c")

    jogging = Exercise(title="Running",
                       muscle_group="Cardio",
                       difficulty="1",
                       description='''One foot in front of the other,
                                    really fast.''',
                       video_url="https://www.youtube.com/watch?v=_kGESn8ArrU")

    cycling = Exercise(title="Bicycling",
                       muscle_group="Cardio",
                       difficulty="1",
                       description='''An excuse to wear really, really
                                    tight shorts.''',
                       video_url="https://www.youtube.com/watch?v=4ssLDk1eX9w")

    dayOff = Exercise(id=28,
                      title="Day Off",
                      muscle_group="none",
                      difficulty=0,
                      description="Take a day off, you deserve it!",
                      video_url="https://giphy.com/gifs/southparkgifs-l0HlPtbGpcnqa0fja")

    db.session.add(pushups)
    db.session.add(mountainClimbers)
    db.session.add(pullups)
    db.session.add(planks)
    db.session.add(jumpingJacks)
    db.session.add(squatJumps)
    db.session.add(situps)
    db.session.add(crunches)
    db.session.add(lunges)
    db.session.add(benchPress)
    db.session.add(latPulldowns)
    db.session.add(dumbBellPress)
    db.session.add(legExtensions)
    db.session.add(bicepCurls)
    db.session.add(tricepsPushdowns)
    db.session.add(tricepsDip)
    db.session.add(bentOverRow)
    db.session.add(squats)
    db.session.add(latRaise)
    db.session.add(jogging)
    db.session.add(cycling)
    db.session.add(skullCrushers)
    db.session.add(burpees)
    db.session.add(cableCrossover)
    db.session.add(dumbbellFlys)
    db.session.add(overheadDumbbellPress)
    db.session.add(cleanJerk)
    db.session.add(dayOff)

    db.session.commit()
Example #17
0
        WorkoutPlan(name="Killer Arm", muscle_id=3, description=""),
        WorkoutPlan(name="Stable Core", muscle_id=4, description=""),
        WorkoutPlan(name="Six Pack Shred", muscle_id=4, description=""),
        WorkoutPlan(name="Deadlift Master", muscle_id=5, description=""),
        WorkoutPlan(name="Wings", muscle_id=5, description=""),
    ]

    for workoutplan in workoutplans:
        db.session.add(workoutplan)

    db.session.commit()

    exercises = [
        Exercise(name="Bench Press",
                 workoutplan_id=1,
                 sets=4,
                 reps=8,
                 difficulty="Beginner"),
        Exercise(name="Chest Fly",
                 workoutplan_id=1,
                 sets=3,
                 reps=12,
                 difficulty="Intermediate"),
        Exercise(name="Incline Bench Press",
                 workoutplan_id=1,
                 sets=3,
                 reps=6,
                 difficulty="Advanced"),
        Exercise(name="BodyWeight Push-Ups",
                 workoutplan_id=1,
                 sets=3,
Example #18
0
def add_post():
    post_data = json.loads(request.get_data())
    if 'title' not in post_data:
        return bad_request("A post title is required.")
    else:
        if 'muscle_group' in post_data:
            post = Post(post_data)
            db.session.add(post)
            db.session.commit()
            exercise = Exercise(post_data, post.id)
            db.session.add(exercise)
            db.session.commit()
            response = {
                'post': {
                    'id': post.id,
                    'title': post.title,
                    'description': post.description,
                    'image_url': post.image_url,
                    'user_id': post.user_id,
                    'date': post.date,
                    'post_type': 'exercise',
                    'exercise': {
                        'id': exercise.id,
                        'muscle_group': exercise.muscle_group,
                        'name': exercise.name,
                        'reps': exercise.reps,
                        'weight': exercise.weight,
                        'time': exercise.time,
                        'distance': exercise.distance
                    }
                }
            }
            return jsonify(response)
        elif 'meal' in post_data:
            post = Post(post_data)
            db.session.add(post)
            db.session.commit()
            meal = Meal(post_data, post.id)
            db.session.add(meal)
            db.session.commit()
            foods = post_data['meal']['foods']
            food_obs = []
            for i, x in enumerate(foods, start=0):
                food = Food(foods[i])
                food_obs.append(food)
                db.session.add(food)
                db.session.commit()
                meal.foods.append(food)
                db.session.commit()
            response = {
                'post': {
                    'id': post.id,
                    'title': post.title,
                    'description': post.description,
                    'image_url': post.image_url,
                    'user_id': post.user_id,
                    'date': post.date,
                    'post_type': 'meal',
                    'meal': {
                        'id': meal.id,
                        'name': meal.name,
                        'post_id': meal.post_id,
                        'foods': get_foods(food_obs)
                    }
                }
            }

            return jsonify(response)
        else:
            return bad_request("AHHH! Something went wrong!")
Example #19
0
def seed_exercises(n):
    for i in range(n):
        entry = Exercise(exercise_name=exercises[i])
        db.session.add(entry)
    db.session.commit()