def test_follow_posts(self): u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') u3 = User(username='******', email='*****@*****.**') u4 = User(username='******', email='*****@*****.**') db.session.add_all([u1, u2, u3, u4]) now = datetime.utcnow() p1 = Post(body="post from john", author=u1, timestamp=now + timedelta(seconds=1)) p2 = Post(body="post from susan", author=u2, timestamp=now + timedelta(seconds=4)) p3 = Post(body="post from mary", author=u3, timestamp=now + timedelta(seconds=3)) p4 = Post(body="post from david", author=u4, timestamp=now + timedelta(seconds=2)) db.session.add_all([p1, p2, p3, p4]) db.session.commit() u1.follow(u2) u1.follow(u4) u2.follow(u3) u3.follow(u4) db.session.commit() f1 = u1.followed_posts().all() f2 = u2.followed_posts().all() f3 = u3.followed_posts().all() f4 = u4.followed_posts().all() self.assertEqual(f1, [p2, p4, p1]) self.assertEqual(f2, [p2, p3]) self.assertEqual(f3, [p3, p4]) self.assertEqual(f4, [p4])
def post(self, user): """ API for creating a new post :param user: authenticated user, returned by auth.token_required function :return: json of a new created post example: curl -H "Content-Type: application/json" -H "X-Api-Key: <USER_TOKEN>" -d '{"text": "user has created a new post!!!"}' http://127.0.0.1:5000/api/posts where <USER_TOKEN> must be replaced by an authenticated user's token """ args = request.get_json() if not args: log_activity("tried to add post without text", user_id=user.id) return {"error": "no post text provided"}, 401 new_post = Post(author_id=user.id, text=args["text"]) db.session.add(new_post) db.session.commit() log_activity("new post added", user_id=user.id, post_id=new_post.id) return new_post.json(), 201
def mutate(self, info, title, body, email): user = User.query.filter_by(email=email).first() post = Post(title=title, body=body) if user is not None: post.author = user db.session.add(post) db.session.commit() return CreatePost(post=post)
def post(self): args = self.get_args('post') print(args) post_ = Post(args['title'], args['text'], g.id, tags=args['tags']) if not post_: current_app.logger.info('PostApi参数错误!') return {'status': 403, 'msg': '文章发布失败!'} post_.add() return {'status': 200, 'msg': '文章发布成功!'}
def test_post_deleted(self): user = User(**self.user) user.save() post = Post(**self.post, owner_id=user.id) post.save() res = self.authorized_delete(f"/posts/{post.id}", user) self.assertEqual(res.status_code, 200) self.assertEqual(res.json['deleted'], post.id)
def test_post_favorited(self): user = User(**self.user) user.save() post = Post(**self.post, owner_id=user.id) post.save() res = self.authorized_post(f"/posts/{post.id}/favorite", user) self.assertEqual(res.status_code, 200) self.assertEqual(res.json['favorites_count'], 1) self.assertEqual(res.json['is_favorited'], True)
async def json_res(request: Request): print(request.url) print(request.pony_session) with request.pony_session: Post(title="第一篇文章", content="Hello world") commit() p = Post.get(post_pk=1) # print(p) print(p.post_pk, '|', p.title, '|', p.content) return Response('{"code":0000,"msg":"OK"}')
def test_comments_retrieved(self): COMMENTS_NUM = 5 user = User(**self.user) user.save() post = Post(owner_id=user.id, **self.post) post.save() [Comment(**self.comment, post_id=post.id, author_id=user.id).save() for _ in range(COMMENTS_NUM)] res = self.client.get(f"/posts/{post.id}/comments") self.assertEqual(res.status_code, 200) self.assertEqual(len(res.json), COMMENTS_NUM)
def test_post_unauthorized_delete(self): user = User(**self.user) user.save() user2 = User('Another', 'another', '*****@*****.**', 'secret') user2.save() post = Post(**self.post, owner_id=user.id) post.save() res = self.authorized_delete(f"/posts/{post.id}", user2) self.assertEqual(res.status_code, 403) self.assertEqual(res.json['message'], 'Permission denied')
def test_post_unfavorited(self): user = User(**self.user) user.save() post = Post(**self.post, owner_id=user.id) post.favorited_by = [user] post.save() res = self.authorized_delete(f"/posts/{post.id}/favorite", user) self.assertEqual(res.status_code, 200) self.assertEqual(res.json['favorites_count'], 0) self.assertEqual(res.json['is_favorited'], False)
def post(): if request.method == 'POST': if request.form['body'] != '': new_post = Post(body=request.form['body'], author=current_user.id) if 'image_url' in request.form: new_post.image_url = request.form['image_url'] db.session.add(new_post) db.session.commit() flash('Successfully posted', 'success') return redirect(url_for('root.home')) else: flash('User try to post an empty post', 'warning') return redirect(url_for('root.home'))
def test_user_get_me_with_posts(self): user = User(**self.user) user.save() post = {'title': 'A', 'description': 'B', 'contents': 'C'} post = Post(**post, owner_id=user.id) post.save() res = self.authorized_get('/me?include=posts', user) self.assertIn('posts', res.json) posts = res.json['posts'] self.assertEqual(posts[0]['title'], post.title) self.assertEqual(posts[0]['description'], post.description) self.assertEqual(posts[0]['contents'], post.contents)
def create_post(topic_id): if request.method == 'GET': form = PostForm() return render_template('create_post.html', form=form, id=topic_id) if request.method == 'POST': #create topic formData = PostForm(request.form) if formData.validate(): #for csrf token validation new_post = Post(name=formData.name.data, description=formData.description.data, topic_id=topic_id) try: db.session.add(new_post) db.session.flush() db.session.commit() return redirect(url_for('post_bp.get_posts', topic_id=topic_id)) except: raise InternalServerError else: flash("Form validation error!", 'danger') return render_template('create_post.html', form=formData, id=topic_id)
def delete(self, post_id): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') post.unfavorite(current_user) return post
def get(self, post_id): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') comments = post.comments. \ order_by(Comment.created_at.desc()) return comments
def post(self, post_id, data): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') comment = Comment(post_id=post.id, author_id=current_user.id, **data) comment.save() return comment
def test_comment_created(self): user = User(**self.user) user.save() post = Post(**self.post, owner_id=user.id) post.save() res = self.authorized_post( f"/posts/{post.id}/comments", user, json=self.comment, ) data = res.json self.assertEqual(res.status_code, 201) self.assertEqual(data['contents'], self.comment['contents']) self.assertEqual(data['author']['id'], user.id) self.assertIn('created_at', data)
def test_post_unauthorized_update(self): new_data = { 'title': 'New title', 'description': 'New description', 'contents': 'New contents' } user = User(**self.user) user.save() user2 = User('Another', 'another', '*****@*****.**', 'secret') user2.save() post = Post(**self.post, owner_id=user.id) post.save() res = self.authorized_put(f"/posts/{post.id}", user2, json=new_data) self.assertEqual(res.status_code, 403) self.assertEqual(res.json['message'], 'Permission denied')
def new_post(): form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') return redirect(url_for('home')) return render_template('create_post.html', title='New Post', form=form, legend='New Post')
def test_post_retrieved(self): user = User(**self.user) user.save() user2 = User('Another', 'another', '*****@*****.**', 'secret') user2.save() post = Post(**self.post, owner_id=user.id) post.favorited_by = [user, user2] post.save() res = self.client.get(f"/posts/{post.id}") data = res.json self.assertEqual(res.status_code, 200) self.assertEqual(data['title'], self.post['title']) self.assertEqual(data['description'], self.post['description']) self.assertEqual(data['contents'], self.post['contents']) self.assertEqual(data['author']['id'], user.id) self.assertEqual(data['favorites_count'], 2) self.assertEqual(data['is_favorited'], False)
def delete(self, post_id): user = current_user post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') if post.owner_id != user.id: raise InvalidUsage(403, 'Permission denied') post.delete() return {'deleted': post.id}
def create(): if request.method == "POST": data = request.get_json() newTitle = data['title'] newBody = data['body'] newImg = data['img'] new_post = Post(title = newTitle, body = newBody, image_url = newImg, user_id = current_user.id) db.session.add(new_post) db.session.commit() return jsonify({'success': True}) return jsonify({'success':False})
def test_post_updated(self): new_data = { 'title': 'New title', # 'description': 'Not updated' 'contents': 'New contents' } user = User(**self.user) user.save() post = Post(**self.post, owner_id=user.id) post.save() res = self.authorized_put(f"/posts/{post.id}", user, json=new_data) data = res.json self.assertEqual(res.status_code, 200) self.assertEqual(data['title'], new_data['title']) self.assertEqual(data['contents'], new_data['contents']) self.assertEqual(data['author']['id'], user.id) # Assert that description remains unchanged self.assertEqual(data['description'], self.post['description'])
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 posts now = datetime.utcnow() p1 = Post(body="post from john", author=u1, timestamp=now + timedelta(seconds=1)) p2 = Post(body="post from susan", author=u2, timestamp=now + timedelta(seconds=4)) p3 = Post(body="post from mary", author=u3, timestamp=now + timedelta(seconds=3)) p4 = Post(body="post from david", author=u4, timestamp=now + timedelta(seconds=2)) db.session.add_all([p1, p2, p3, p4]) db.session.commit() # setup the followers u1.want_to_follow(u2) # john follows susan u1.want_to_follow(u4) # john follows david u2.want_to_follow(u3) # susan follows mary u3.want_to_follow(u4) # mary follows david db.session.commit() # check the followed posts of each user f1 = u1.posts_im_following().all() f2 = u2.posts_im_following().all() f3 = u3.posts_im_following().all() f4 = u4.posts_im_following().all() self.assertEqual(f1, [p2, p4, p1]) self.assertEqual(f2, [p2, p3]) self.assertEqual(f3, [p3, p4]) self.assertEqual(f4, [p4])
def put(self, post_id, data): user = current_user post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') if user.id != post.owner_id: raise InvalidUsage(403, 'Permission denied') post.update(**data) return post
def put(self, post_id, comment_id, data): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') comment = post.comments.filter_by(id=comment_id).first() if not comment: raise InvalidUsage(404, 'Comment not found') if comment.author_id != current_user.id: raise InvalidUsage(403, 'Permission denied') comment.update(**data) return comment
def delete(self, post_id, comment_id): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') comment = post.comments.filter_by(id=comment_id).first() if not comment: raise InvalidUsage(404, 'Comment not found') if comment.author_id != current_user.id: raise InvalidUsage(403, 'Permission denied') comment.delete() return {'deleted': comment.id}
def get(self): args = self.get_args('get') post_ = Post.get(args['post_id']) author = User.get(post_.user_id).username post_data = { 'title': post_.title, 'text': post_.text, 'publish_date': post_.publish_date.strftime('%Y-%m-%d %H:%M:%S'), 'author': author } print(post_data) return {'status': 200, 'msg': '成功', 'post': post_data}
def test_comment_updated(self): new_data = { 'contents': 'New contents' } user = User(**self.user) user.save() post = Post(owner_id=user.id, **self.post) post.save() comment = Comment(**self.comment, post_id=post.id, author_id=user.id) comment.save() res = self.authorized_put( f"/posts/{post.id}/comments/{comment.id}", user, json=new_data ) data = res.json self.assertEqual(res.status_code, 200) self.assertEqual(data['contents'], new_data['contents']) self.assertEqual(data['author']['id'], user.id)
def new_post(): form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data, author=current_user) db.session.add(post) db.session.commit() flash('Запись размещена', 'success') return redirect(url_for('main.hello')) context = {'title': 'Новая запись', 'legend': 'Новая запись'} return render_template('create_post.html', context=context, form=form)