def subscribe(request): """ Subscribe or unsubscribe to/from user """ subscribeForm = SubscribeForm(request.POST) if subscribeForm.is_valid(): followed_user = get_object_or_404(User, id=subscribeForm.cleaned_data['followed']) if subscribeForm.cleaned_data['is_subscribed']: if Follow.unsubscribe(request.user, followed_user): request.user.message_set.create( message=_('Unsubscribed from user %(username)s' % {'username': followed_user.username})) else: if Follow.subscribe(request.user, followed_user): request.user.message_set.create( message=_('Subscribed to user %(username)s' % {'username': followed_user.username})) return redirect('pythonica-profile', username=followed_user.username) else: return HttpResponseBadRequest()
def create(user_id): user = User[user_id] follow = Follow(follower_id=current_user.id, idol_id=user_id, approved=False if user.is_private else True) if follow.save(): return redirect(url_for('users.show', username=user.username)) else: return redirect(url_for('home'))
def followUser(request,*,page='1',followed_user): follow = Follow(user_Id=request.__user__.id,followed_user=followed_user,status=1) yield from follow.save() fans = Fans(user_Id=followed_user,follower_user=request.__user__.id,status=1) yield from fans.save() return dict(follow=follow)
def unfollow_act(user_id): user_now = current_user() u = User.query.filter_by(id=user_id).first() f = Follow().query.filter_by(user_id=user_now.id, followed_id=user_id).first() f.delete() log('取消关注成功') fan_follow_count(user_now) return redirect(url_for('timeline_view', username=u.username))
def users_follow(request, *args, **kwargs): try: username = kwargs.get('slug', '') friend = get_object_or_404(User, username=username) follow = Follow(from_user=request.user, to_user=friend) follow.save() messages.info(request, 'You are now following %s' % friend.username) except IntegrityError: messages.info(request, 'You are already following %s' % friend.username) return HttpResponseRedirect(reverse('profiles_profile_detail', args=[friend.username]))
def follow_act(user_id): user_now = current_user() if user_now is None: return redirect(url_for('login_view')) else: u = User.query.filter_by(id=user_id).first() f = Follow() f.user_id = user_now.id f.followed_id = user_id f.save() log('关注成功') fan_follow_count(user_now) return redirect(url_for('timeline_view', username=u.username))
def get_follows(self, channel_name, limit=25, offset=0, direction='desc'): """ Returns list of follow objects for specific channel :param channel_name: Name of the channel :param limig: Maximum number of objects in array :param offset: Offset for pagination :param direction: Creation date sorting direction. Valid values are `asc` and `desc` """ params = { 'limit': limit, 'offset': offset, 'direction': direction } data = self._get( 'channels/{0}/follows'.format(channel_name), params=params ) follows = [] for entry in data['follows']: follow = Follow.object_from_dict(entry) follows.append(follow) return follows
def relation_status(user_Id): sql = " ".join(['SELECT f1.status AS status1,f2.status AS status2 FROM follow f1,follow f2', 'WHERE f1.user_id = f2.followed_user AND f1.followed_user = f2.user_id' "AND f1.user_id = '%s'"%user_Id]) follow = yield from Follow.unionSelect(sql) print (follow) return follow
def resolve_following(source, info): if source.followee_set: return [follow.followee for follow in source.followee_set] return [ follow.followee for follow in Follow.select().where(Follow.follower == source.id) ]
def destroy(user_id): user = User[user_id] follow = Follow.get(follower_id=current_user.id, idol_id=user_id) if follow.delete_instance(): return redirect(url_for('users.show', username=user.username)) else: return redirect(url_for('home'))
def profile(request, username, is_logged_in, page=1): """ show user info and user timeline """ try: list_owner = User.objects.get(username=username) except User.DoesNotExist: raise Http404 q_public = Q(is_restricted=False) q_own = Q(author=list_owner) notices = Notice.objects.filter(q_own) if not is_logged_in or request.user != list_owner: notices = notices.filter(q_public) notices = Paginator(notices, 10) is_subscribed = (is_logged_in and Follow.is_subscribed(request.user, list_owner)) subscribeForm = SubscribeForm( initial={'followed': list_owner.id, 'is_subscribed': is_subscribed}) is_blocked = is_logged_in and Block.is_blocked(request.user, list_owner) blockForm = BlockForm( initial={'blocked': list_owner.id, 'is_blocked': is_blocked}) return {'list_owner': list_owner, 'notices': notices.page(page), 'is_subscribed': is_subscribed, 'subscribe_form': subscribeForm, 'is_blocked': is_blocked, 'block_form': blockForm}
def add_follow(): """Add an item to follow""" if not g.user: flash("You must log in to access that page.", "danger") return redirect("/login") form = AddFollow() if form.validate_on_submit(): name = form.name.data category = form.category.data sportsdb_id = form.sportsdb_id.data tb_image = form.tb_image.data if form.tb_image.data else "/static/img/isports-default.png" if category == "league": tb_image = isports.get_league_image(sportsdb_id) follow = Follow(name=name, category=category, user_id=g.user.id, sportsdb_id=sportsdb_id, tb_image=tb_image) db.session.add(follow) db.session.commit() else: flash("Invalid input! Select an item from the list.", "danger") return redirect(f"/user")
def test_is_followed_by(self): """Is this user followed by other user?""" follow = Follow(followee=self.u2.id, follower=self.u1.id) db.session.add(follow) db.session.commit() self.assertEqual(self.u2.is_followed_by(self.u1), True) self.assertEqual(self.u1.is_followed_by(self.u2), False)
def post(self): data = request.get_json() print("follow data",data) rec = Follow(following = data["following"], follower = data["follower"], follow_date = datetime.datetime.now()) db.session.add(rec) db.session.commit() return { "message": "{} is now following to {}".format(data["following"],data["follower"])}
def test_invalid_name(self): follow = Follow( name=None, sportsdb_id="34146370", category="player", tb_image= "https://www.thesportsdb.com/images/media/player/thumb/rgevg81516994688.jpg" ) self.u1.follows.append(follow) with self.assertRaises(exc.IntegrityError) as context: db.session.commit()
def userFollow(): uid = int(request.form.get('uid')) follow_id = int(request.form.get('follow_id')) following = User.query.filter_by(id=uid).first() #粉丝 followed = User.query.get(follow_id) #明星 following.follow_num = following.follow_num + 1 #粉丝数和关注数个加一,插入fans和follow followed.fans_num = followed.fans_num + 1 follow = Follow(uid=uid, followed_id=follow_id) fans = Fans(uid=follow_id, fans_id=uid) try: db.session.add_all([fans, follow]) db.session.commit() return (jsonify({'static': 1})) except Exception as e: print(e) return (jsonify({'statir': 0}))
def test_follow_model(self): """Does basic model work?""" follow = Follow( name="Lionel Messi", user_id=self.u1.id, sportsdb_id="34146370", category="player", tb_image= "https://www.thesportsdb.com/images/media/player/thumb/rgevg81516994688.jpg" ) db.session.add(follow) db.session.commit() # User should have one follow self.assertEqual(len(self.u1.follows), 1)
def test_valid_follow(self): """Does creating a follow work?""" follow = Follow( name="Lionel Messi", sportsdb_id="34146370", category="player", tb_image= "https://www.thesportsdb.com/images/media/player/thumb/rgevg81516994688.jpg" ) self.u1.follows.append(follow) db.session.commit() test_id = follow.id test_follow = Follow.query.get(test_id) self.assertEqual(test_follow.name, "Lionel Messi") self.assertEqual(test_follow.user_id, self.u1.id)
def follow_user(user_id, follower_id): if user_id_in_db(user_id) and user_id_in_db(follower_id): exists = db.session.query(Follow).filter(Follow.user_id==user_id, Follow.follower_id==follower_id).first() is not None if not exists: db.session.add(Follow(user_id=user_id, follower_id=follower_id, follow_date=datetime.date.today())) follow_id = db.session.query(Follow.id).filter_by(user_id=user_id, follower_id=follower_id).first() db.session.add(Activity(user_id=follower_id, action_id=6, object_id=5, date_created=datetime.datetime.now(), target_id=user_id)) db.session.commit() return make_response(jsonify({"success" : "Followed user", "data" : follow_id}), 200) else: return make_response(jsonify({"error" : "Follow relationship already exists"}), 400) else: return make_response(jsonify({"error" : "Invalid user"}), 400)
def follow(username): if 'username' not in session: return redirect(url_for('signin')) follower = User.query.filter_by(username=session['username']).first() try: followed = User.query.filter_by(username=username).first() except: return 'no such user exists ===(' if Follow.query.filter((Follow.follower_username==session['username']) & (Follow.followed_username==username)).count() >= 1: return 'you can\'t follow the same guy twice dude..' else: add_follower = Follow(username, session['username'], followed.id, follower.id) db.session.add(add_follower) db.session.commit() return jsonify({'success': 'true'})
def get(self): user_id = int(self.get_cookie('user_id')) follow_id = int(self.get_argument('follow_id')) #定义数据类型 session = Session() follow = Follow(user_id=user_id, follow_id=follow_id, created=datetime.datetime.now()) session.add(follow) try: session.commit() except (IntegrityError, err.IntegrityError): session.rollback() session.query(Follow).get((user_id, follow_id)).status = True session.commit() return self.redirect('/user/info?user_id=%s' % follow_id)
def test_delete_follow_not_logged_in(self): """Can you delete a follow when not logged in?""" follow = Follow(name="Lionel Messi", sportsdb_id="34146370", category="player", tb_image="https://www.thesportsdb.com/images/media/player/thumb/rgevg81516994688.jpg") self.testuser.follows.append(follow) db.session.commit() test_id = follow.id with self.client as c: resp = c.post(f"/follow/{test_id}/delete", follow_redirects=True) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code, 200) self.assertIn('You must log in to access that page.', html) follow = Follow.query.get(test_id) self.assertIsNotNone(follow)
def test_delete_follow(self): """Can user delete a follow?""" follow = Follow(name="Lionel Messi", sportsdb_id="34146370", category="player", tb_image="https://www.thesportsdb.com/images/media/player/thumb/rgevg81516994688.jpg") self.testuser.follows.append(follow) db.session.commit() test_id = follow.id with self.client as c: with c.session_transaction() as sess: sess[CURR_USER_KEY] = self.testuser.id resp = c.post(f"/follow/{test_id}/delete", follow_redirects=True) self.assertEqual(resp.status_code, 200) follow = Follow.query.get(test_id) self.assertIsNone(follow)
def follow_user(id): user_id = g.user.id session = db_session() follow = Follow(follow_id=id, follower_id=user_id) existed_follow = session.query(Follow).filter(Follow.follow_id == id, Follow.follower_id == user_id).first() code = 1 message = "操作成功" if existed_follow is None: session.add(follow) else: session.delete(existed_follow) try: session.commit() except IntegrityError: print "error" code = 0 message = "用户不存在" session.rollback() finally: session.close() return jsonify(generate_return_info(code, message))
def module001_follow(): form = FollowForm() unfollow = False if request.method == 'POST': if form.validate_on_submit(): course_code = form.code.data follow = Follow.query.filter( and_(Follow.course_code == form.code.data, Follow.user_id == current_user.id)).first() if follow: flash("You are already following the course {} ".format( course_code)) else: course = Course.query.filter_by(code=form.code.data).first() if not course: flash( 'The code {} is invalid, try again with the correct code.' .format(form.code.data)) else: follow = Follow(user_id=current_user.id, course_id=course.id, course_code=course.code, course_name=course.name, institution_name=course.institution_name) try: db.session.add(follow) db.session.commit() flash("You are now following {}".format(course.name)) except: db.session.rollback() flash("Error following!") elif ('sharedlink' in request.args): form = FollowForm(code=request.args.get('code')) follows = Follow.query.filter_by(user_id=current_user.id) return render_template('module001_follow.html', module="module001", form=form, rows=follows, unfollow=unfollow)
def get(self): # 获取参数 user_id = int(self.get_cookie('user_id')) follow_id = int(self.get_argument('follow_id')) # 定义数据模型 follow = Follow(user_id=user_id, follow_id=follow_id, created=datetime.datetime.now()) # 插入数据 session = Session() session.add(follow) try: session.commit() # 提交修改 except (IntegrityError, err.IntegrityError): session.rollback() # 回滚之前的操作 # 数据有冲突,说明用户重复提交关注,或者用户想将“取消关注”的状态重新修改为“关注” session.query(Follow).get((user_id, follow_id)).status = True session.commit() # 跳回用户信息页 return self.redirect('/user/info?user_id=%s' % follow_id)
def setUp(self): """Create test client, add sample data.""" User.query.delete() Follow.query.delete() Favorite.query.delete() self.client = app.test_client() self.testuser = User.signup(username="******", email="*****@*****.**", password="******") db.session.commit() self.follow = Follow( name="Lionel Messi", sportsdb_id="34146370", category="player", tb_image= "https://www.thesportsdb.com/images/media/player/thumb/rgevg81516994688.jpg" ) self.fav = Favorite( title= "Bundesliga droht TV-Blackout am ersten Spieltag des Re-Starts - Digitalfernsehen.de", url= "https://www.digitalfernsehen.de/news/medien-news/maerkte/bundesliga-droht-tv-blackout-am-ersten-spieltag-des-re-starts-556301/", image_url= "https://www.digitalfernsehen.de/wp-content/uploads/2019/11/Testbild.jpg", published_at="2020-05-15T17:17:28Z") self.testuser.follows.append(self.follow) self.testuser.favorites.append(self.fav) db.session.commit()
def accept(user_id): follow = Follow.get(idol_id=current_user.id, follower_id=user_id) follow.approved = True follow.save() return jsonify({"success": True}), 200
def decline(user_id): follow = Follow.get(idol_id=current_user.id, follower_id=user_id) follow.delete_instance() return jsonify({"success": True}), 200
def followedUser(request,*,page=1): if request.__user__ is not None: user_Id = request.__user__.id # sql = " ".join(['SELECT u.*,f.followed_user FROM follow f ', # 'LEFT JOIN users u ON f.followed_user = u.id', # "WHERE f.user_id ='%s'"%user_Id, # "and f.status=1"]) # follows = yield from Follow.unionSelect(sql) # sql = " ".join(['SELECT f1.status AS status1,f2.status AS status2 FROM follow f1,follow f2', # 'WHERE f1.user_id = f2.followed_user AND f1.followed_user = f2.user_id', # "AND f1.user_id = '%s'"%user_Id]) # follow_relation = yield from Follow.unionSelect(sql) page_index = get_page_index(page) num = yield from Follow.findNumber('count(id)',"user_id=? and status=?",[user_Id,1]) page = Page(num,page_index) newFollows = [] sql = " ".join(['SELECT u.*,f1.user_id,f1.followed_user,f1.status AS status1,f2.status AS status2 FROM follow f1', 'LEFT JOIN follow f2 ON f1.user_id = f2.followed_user AND f1.followed_user = f2.user_id', 'LEFT JOIN users u ON f1.followed_user = u.id', "WHERE f1.user_id = '%s'"%user_Id, 'LIMIT %s,%s'%(page.offset, page.limit)]) follows = yield from Follow.unionSelect(sql) for index,follow in enumerate(follows): newFollow = {} newFollow['index']= index newFollow['user_id'] = follow.id newFollow['user_name'] = follow.name newFollow['avatar_url'] = follow.avatar sql2 = " ".join(['SELECT u.* FROM users u WHERE id IN(SELECT t1.followed_user FROM', '(SELECT user_Id,followed_user FROM follow', "WHERE user_id = '%s'"%user_Id, ')AS t1 INNER JOIN' '(SELECT user_Id,followed_user FROM follow', "WHERE user_id = '%s'"%follow.followed_user, ')AS t2', 'ON t1.followed_user = t2.followed_user) AND u.`status` = 1']) followInfos = yield from Follow.unionSelect(sql2) if(len(followInfos) >0): newFollow['cf_count'] = len(followInfos) newFollow['cf_info'] = followInfos[0].name newFollow['followed_user'] = followInfos[0].id else: newFollow['cf_count'] = 0 newFollow['cf_info'] = '' newFollow['followed_user'] = '******' if follow.status1 == '1' and follow.status2 == '1': relation_status = 2 is_followed = True is_following = True elif follow.status1 == '0' and follow.status2 == '1': relation_status = 1 is_followed = False is_following = True elif follow.status1 == '1' and (follow.status2 == '0' or follow.status2 == None): relation_status = 1 is_followed = True is_following = False else: relation_status = 0 is_followed = False is_following = False newFollow['is_followed'] = is_followed newFollow['is_following'] = is_following newFollow['relation_status'] = relation_status newFollows.append(newFollow) return { '__template__': 'user/follow.html', 'page':page, 'follows': newFollows } #return dict(data=newFollows) else: return web.HTTPFound('/signin')
def test_api(db_connection): u1 = User.create(username="******") u2 = User.create(username="******") u3 = User.create(username="******") u4 = User.create(username="******") u5 = User.create(username="******") u6 = User.create(username="******") u7 = User.create(username="******") Follow.create(follower=u1, followee=u2) Follow.create(follower=u1, followee=u3) Follow.create(follower=u1, followee=u4) Follow.create(follower=u2, followee=u1) Follow.create(follower=u2, followee=u6) Follow.create(follower=u3, followee=u2) Follow.create(follower=u4, followee=u3) Follow.create(follower=u4, followee=u5) Follow.create(follower=u5, followee=u1) Follow.create(follower=u6, followee=u2) Follow.create(follower=u6, followee=u3) Follow.create(follower=u6, followee=u7) Follow.create(follower=u7, followee=u1) Follow.create(follower=u7, followee=u2) p1 = Post.create(author=u2, content="lorem ipsum") p2 = Post.create(author=u3, content="dolorum") p3 = Post.create(author=u6, content="foo bar") Like.create(user=u1, post=p1) Like.create(user=u1, post=p2) Like.create(user=u1, post=p3) schema = Schema(query=Query) query = """ { users(usernames: ["user1"]) { username, following { username followers { username } } likes { author { username } content } } posts { content } } """ result = schema.execute(query) assert result.data == { u"users": [{ u"following": [ { u"followers": [ { u"username": u"user1" }, { u"username": u"user3" }, { u"username": u"user6" }, { u"username": u"user7" }, ], u"username": u"user2", }, { u"followers": [ { u"username": u"user1" }, { u"username": u"user4" }, { u"username": u"user6" }, ], u"username": u"user3", }, { u"followers": [{ u"username": u"user1" }], u"username": u"user4" }, ], u"likes": [ { u"author": { u"username": u"user2" }, u"content": u"lorem ipsum" }, { u"author": { u"username": u"user3" }, u"content": u"dolorum" }, { u"author": { u"username": u"user6" }, u"content": u"foo bar" }, ], u"username": u"user1", }], u"posts": [ { u"content": u"lorem ipsum" }, { u"content": u"dolorum" }, { u"content": u"foo bar" }, ] } assert db_connection.queries_executed == 2
def follow(username): try: Follow.new(username, session['username']) except ValueError: # already following flash("You're already following that user!!!\n") return redirect(url_for('user_profile', username=username))
published_at="2020-05-15T17:17:28Z", user_id=u1.id) f2 = Favorite( title= "BVB: Stadt Dortmund und Polizei planen Meisterfeier trotz Corona - SPORT1", url= "https://www.sport1.de/fussball/bundesliga/2020/05/bvb-stadt-dortmund-und-polizei-planen-meisterfeier-trotz-corona", image_url= "https://reshape.sport1.de/c/t/12FD2190-55F9-49DC-A6AA-4B4CBE75A436/1200x630", published_at="2020-05-15T17:20:00Z", user_id=u1.id) follow1 = Follow( name="Lionel Messi", user_id=u1.id, sportsdb_id="34146370", category="player", tb_image= "https://www.thesportsdb.com/images/media/player/thumb/rgevg81516994688.jpg" ) follow2 = Follow( name="Barcelona", user_id=u1.id, sportsdb_id="133739", category="team", tb_image= "https://www.thesportsdb.com/images/media/team/badge/xqwpup1473502878.png") db.session.add_all([f1, f2, follow1, follow2]) db.session.commit()