def follow(user_id): """create a follow relationship between the current user and the target user.""" if request.method == 'POST': target_user = int(request.form['user_id']) current_user = int(request.form['follower_id']) follows = UserFollows.query.filter_by(user_id=target_user).all() check = '' for follow in follows: if current_user == follow.follower_id: check = 1 if check != 1: follow = UserFollows(target_user, current_user) db.session.add(follow) db.session.commit() user = UserProfile.query.filter_by(id=target_user).first() msg = "You are now following that user." + user.username numfollow = len( UserFollows.query.filter_by(user_id=target_user).all()) return jsonify(response=[{"message": msg, "follow": numfollow}]) else: numfollow = len( UserFollows.query.filter_by(user_id=target_user).all()) return jsonify(response=[{ "message": "You are already following that user.", "follow": numfollow }]) else: return jsonify(errors=[{'error': 'unable to create link'}])
def follow(userid): if request.method == 'POST': current = current_user target = UserProfile.query.filter_by(id = userid).first() if target is not None: new_follow_relationship = UserFollows(current.id,target.id) db.session.add(new_follow_relationship) db.session.commit() er = None msg ="{} is now following {}".format(current.user_name,target.user_name) return jsonify(error=er,message=msg),202 else: er = True msg ="Target user doesn't exists" return jsonify(error=er,message=msg),404 else: abort(405)
def follow(userid): if request.method == 'POST': current = current_user target = UserProfile.query.filter_by(id=userid).first() if target is not None: new_follow_relationship = UserFollows(current.id, target.id) db.session.add(new_follow_relationship) db.session.commit() er = None msg = "{} is now following {}".format(current.user_name, target.user_name) return jsonify(error=er, message=msg), 202 else: er = True msg = "Target user doesn't exists" return jsonify(error=er, message=msg), 404 elif request.method == 'PUT': current = current_user target = UserProfile.query.filter_by(id=userid).first() if target is not None: def check_if_currentuser_is_following(current, target): follows = UserFollows.query.all() for follow in follows: if follow.user_id == current.id and follow.follow_id == target.id: db.session.delete(follow) db.session.commit() return True return False if check_if_currentuser_is_following(current, target): er = None msg = "{} has unfollowed {}".format(current.user_name, target.user_name) return jsonify(error=er, message=msg), 202 else: er = True msg = "{} is not following {}, so he/she can't unfollow {}".format( current.user_name, target.user_name, target.user_name) return jsonify(error=er, message=msg), 202 else: er = True msg = "Target user doesn't exists" return jsonify(error=er, message=msg), 404 else: abort(405)
def follow(userid): if request.method == 'POST': current = current_user if target is not None: if target is not None: new_follow_relationship = UserFollows(current.id,target.id) db.session.add(new_follow_relationship) db.session.commit() er = None msg ="{} is now following {}".format(current.user_name,target.user_name) return jsonify(error=er,message=msg),202 else: er = True msg ="Target user doesn't exists" return jsonify(error=er,message=msg),404 else: abort(405) @app.route('/api/posts/<int:postid>/like', methods=['POST']) def like(postid): if request.method == 'POST': user = current_user post = UserPosts.query.filter_by(id = postid).first() def check_if_user_liked_already(user,post): likes = UserLikes.query.all() for like in likes: if like.user_id == user.id and like.post_id == post.id: return True return False if post is not None: if check_if_user_liked_already(user,post): er =True msg = "{} already likes this post".format(user.user_name) return jsonify(error=er,message=msg),403 new_like = UserLikes(user.id,post.id) db.session.add(new_like) db.session.commit() er=None msg ="{} liked this post".format(user.user_name) return jsonify(error=er,message=msg),202 else: er=True msg ="Invalid post id" return jsonify(error=er,message=msg),404 else: abort(405) #returns user's information @app.route('/api/u/<int:id>', methods=['GET','POST']) def userInfo(id): if request.method == 'GET': user = UserProfile.query.filter_by(id = id).first() if user is not None: posts_count = UserPosts.query.filter_by(user_id=id).count() follower_count = UserFollows.query.filter_by(follow_id=id).count() following_count = UserFollows.query.filter_by(user_id=id).count() userData = { 'id': user.id, 'email': user.email, 'username': user.user_name, 'gender': user.gender, 'firstname': user.first_name, 'lastname': user.last_name, 'location': user.location, 'bio': user.biography, 'profile_pic': user.pic, 'joined': user.joined_on, 'follower_count': follower_count, 'following_count':following_count, 'posts_count':posts_count } er = None msg= "Info for {} successfully fetched".format(user.user_name) return jsonify(error=er, message=msg , user_info = [userData]) else: er = True msg= "User doesn't exist" return jsonify(error=er,message=msg),404 else: abort(405) #checks if the current user is following a specific user @app.route('/api/users/follows/<int:id>',methods=['GET','POST']) def followChecker(id): current = current_user target_user = UserProfile.query.filter_by(id = id).first() if target_user is None: er=True msg="Target user with the id {} doesn't exist".format(id) return jsonify(error=er,message=msg),404 if current.id == target_user.id: er=True msg="A User cannot follow themselves" current_following_target = False return jsonify(error=er,message=msg,current_following_target=current_following_target) def check_if_currentuser_is_following(current,target): follows = UserFollows.query.all() for follow in follows: if follow.user_id == current.id and follow.follow_id == target.id: return True return False current_following_target= check_if_currentuser_is_following(current,target_user) er=None msg="Follow status successfully fetched" return jsonify(error=er,message=msg,current_following_target=current_following_target) @app.route('/token') def generate_token(): payload = r token = jwt.encode(payload, 'some-secret', algorithm='HS256') return jsonify(error=None, data={'token': token}, message="Token Generated") ### # The functions below should be applicable to all Flask apps. ### def form_errors(form): error_messages = [] """Collects form errors""" for field, errors in form.errors.items(): for error in errors: message = u"Error in the %s field - %s" % ( getattr(form, field).label.text, error ) error_messages.append(message) return error_messages def format_date_joined(d): return d.strftime("%d %b, %Y"); def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.headers.get('Authorization', None) if not auth: return jsonify({'code': 'authorization_header_missing', 'description': 'Authorization header is expected'}), 401 parts = auth.split() if parts[0].lower() != 'bearer': return jsonify({'code': 'invalid_header', 'description': 'Authorization header must start with Bearer'}), 401 elif len(parts) == 1: return jsonify({'code': 'invalid_header', 'description': 'Token not found'}), 401 elif len(parts) > 2: return jsonify({'code': 'invalid_header', 'description': 'Authorization header must be Bearer + \s + token'}), 401 token = parts[1] try: payload = jwt.decode(token, 'some-secret') except jwt.ExpiredSignature: return jsonify({'code': 'token_expired', 'description': 'token is expired'}), 401 except jwt.DecodeError: return jsonify({'code': 'token_invalid_signature', 'description': 'Token signature is invalid'}), 401 g.current_user = user = payload return f(*args, **kwargs) return decorated @login_manager.user_loader def load_user(id): return db.session.query(UserProfile).get(int(id)) @app.route('/<file_name>.txt') def send_text_file(file_name): """Send your static text file.""" file_dot_text = file_name + '.txt' return app.send_static_file(file_dot_text) @app.after_request def add_header(response): """ Add headers to both force latest IE rendering engine or Chrome Frame, and also tell the browser not to cache the rendered page. If we wanted to we could change max-age to 600 seconds which would be 10 minutes. """ response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1' response.headers['Cache-Control'] = 'public, max-age=0' return response @app.errorhandler(404) def page_not_found(error): """Custom 404 page.""" return render_template('404.html'), 404 @app.errorhandler(405) def method_not_allowed(error): """Custom 405 page.""" return render_template('405.html'), 405 if __name__ == '__main__': app.run(debug=True, host="0.0.0.0", port="8080")
def create_follow(user_id): follow = UserFollows(user_id = user_id, follower_id=session['user_id']) db.session.add(follow) db.session.commit() return jsonify (message= 'You followed a user')