class PostModel(Model): def __init__(self, db, collection, obj): super(PostModel, self).__init__(db, collection, obj) self.user = obj['user'] self.title = obj['title'] self.body = obj['body'] self.tags = obj['tags'] self.upvotes = obj['upvotes'] self.comments = Comment() # Increases the upvotes on a post def vote_up(self): self.upvotes += 1 self.collection.objects.update({'_id': self.get_id()}, {'$inc': {'upvotes': 1}}) # Adds a comment on this post def add_comment(self, **kwargs): return self.comments.insert(post_id=self.get_id(), **kwargs) # Gets comments on this post def get_comments(self): return self.comments.find(post_id=self.get_id()) # Use for removing comments by the user who created them, or by the poster def remove_comments(self, **kwargs): self.comments.remove(**kwargs) # Removes self and the comments def remove(self): self.remove_comments(post_id=self.get_id()) super(PostModel, self).remove()
def post_comment(): if request.method == "POST": user_id = session.get("user_id") comment = request.form.get("comment") Comment.add_comment(g.db,user_id=user_id,user_comment=comment) return redirect("/comment") return redirect("/")
def comment_request_impl(args): try: author = user_from_token(args['token']) post = post_from_id(author, args['post_id']) comment = Comment(args['content']) post.comments.append(comment) author.comments.append(comment) post.add_hot(5, None) if args.has_key("picture") and args['picture'] is not None: output = s3_upload(args['picture']) url = 'https://{}.s3.amazonaws.com/{}'.format(os.environ['S3_BUCKET_NAME'], output) comment.pic = url db.session.commit() #send notification to author send_notification_for_user_commenting_on_post(device_token=post.user.device_token, user_id=author.id, user_pic=author.pic, comment_id=comment.id, nickname=author.nickname, post_id=post.id, platform=post.user.platform) return Response(True, "Comment Succeded", CommentSchema().dumps(comment).data).output() except Exception as exception: return Response(False, str(exception), None).output()
def post(self): print 'Content-Type: text/plain' print '' video = Video.get_by_key_name('vid' + self.request.get('playerID')) if not video: video = Video.get_by_key_name(self.request.get('playerID')) author = users.get_current_user() if video: text = unicode(self.request.get('message')).strip() stime = float(self.request.get('playTime')) mode = int(self.request.get('mode')) fontsize = int(self.request.get('fontsize')) color = int(self.request.get('color')) cmt = Comment(author=author, text=text, stime=stime, mode=mode, fontsize=fontsize, color=color, cid=video) if cmt: cmt.put() print 'OK' else: print 'Failed' else: print 'Failed'
def comment(recipe_id=None): if recipe_id != None and 'comment_text' in request.form and len(request.form['comment_text'].strip()) > 0: Comment.create_comment(g.current_user, recipe_id, request.form['comment_text'].strip()) comment = Comment.load_last_comment(recipe_id) return render_template('comment.html', comment=comment) else: return ''
def post(self, content_id): user = users.get_current_user() comment = { 'nickname': user.nickname(), 'content_id': content_id, 'comment': self.request.get('comment') } Comment.create(comment) self.redirect('/content/' + content_id + "?action=comment.post")
def test_add_and_get(self): uid0 = User.add("test1", "password", "*****@*****.**") bid0 = Board.add("board1", "A") lid0 = List.add("To Do", bid0) caid0 = Card.add("card1", lid0, uid0) coid0 = Comment.add(caid0, uid0, "comment1") comment0 = Comment.get(coid0) assert caid0 == comment0.card_id assert uid0 == comment0.user_id assert "comment1" == comment0.content
def post(self): """Recieves comment message from user and stores in database""" if self.authenticated(): post_id = self.request.get('post_id') post = Post.get_by_id(int(post_id)) comment_txt = self.request.get('comments') comment = Comment(comment = comment_txt, commenter = self.user, post = post) comment.put() self.redirect('/blog/%s' % (post_id)) else: self.login_redirect()
def post(self): uname = self.get_current_user() user = User.get_user_by_name(uname) if len(user)>0: aid = self.get_argument("aid",None) uid = user[0].uid touname = self.get_argument("touname",None) touid = User.get_user_by_name(touname)[0].uid comment = self.get_argument("comment") date = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) Comment.add_one_comment(aid,uid,touid,comment,date) Article.add_one_ncomment(aid) self.redirect("/article?aid="+str(aid)+"#comment-id") else: self.redirect("/login")
def saveComment(self): results = {'result': False} text = self.request.get('commentText') pointRootUrlsafe = self.request.get('p') parentCommentUrlsafe = self.request.get('parentKey') user = self.current_user if user: try: comment = Comment.create( text, user, pointRootUrlsafe, parentCommentUrlsafe) if comment: pst_date = PST.convert(comment.date) results = { 'result': True, 'userName': user.name, 'userURL': user.url, 'avatar_url': user.avatar_url if hasattr(user, 'avatar_url') else '/static/img/icon_triceratops_black_47px.png', 'text': text, 'date': pst_date.strftime('%b. %d, %Y, %I:%M %p'), 'parentUrlsafe': parentCommentUrlsafe, 'myUrlSafe':comment.key.urlsafe(), 'level': comment.level } except WhysaurusException as e: results['error'] = str(e) resultJSON = json.dumps(results) self.response.headers.add_header('content-type', 'application/json', charset='utf-8') self.response.out.write(resultJSON)
def get_comment(page=None): if request.method == "GET": comments = Comment.get_all_comment(g.db,status=1) page_nums = get_page_nums(comments) return render_template("comment.html", comments= SqlalchemyOrmPage(comments,page=page,items_per_page=20), page_nums = page_nums)
def post(self, post_id): if self.user: content = self.request.get('content') postid = int(post_id) blog = Post.by_id(postid) title = blog.subject if content: comment = Comment(title=title, content=content, created_by=self.user.name, post_id=postid) comment.put() self.redirect('/comment') else: error = "We need some content for the comment" self.render_front(title, content, error) else: self.redirect('/login')
def post(self): comment_id = self.request.get('comment_id') comment_txt = self.request.get('comment') comment = Comment.get_by_id(int(comment_id)) comment.comment = comment_txt comment.put() self.redirect('/blog/%s' % comment.post.key().id())
def comment_add(request): u = current_user(request) form = request.form() form['user_id'] = u.id c = Comment.insert(form) log('comment add', c, u, form) return redirect('/weibo/index')
def post(self, topic_id): if not topic_id: return self.write( 'Error trying to write a comment into undefined topic!') topic = Topic.get_by_id(int(topic_id)) logged_user = users.get_current_user() if not logged_user: return self.write( 'Please login to be allowed to post a new comment.') content = self.request.get('comment') if (not content) or (not content.strip()): return self.write('Empty comments are not allowed!') new_comment = Comment.create( content=content, user=logged_user, topic=topic, ) flash = { 'flash_message': 'Comment added successfully', 'flash_class': 'alert-success', } return self.redirect_to('topic-details', topic_id=topic_id, **flash)
def post(self, submission_id, **kwargs): ''' creates a new comment instance and inserts it into the db. content is required to make a new comment ''' content = self.request.get('content') if content: comment = Comment(user=self.user, content=content, **kwargs) comment.put() time.sleep(0.1) self.redirect('/%s' % submission_id) else: error = 'You must enter content' self.render('comments/new_comment.html', error=error, **kwargs)
def all(request): weibos = Weibo.all_json() # 下面是 weibo 的 all 路由只看到自己 weibo 的方法 # u = current_user(request) # weibos = Weibo.find_all(user_id=u.id) # weibos = [w.json() for w in weibos] weibo_list = [] for i in range(len(weibos)): weibo_list.append( dict(id=weibos[i]['id'], content=weibos[i]['content'], user_id=weibos[i]['user_id'], weibo_user=User.find_by(id=weibos[i]['user_id']).username)) weibos = weibo_list for weibo in weibos: comments = Comment.find_all(weibo_id=weibo['id']) comment_list = [] for i in range(len(comments)): comment_list.append( dict(id=comments[i].id, content=comments[i].content, user_id=comments[i].user_id, weibo_id=comments[i].weibo_id, comment_user=User.find_by( id=comments[i].user_id).username)) weibo['comments'] = comment_list log('allweibos', weibos) return json_response(weibos)
def delete(id): image = request.form.get('image') comment = Comment.get_by_id(id) comment.delete_instance() flash('Your comment has been removed', 'info') return redirect(url_for('images.show', id=image))
def post(self, post_id, user_id): if not self.user: return content = self.request.get('content') user_name = self.user.name key = db.Key.from_path('Post', int(post_id), parent=blog_key()) c = Comment(parent=key, user_id=int(user_id), content=content, user_name=user_name) c.put() self.redirect('/' + post_id)
def get(self): user = users.get_current_user() comments = Comment.query(Comment.user_email == user.email(), Comment.deleted == False,).order(-Comment.created_at).fetch() params = {"comments": comments} return self.render_template("user_comments.html", params=params)
def comment_add(): form = request.get_json() log(form) todo = Todo.one(id=form['id']) if todo is not None: c = Comment.add(form) return render_json(c)
def post(self, post_id): post = Post.get_by_id(int(post_id)) if not post: self.redirect('/') elif not self.login_status(): self.redirect('/%s' % post_id) else: comment = self.request.get('comment') if not comment: error = 'You must enter a comment' self.render('post.html', post=post, error=error) else: c = Comment(username=self.get_username(), post=post, comment=self.br_substitution(comment)) c.put() self.redirect('/%s' % post_id)
def search_comments(connection, instructor_id, query): objs = [] try: cur = connection.cursor() # neutralize regexp attempts query = query.translate(str.maketrans({"_": r"\_", "%": r"\%"})) query = '%' + query.lower() + '%' sql = "SELECT * FROM comments WHERE instructor_id = %s AND lower(text) LIKE %s ESCAPE '\\'" cur.execute(sql, (instructor_id, query)) row = cur.fetchone() while row is not None: comment = Comment(row[0], row[1], row[2], row[3]) objs.append(comment) row = cur.fetchone() connection.commit() cur.close() except Exception as error: print(error) return objs
def create(id): cur_com = Comment.get_or_none(Comment.id == id) if not cur_com: return jsonify({"msg": "error, com id wrong"}), 400 else: comment_like = request.get_json() user_id = comment_like['user'] comment_id = comment_like['comment'] existing_like = CommentLike.get_or_none(( CommentLike.user == user_id) & (CommentLike.comment == comment_id)) if existing_like: return jsonify({ 'success': False, 'message': "You've already liked this comment" }) new_comment_like = CommentLike(user=user_id, comment=comment_id) new_comment_like.save() return jsonify({ 'success': True, 'message': "Comment liked successfully", }), 200
def delete_one_comment(comment_id): try: # deletes the comment Comment.delete().where(Comment.id == comment_id).execute() return jsonify( data={}, status={'code': 200, 'message': 'successfully deleted comment.'} ) # if the queried comment doesnt exist except DoesNotExist: return jsonify( data={}, status={'code': 404, 'message': 'Resource does not exist.'} )
def create_comment(): # gets json data from client data = request.get_json() try: # gets post by its id post = Post.get(Post.id == data['post_id'], Post.soft_delete == False) # creates a new comments comment = Comment.create(**data, user=current_user.id, post=post) # converts model to dictionary comment_dict = model_to_dict(comment) return jsonify( data=comment_dict, status={'code': 201, 'message': 'successfully created comment.'} ) # if the queried post doesnt exist except DoesNotExist: return jsonify( data={}, status={'code': 404, 'message': 'Resource does not exist.'} )
def f(request): log('comment_or_weibo_owner_required') if request.method == 'GET': data = request.query elif request.method == 'POST': data = request.form() else: raise ValueError('不支持的方法', request.method) comment_key = 'comment_id' weibo_key = 'weibo_id' if comment_key in data: c = Comment.one(id=int(data[comment_key])) if c is None: return redirect('/weibo/index') else: user_id = c.user_id elif weibo_key in data: w = Weibo.one(id=int(data[weibo_key])) if w is None: return redirect('/weibo/index') else: user_id = w.user_id else: raise ValueError('不支持的参数', data) u = current_user(request) if user_id == u.id: log('不是评论或者微博的作者', user_id, u.id) return route_function(request) else: return redirect('/weibo/index')
def all(cls, **kwargs): u = current_user() data = super().all(user_id=u.id, **kwargs) for d in data: comments = Comment.all(todo_id=d['id']) d['comments'] = comments return data
def get(self, user_key): """ Get all posts of a given user :param user_key: Key of the user we want to get all posts """ user = User.get(user_key) posts = Post.get_all(user=user) pagination = Pagination(self.request.GET.get('p'), posts.count()) if pagination and pagination.is_valid(): posts = posts.fetch(limit=pagination.posts_per_page, offset=pagination.offset) nb_likes = Like.get_nb_likes_per_posts(posts) nb_comments = Comment.get_nb_comments_per_posts(posts) self.render("posts/user.html", userposts=user, posts=posts, nb_likes=nb_likes, nb_comments=nb_comments, pagination=pagination) else: self.abort(404, "Invalid page number")
def f(request): u = current_user(request) # 拿到修改数据对应的 id if 'id' in request.query: id = request.query['id'] else: form = request.dejson() id = form['id'] # 判断修改数据的类型 log('id', id) if 'todo' in request.path: m = Todo.one(id=int(id)) elif 'weibo' in request.path: m = Weibo.one(id=int(id)) elif 'comment' in request.path: m = Comment.one(id=int(id)) # 判断当前用户与被修改数据的用户是否是同一用户 log('path', request.path) log('member', m) if m.user_id == u.id: return route_function(request) else: d = dict( deny="yes", message="owner required", ) return json_response(d)
def get(self): user = users.get_current_user() comments = Comment.query(Comment.deleted==False, Comment.author_email==user.email()).fetch() topics = Topic.query().fetch() params = {"comments":comments, "topics": topics} return self.render_template("comments_list.html", params=params)
def test_comment_delete(self): user = User.query().get() topic = Topic.query().get() test_comment = Comment(user_email=user.email, user_id=user.key.id(), content="Test content", topic_id=topic.key.id(), topic_title=topic.title) test_comment.put() memcache.add(key="abc123", value=True) params = {"csrf_token": "abc123"} response = self.testapp.post("/comment/" + str(test_comment.key.id()) + "/delete", params=params)
def get(self, topic_id): topic = Topic.get_by_id(int(topic_id)) comments = Comment.query(Comment.topic_id == topic.key.id(), Comment.deleted == False).order(Comment.created).fetch() params = {"topic": topic, "comments": comments} return self.render_template_with_csrf("topic_details.html", params=params)
def addcomment(self): com = Comment(author='nik', text='aaa', postid=2) db.session.add(com) db.session.commit() data = Post.query.filter_by(id=2).one() assert len( data.post_comments) == 1 and data.post_comments[0].text == 'aaa'
def delete(request): weibo_id = int(request.query['id']) Weibo.delete(weibo_id) cs = Comment.all(weibo_id=weibo_id) for c in cs: c.delete(c.id) return redirect('/weibo/index')
def comment_add(): form = request.get_json() u = current_user() form['user_id'] = u.id c = Comment.new(form) log(c) return jsonify(c.json())
def __init__(self, db, collection, obj): super(UserModel, self).__init__(db, collection, obj) self.username = obj['username'] self.password = obj['password'] self.voted = obj['voted'] self.posts = Post() self.comments = Comment()
def get(self, topic_id): topic = Topic.get_by_id(int(topic_id)) comments = Comment.query(Comment.topic_id == topic.key.id(), Comment.deleted == False).count() return self.write(comments)
def get(self, topic_id): topic = Topic.get_by_id(int(topic_id)) user = users.get_current_user() comments = Comment.query(Comment.topic_id == topic.key.id(), Comment.deleted == False).order( Comment.created).fetch() comments_sum = len(comments) if user: subscriber = Subscription.query( Subscription.topic_id == topic.key.id(), Subscription.deleted == False, Subscription.subscriber_email == user.email()).get() else: subscriber = "" params = { "topic": topic, "comments": comments, "comments_sum": comments_sum, "user": user, "subscriber": subscriber } return self.render_template("topic.html", params=params)
def f(request): log('comment_owner_required') u = current_user(request) # 查询评论id,识别用户 id_key = 'comment_id' if id_key in request.query: comment_id = request.query[id_key] else: comment_id = request.form()[id_key] c = Comment.one(id=int(comment_id)) w_id = c.weibo_id w = Weibo.one(id=int(w_id)) # 判断评论用户 if c.user_id == u.id: comment_owner = True else: comment_owner = False # 判断微博用户 if w.user_id == u.id: weibo_owner = True else: weibo_owner = False if comment_owner or weibo_owner: return route_function(request) else: return redirect('/weibo/index')
def post(self, comment_id): comment = Comment.get_by_id(int(comment_id)) user = users.get_current_user() if comment.author_email == user.email() or users.is_current_user_admin(): comment.deleted = True comment.put() return self.redirect_to("topic-details", topic_id=comment.topic_id)
def get(self, topic_id): # Find latest comment in given topic comments = Comment.query(Comment.topic_id == int(topic_id)).order( -Comment.created_at).fetch() # If no comments are found return this message if not comments: data = {"email": "", "content": "This topic has no comments yet."} return self.write(json.dumps(data)) comment = comments[0] # Pass comment data to a dictionary comment_dict = {} comment_dict['email'] = comment.user_email comment_dict['content'] = comment.content # Truncate the comment's contents if too long if len(comment_dict['content']) > 75: comment_dict['content'] = comment_dict['content'][:75] + "..." # Convert dictionary to JSON and return data = json.dumps(comment_dict) return self.write(data)
def get(self): user = users.get_current_user() comments = Comment.query(Comment.deleted == False).order( Comment.topic_title).fetch() params = {"user": user, "comments": comments} return self.render_template("comment_list.html", params=params)
def put(self, id): comment = Comment.find_by_id(id) data = request.get_json() for key in data: setattr(comment, key, data[key]) db.session.commit() return comment.json()
def test_get_comment_by_event_2(self): """ Test get_comment_by_event: event doesn't exist """ user = "******" event_id = '1' content = "this is a comment" time = datetime.strptime("2020-01-01 12:12:30", "%Y-%m-%d %H:%M:%S") comment = Comment(user=user, content=content, comment_time=time, event=event_id) self.assertRaises(mysql.connector.Error, Comment.create_comment, comment) comments = Comment.get_comment_by_event(event_id) self.assertEqual(len(comments), 0)
def create(parameters): comment = Comment(Comment.cxn, "comments", parameters) try: comment.save() attributes_to_render = comment.attributes attributes_to_render.update({"id": comment.id}) template = open('./templates/comments/show.html').read() attributes_to_render.update({"html": TemplateEngine(template, attributes_to_render).render_partial()}) return json.dumps(attributes_to_render) except ValidationError as ve: response = {"status": 422, "errors": ve.messages} return json.dumps(response) except Exception as e: print(str(e)) response = {"status": 500, "errors": [str(e)]} return json.dumps(response)
def post(self, comment_id): comment = Comment.get_by_id(int(comment_id)) comment.content = self.request.get("content") comment.updated = datetime.datetime.now() comment.updated_by = users.get_current_user().nickname() comment.put() self.redirect("/topic/" + str(comment.the_topic_id))
def post(self, slug=None): try: linkcheck = self.request.get_all('checks') for key in linkcheck: comment = Comment.get(key) comment.delit() finally: self.redirect('/admin/comments')
def __init__(self, db, collection, obj): super(PostModel, self).__init__(db, collection, obj) self.user = obj['user'] self.title = obj['title'] self.body = obj['body'] self.tags = obj['tags'] self.upvotes = obj['upvotes'] self.comments = Comment()
def add_comment(post_id, comment_body, user, parent_id=None): post = Post.get_by_id(post_id) if parent_id is not None: parent = Comment.get_by_id(parent_id).key comment = Comment() comment.add( text=comment_body, author=user, post=post.key, parent=None if parent_id is None else parent) if post.num_comments is None: post.num_comments = 0 post.num_comments += 1 post.put()
def add(): target_type = request.values.get('target_type') target_id = request.values.get('target_id') url = request.values.get('url') msg = request.values.get('msg') msg_channel = request.values.get('msg_channel') comment = Comment.add(target_type, target_id, msg, g.user, msg_channel=msg_channel) add_comment_signal.send(current_app._get_current_object(), comment=comment, msg_channel=msg_channel, url=url) return jsonify({'msg': "msg add success"})
def get(self, content_id): user = users.get_current_user() comments = Comment.get_by_content_id(content_id) params = { 'user': user, 'content_id': content_id, 'comments': comments } self.response.write(template.render('content/' + content_id + '.html', params))
def delete_post_comment(comment_id): comment = Comment.get_by_id(comment_id) origin_post = comment.post.get() origin_post.num_comments -= 1 origin_post.put() #will now display [deleted] to keep comment chain intact comment.partial_delete() return origin_post.key.id()
def decorated_function(self, *args, **kwargs): comment_id = args[1] comment = Comment.by_id(comment_id) if comment: kwargs['comment'] = comment return f(self, *args, **kwargs) else: self.error(404) return
def blog_show(blog_id): blog = Blog.get(blog_id) user = get_user() if not user: is_join = False else: is_join = blog.get_is_join(user.id) comment_list = Comment.get_comments(blog_id) return header_render('blog_show.html', blog=blog, comment_list = comment_list, is_join = is_join)
def post(self, comment_id): comment = Comment.get_by_id(int(comment_id)) comment.deleted = True comment.put() topic = Topic.get_by_id(comment.the_topic_id) topic.num_comments -= 1 topic.put() self.redirect("/topic/" + str(comment.the_topic_id))
def get(self): if self.authenticated(): comment_id = self.request.get('comment_id') comment = Comment.get_by_id(int(comment_id)) if comment.commenter.username == self.user.username: self.render("edit_comment.html",comment = comment) else: self.render_homepage("You can not edit others comment !") else: self.login_redirect()
def get(self, slug=None): try: page_index = int(self.param('page')) except: page_index = 1 query = Comment.all().order('-date') (comments, pager) = Pager(query=query, items_per_page=15).fetch(page_index) self.render2('views/admin/comments.html', {'current': 'comments', 'comments': comments, 'pager': pager})
def post(self, task_id): # create new task (with parent) task_key = ndb.Key(urlsafe=task_id) # check if user is authed to reassign task if not authed_for_task(task_key.get(), self.user_entity): return self.abort(401) # get user key user_key = self.user_entity.key # create new comment object comment = Comment(parent=task_key) # populate form with POST data form = CommentForm(self.request.POST) if form.validate(): # populate comment object with validated form data form.populate_obj(comment) # set reference properties on comment object comment.task = task_key comment.user = user_key # store comment comment.put() # record history item history_text = 'Comment added' add_to_history(task_key.get(), self.user_entity, history_text) # add a flash message to session self.session.add_flash(history_text) else: # if form doesn't validate then add a flash message before redirecting flash_msg = form.errors self.session.add_flash(flash_msg) # redirect to task view page redirect_url = self.uri_for('task-view', task_id=task_key.urlsafe()) return self.redirect(redirect_url)
def post(self): comment_id = self.request.get('comment_id') comment = Comment.get_by_id(int(comment_id)) if self.authenticated(): if comment.commenter.username == self.user.username: comment.delete() else: self.render_homepage("You cant delete others comment") self.redirect('/blog/%s' % comment.post.key().id()) else: self.login_redirect()