def follow_user(current_user, user_id): """Creates a relationship where the currently logged in user follows the user with id <user_id> """ user = User.query.filter_by(id=user_id).first() if user == None: return jsonify({'error': 'This user does not exist'}) if request.method == 'POST': follower_id = current_user.id pre_existing_relationship = Follow.query.filter_by( follower_id=follower_id, userid=user_id).first() if pre_existing_relationship == None: follow_relationship = Follow(follower_id=follower_id, userid=user_id) print(follow_relationship) db.session.add(follow_relationship) db.session.commit() response = { 'message': 'You are now following that user', 'newRelationship': 'true' } return jsonify(response) else: response = { 'message': 'You are already following that user', 'newRelationship': 'false' } print(response) return jsonify(response)
def fixture(): for i in range(5): user = User("user" + str(i), i, "user" + str(i) + "@ynov.com", "aaaa", "default.png") receive = User("user1" + str(i), i, "user" + str(i) + "@ynov.com", "aaaa", "default.png") db.session.add(user) db.session.add(receive) db.session.commit() follow = Follow(user, receive) db.session.add(follow) db.session.commit() for j in range(5): post = Post("post" + str(i), "vdbziego", "default.png", '2019-01-16 00:00:00', '2019-01-16 00:00:00', user) db.session.add(post) user.like.append(post) commentary = Comment(content="blabla", publication_date='2019-01-16 00:00:00') commentary.post = post user.comment.append(commentary) for k in range(5): message = Message('message' + str(k), '2019-01-16 00:00:00', user, receive) db.session.add(message) return 'fixtures'
def follow(): req_json = request.get_json() following_user_id = req_json.get("user_id") my_user_id = g.get("user_id") my_username = session.get("username") if not following_user_id: return jsonify(re_code=400, msg="参数不完整") try: user = User.query.get(following_user_id) except Exception as e: current_app.logger.error(e) user = None if not user: return jsonify(re_code=400, msg="查询不到当前要关注的用户") try: ip_addr = request.remote_addr # 获取用户的ip operate_detail = "用户id:%r,用户名:%s,关注了id:%r,用户名:%s" % ( my_user_id, my_username, user.id, user.username) user_operate_log = UserOperateLog(user_id=user.id, ip=ip_addr, detail=operate_detail) try_follow = Follow(follower_id=my_user_id, followed_id=following_user_id) db.session.add(user_operate_log) db.session.add(try_follow) db.session.commit() return jsonify(re_code=200, msg="关注用户成功 !") except Exception as e: current_app.logger.error(e) db.session.rollback() return jsonify(re_code=400, msg="数据库失败,关注用户失败,请稍后重试")
def follow_user(user_id): data = request.json print(data) # the person to be followed. Obtaining info from the POST body rather than the route params target_id = data["follower_id"] user_id = getUserID() tar_user = User.query.get(target_id) # ensure the target user exists in the db and that the user isn't trying to follow his/herself if tar_user and target_id != user_id: # check if user is already following target user follow = Follow.query.filter_by(user_id=user_id, follower_id=target_id).first() if follow == None: follow = Follow(user_id, target_id) db.session.add(follow) db.session.commit() return jsonify({"message": "You are now following that user"}) else: # unfollow db.session.delete(follow) db.session.commit() followers = Follow.query.filter_by(follower_id=target_id).count() return jsonify( {"message": "You are no longer following that user"}) # return jsonify({'code': -1, "message": "You are already following that user", 'errors': []}) else: return jsonify({ 'code': -1, 'message': 'Target user does not exist/User cannot follow oneself', 'errors': [] })
def follow(): result = True data = request.get_data().decode('utf-8') data = json.loads(data) follower_id = int(data['follower']) followed_id = int(data['followed']) opt = data['opt'] follower = UserInfo.query.get_or_404(follower_id) followed = UserInfo.query.get_or_404(followed_id) print('=============================================') try: if opt == 'following': follow = Follow(follower=follower,followed=followed) db.session.add(follow) else: f = follower.followed.filter_by(followed_id=followed_id).first() if f: db.session.delete(f) # else: # f = follower.followed.filter(followed_id=followed_id) # db.session.delete(f) except Exception as e: result = False db.session.rollback() print('关注对象时出错 ! ') print(e) return jsonify({'result':result})
def followeReq(followedId): reqData = request.json newFollow = Follow() newFollow.followed_id = followedId newFollow.follower_id = reqData['userId'] db.session.add(newFollow) db.session.commit() return "New followe added"
def follow(user_id): current_user = get_jwt_identity() follower = UserProfile.query.filter_by(username=current_user).first() follower_id = follower.id new_follower = Follow(user_id, follower_id) db.session.add(new_follower) db.session.commit() return jsonify({'message': 'Following'}), 200
def follow(username): user=User.query.filter_by(username=username).first() if user is not None and not current_user.is_following(user): follow=Follow( followed_id=user.id, follower_id=current_user.id ) db.session.add(follow) return redirect(url_for('main.profile',username=username))
def follow_user(user_id): user = g.current_user #adding to the followers database follow = Follow(user_id, user['sub']) db.session.add(follow) db.session.commit() return make_response( jsonify({'message': 'You are now following that user'}), 201)
def article(id): article = Article.query.get_or_404(id) if not article.published: abort(403) next = next_article(article) prev = prev_article(article) form = CommentForm(request.form, follow_id=-1) if form.validate_on_submit(): followed_id = int(form.follow_id.data if form.follow_id.data else -1) reply_to = form.follow.data content = form.content.data if reply_to: content = form.content.data.replace("@" + reply_to + " ", "") comment = Comment(article=article, content=content, author_name=form.name.data, author_email=form.email.data) db.session.add(comment) db.session.commit() if followed_id != -1: followed = Comment.query.get_or_404(followed_id) f = Follow(follower=comment, followed=followed) comment.comment_type = 'reply' # comment.reply_to = followed.author_name comment.reply_to = reply_to if reply_to else followed.author_name db.session.add(f) db.session.add(comment) db.session.commit() # flash(u'提交评论成功!', 'success') return redirect(url_for('.article', id=article.id, page=-1)) # if form.errors: # flash(u'发表评论失败', 'danger') page = request.args.get('page', 1, type=int) counts = article.comments.count() if page == -1: page = int((counts - 1) / Comment.PER_PAGE + 1) pagination = article.comments.order_by(Comment.created.asc()).paginate( page, per_page=Comment.PER_PAGE, error_out=False) comments = pagination.items return render_template('article.html', article=article, category_id=article.category_id, next_article=next, prev_article=prev, comments=comments, counts=counts, pagination=pagination, form=form, endpoint='.article', id=article.id)
def fake_follow(): """Generating some random following relationship.""" user_count = User.query.count() for b in range(500): follower = User.query.offset(randint(0, user_count - 1)).first() followed = User.query.offset(randint(0, user_count - 1)).first() follow_ship = Follow(follower=follower, followed=followed) db.session.add(follow_ship) db.session.commit() return True
def follow(): form = FollowForm() if form.validate_on_submit(): to_follow = Follow(code=form.station_id.data.upper(), text_alert=form.text_alert.data, email_alert=form.email_alert.data, user_id=current_user.id) db.session.add(to_follow) db.session.commit() flash( f'Congratulations, you are now following {form.station_id.data}!') return redirect(url_for('index')) return render_template('follow.html', title='Follow', form=form)
def follow_user(current_user, user_id): """Creates a relationship where the currently logged in user follows the user with id <user_id> """ user = User.query.filter_by(id=user_id).first() if user == None: return jsonify({'error': 'This user does not exist'}) if request.method == 'POST': follower_id = current_user.id follow_relationship = Follow(follower_id=follower_id, userid=user_id) db.session.add(follow_relationship) db.session.commit() response = {'follower_id': follower_id, 'user_id': user_id} return jsonify(response) return jsonify_errors(['Only POST requests are accepted'])
def seed_follows(): follow1 = Follow(followee_id=1, follower_id=2) follow2 = Follow(followee_id=1, follower_id=3) follow3 = Follow(followee_id=1, follower_id=4) follow4 = Follow(followee_id=2, follower_id=1) follow5 = Follow(followee_id=2, follower_id=4) follow6 = Follow(followee_id=3, follower_id=4) follow7 = Follow(followee_id=4, follower_id=3) db.session.add(follow1) db.session.add(follow2) db.session.add(follow3) db.session.add(follow4) db.session.add(follow5) db.session.add(follow6) db.session.add(follow7) db.session.commit()
def test_followed_posts(self): user1 = User(email="*****@*****.**", username="******", password="******") user2 = User(email="*****@*****.**", username="******", password="******") db.session.add(user1) db.session.add(user2) db.session.commit() post = Post(title="test", body="test") post.user = user2 db.session.add(post) db.session.commit() follow = Follow(follower_id=user1.id, followed_id=user2.id) db.session.add(follow) db.session.commit() res = self.open_with_auth("api/followedposts", "get", "test1", "test") self.assertTrue(res["all_posts"] == 1)
def follow(user_id): form = FollowForm() if form.validate_on_submit(): follower_id = form.follower_id.data follow = Follow(user_id, follower_id) try: db.session.add(follow) db.session.commit() response = {'message': 'You are now following that user.'}, 200 except: response = {'errors': ['You are already following that user.']}, 400 else: response = {'errors': form_errors(form)}, 400 return jsonify(response[0]), response[1]
def follow(): session_user_id = request.json['session_user_id'] follow_user_id = request.json['follow_user_id'] following = request.json['following'] if following: old_follow = Follow.query \ .filter(Follow.follower_id == session_user_id, Follow.followee_id == follow_user_id) \ .first() db.session.delete(old_follow) db.session.commit() return old_follow.to_dict() else: new_follow = Follow(follower_id=session_user_id, followee_id=follow_user_id) db.session.add(new_follow) db.session.commit() return new_follow.to_dict()
def test_user_follow(self): user1 = User(email="*****@*****.**", username="******", password="******") user2 = User(email="*****@*****.**", username="******", password="******") db.session.add(user1) db.session.add(user2) db.session.commit() follow = Follow(follower_id=user1.id, followed_id=user2.id) db.session.add(follow) db.session.commit() res = self.client.get("api/user/" + str(user2.username) + "/followers") res = json.loads(res.data) self.assertTrue(res["all_users"] == 1) res = self.client.get("api/user/" + str(user1.username) + "/followings") res = json.loads(res.data) self.assertTrue(res["all_users"] == 1)
def contact(): form = CommentForm(request.form, follow_id=-1) if form.validate_on_submit(): followed_id = int(form.follow_id.data if form.follow_id.data else -1) reply_to = form.follow.data content = form.content.data if reply_to: content = form.content.data.replace("@" + reply_to + " ", "") comment = Comment(content=content, author_name=form.name.data, author_email=form.email.data, comment_type='contact') db.session.add(comment) db.session.commit() if followed_id != -1: followed = Comment.query.get_or_404(followed_id) f = Follow(follower=comment, followed=followed) comment.comment_type = 'reply' # comment.reply_to = followed.author_name comment.reply_to = reply_to if reply_to else followed.author_name db.session.add(f) db.session.add(comment) db.session.commit() # flash(u'提交评论成功!', 'success') return redirect(url_for('.contact', page=-1)) page = request.args.get('page', 1, type=int) _query = Comment.query.filter_by(comment_type='contact') counts = _query.count() if page == -1: page = int((counts - 1) / Comment.PER_PAGE + 1) pagination = _query.order_by(Comment.created.asc()).paginate( page, per_page=Comment.PER_PAGE, error_out=False) comments = pagination.items return render_template('contact.html', comments=comments, counts=counts, pagination=pagination, form=form, endpoint='.contact')
def addFollow(current_user, sk_id): newFollow = Follow(sketchbook_id=sk_id, follower_id=current_user.id) db.session.add(newFollow) db.session.commit() returnDict = {newFollow.sketchbook_id: True} return returnDict
def unsubscribe(user_id): follow = Follow(FollowerID=current_user.UserID, BeFollowedID=user_id) db.session.delete(follow) db.session.commit() return ""
def following(id=None): if not (current_user.is_authenticated): return redirect(url_for('main.login')) route = 0 url = request.url_rule if str(url) == "/profil/following": route = 3 elif id != None: route = 4 userLog = current_user button = [] followerUserLog = Follow.query.filter_by(follower_id=userLog.id).all() if id == None: followers = Follow.query.filter_by(followby_id=userLog.id).all() for follower in followers: status = False for followerUser in followerUserLog: if follower.follower_id == followerUser.followby_id: button.append({ 'followBy': follower.follower_id, 'value': 0 }) status = True if status == False: button.append({'followBy': follower.follower_id, 'value': 1}) else: user = User.query.filter_by(id=id).first() followers = Follow.query.filter_by(followby_id=user.id).all() followerUserLog = Follow.query.filter_by(follower_id=userLog.id).all() for follower in followers: status = False if follower.follower_id == userLog.id: button.append({'followBy': follower.follower_id, 'value': 2}) status = True for followerUser in followerUserLog: print(followerUser.follower_id) print(followerUser.followby_id) if follower.follower_id == followerUser.followby_id and status == False: button.append({ 'followBy': follower.follower_id, 'value': 0 }) status = True if status == False: button.append({'followBy': follower.follower_id, 'value': 1}) if request.method == 'POST': unfollowUser = request.form.get('unfollowUser') followUser = request.form.get('followUser') if unfollowUser != None: userLogUnFollow = Follow.query.filter_by( followby_id=unfollowUser, follower_id=userLog.id).first() db.session.delete(userLogUnFollow) else: userFollow = User.query.filter_by(id=followUser).first() following = Follow(userLog, userFollow) db.session.add(following) db.session.commit() return redirect(url_for('main.following', id=id)) return render_template('pages/user/follow.html', followers=followers, id=id, userLog=userLog, button=button, route=route, currentUser=current_user)
def profil(id=None): if not (current_user.is_authenticated): return redirect(url_for('main.login')) userLog = current_user URL_ROOT = request.url_root error = None follow = 0 if (id == None): # user connecter url = URL_ROOT + 'api/post/user/' + str(userLog.id) user = User.query.filter_by(id=userLog.id).first() if request.method == 'POST': username = request.form.get('username') age = request.form.get('age') avatar = request.files.get('avatar') print(avatar) if username != None: if username == "": error = "vous n'avez pas mis votre username" elif age == "": error = "vous n'avez pas mis votre age" else: if avatar != "": resp = uploadImage(avatar, user) if resp: user.avatar = avatar.filename else: error = "l'image n'a pas été envoyer car ce n'est pas une image" user.username = username user.age = age db.session.commit() elif id == userLog.id: return redirect(url_for('main.profil', id=None)) else: url = URL_ROOT + 'api/post/user/' + str(id) user = User.query.filter_by(id=id).first() follow = Follow.query.filter_by(follower_id=userLog.id, followby_id=id).first() if not (follow): follow = 1 if request.method == 'POST': if follow == 1: following = Follow(userLog, user) db.session.add(following) else: db.session.delete(follow) following = Follow.query.filter_by(follower_id=user.id).count() followers = Follow.query.filter_by(followby_id=user.id).count() numberPosts = Post.query.filter_by(user_id=user.id).count() stats = { "followers": followers, "following": following, "posts": numberPosts } if request.method == 'POST': post = request.form.get('post') if post != None: postDelete = Post.query.filter_by(id=post).first() postDelete.like = [] db.session.commit() commentDelete = Comment.query.filter_by(id=post).all() for comment in commentDelete: db.session.delete(comment) db.session.delete(postDelete) db.session.commit() return redirect(url_for('main.profil', id=id)) response = requests.get(url) user = response.json() return render_template('pages/user/profil.html', stats=stats, error=error, id=id, user=user, follow=follow, userLog=userLog, currentUser=current_user)
user3 = User( username='******', hashed_password= '******', email='*****@*****.**', bio='I am a professional photographer', ) user4 = User( username='******', hashed_password= '******', email='*****@*****.**', bio='hi im a guest! ', ) f1 = Follow( follower=user1, followed=user2, ) f2 = Follow( follower=user2, followed=user1, ) f3 = Follow(follower=user4, followed=user1) f4 = Follow( follower=user4, followed=user2, ) f5 = Follow( follower=user4, followed=user3, )