def show(page_id): page = Page.get_page(Page(), page_id) content = Markup(markdown.markdown(page.content)) tags = page.get_tags() if current_user.is_authenticated: comment = Comment(('', current_user.user_id, page_id, '')) comments = process_comments(page.get_comments()) else: comment = None comments = [] form = CommentForm(secret_key=app.config['SECRET_KEY'], obj=comment) if form.validate_on_submit(): form.populate_obj(comment) comment.new_comment(comment) flash('Comment posted successfully!', 'success') return redirect('/pages/%s' % page_id) elif form.is_submitted(): if current_user.is_authenticated: flash('Can\'t post if there is no content!', 'warning') else: flash('You must login first to post a comment!', 'info') return redirect('/users/login') return render_template('pages/show.html', title="Show Page", content=content, page_id=page_id, comments=comments, comment=comment, tags=tags, form=form)
def index(): return render_template('database/index.html', title="Database", users=User.all(User()), pages=Page.get_all_pages(Page()), comments=Comment.get_all_comments(Comment()), tags=Tag.get_all_tags(Tag()))
def delete(self,id): comment = Comment.get_by_id(id) if comment is None: if request.is_xhr: abort(404) else: flash(gettext('The comment was not found'), 'error') return redirect(url_for('CommentsView:index')) if not comment.can_edit(): abort(401) message = "" try: Comment.safe_delete(comment) if request.is_xhr: js = [ { "result": "ok" , "type": "comment", "redirect": url_for('CommentsView:index') } ] return Response(json.dumps(js), mimetype='application/json') else: flash(gettext('Comment removed')) return redirect(url_for('CommentsView:index')) except: if request.is_xhr: js = [ { "result": "error" , "type": "comment", "redirect": url_for('CommentsView:index') } ] return Response(json.dumps(js), mimetype='application/json') else: flash(gettext('Error while removing the comment'), 'error') return redirect(url_for('CommentsView:get', id=comment.id))
def comments_create(recipe_id): form = CommentForm(request.form) if not form.validate(): return redirect(url_for("recipes_show", recipe_id=recipe_id, form=form)) c = Comment(form.text.data) c.account_id = current_user.id c.recipe_id = recipe_id db.session().add(c) db.session().commit() return redirect(url_for("recipes_show", recipe_id=recipe_id))
def seed_comments(): comments_count = db.session.query(func.count(Comment.id)).scalar() comments_to_seed = 20 comments_to_seed -= comments_count sys.stdout.write('[+] Seeding %d comments\n' % comments_to_seed) comments = [] user_ids = [ user[0] for user in User.query.with_entities(User.id).filter( User.roles.any(name='ROLE_USER')).all() ] product_ids = [ product[0] for product in Product.query.with_entities(Product.id) ] # equivalent: # user_ids = [user[0] for user in db.session.query(User.id).all()] # product_ids = [product[0] for product in db.session.query(Product.id).all()] for i in range(comments_count, comments_to_seed): user_id = random.choice(user_ids) product_id = random.choice(product_ids) rating = fake.random_int(min=1, max=5) if fake.boolean( chance_of_getting_true=50) else None comments.append( Comment(product_id=product_id, user_id=user_id, rating=rating, content=fake.paragraph(nb_sentences=4, variable_nb_sentences=True, ext_word_list=None), created_at=random_date)) db.session.add_all(comments) db.session.commit()
def dispatch_request(self, post_id: int): post = db_posts(id=post_id) comments = db_comments(post_id=post_id) user_loggedin = user_authenticated() form = CommentForm() if user_loggedin: if request.method == 'POST': if form.validate_on_submit(): comment = form.comment.data try: username = session['active_user']['username'] author = db_user(username=username) parent_post = db_posts(id=post_id) new_comment = Comment(comment=comment, parent_post=parent_post, author=author) db.session.add(new_comment) db.session.commit() flash('Your comment is successfully posted.', 'success') return redirect( url_for(request.endpoint, post_id=post_id)) except: flash('Some errors occurred.', 'error') return redirect( url_for(request.endpoint, post_id=post_id)) return render_template('post.html', post=post, comments=comments, form=form, user_loggedin=user_loggedin)
def get(self,id): comment = Comment.get_by_id(id) if comment is None: flash(gettext('The comment was not found'), 'error') return redirect(url_for('CommentsView:index')) return render_template('admin/comments/show.html', title = gettext('Comment %(id)s', id=comment.id), comment = comment)
def post(self, answer_id=None): data = request.get_json(force=True) data['answer_id'] = answer_id response = Comment(data).save() if response: response_object = {'message': 'Your comment was successful'} return make_response(jsonify(response_object)), 201 response_object = {'message': 'Some error occurred. Please try again.'} return make_response(jsonify(response_object)), 400
def addComment(photoid): user = User.query.filter(User.id == session['user_id']).first() username = user.name text = request.form['text'] userid = user.id comment = Comment(text, userid, username, photoid) db.session.add(comment) db.session.commit() return redirect(url_for('user.uploaded_file', fileid=photoid))
def reply_comment(post_id, id): try: comment = Comment.get_by_id(id) except: comment = None try: post = Post.get_by_id(post_id) except: post = None if comment is None or post is None: abort(403) form = CommentForm() if request.method == 'POST': if form.validate_on_submit(): try: reply = Comment.create() form.populate_obj(reply) reply.user = current_user reply.post = post reply.reply = comment reply.save() flash(gettext('Comment succesfully created')) return redirect('%s#comment_%s' % (url_for('show_post', id=post.id), reply.id)) except: flash(gettext('Error while posting the new comment, please retry later'), 'error') else: flash(gettext('Invalid submission, please check the message below'), 'error') return redirect(url_for('show_post', id=post.id)) else: form = CommentForm() tmplt = render_template("blog/post_form.js", comment=comment, form=form, postid=post.id) resp = Response(tmplt, status=200, mimetype='text/javascript') return resp
def get_stat(value): if value == 4: last_post, count = Post.pagination() return last_post elif value == 5: last_comments, count = Comment.pagination() return last_comments elif value == 6: last_categories, count = Category.pagination() return last_categories else: return 0
def _insert_test_comment(self, session, comment: dict = {}): data = { "content": "Test comment", "item_id": 1, "user_id": "user", "user_name": "Test User", "date": datetime.datetime.now(), } data.update(comment) db_comment = Comment(**data) session.add(db_comment) session.commit() return db_comment
def before_request(): if request.endpoint: if request.endpoint in ['index', 'show_post', 'search_post', 'show_article', 'show_category']: g.user_count = User.count() g.post_count = Post.count() g.comment_count = Comment.count() if request.endpoint != 'search_post': g.searhform = SearchForm() if 'redirect_to' in session and request.endpoint not in ['static', 'sessions.login', 'sessions.signup', 'sessions.login_comment']: session.pop('redirect_to', None)
class CommentSerializer(MetamapperSerializer, serializers.ModelSerializer): """Serializer for interacting with comments. """ html = serializers.CharField(required=True, min_length=1) content_object = fields.RelatedObjectField( allowed_models=Comment.commentable_types(), allow_null=False, ) parent = fields.RelatedObjectField( required=False, allowed_models=(Comment,), allow_null=True, ) def validate_html(self, html): """Clean HTML to reduce risk of injection attacks. """ return shortcuts.clean_html(html) class Meta: model = Comment fields = ( 'content_object', 'html', 'parent', ) @audit.capture_activity( verb='commented on', hydrater=get_audit_kwargs, ) def create(self, validated_data): """Create a comment using the provided data. """ return Comment.objects.create(**validated_data) @audit.capture_activity( verb='updated comment on', hydrater=get_audit_kwargs, capture_changes=True, ) def update(self, instance, validated_data): """Perform the update on the comment instance. """ instance.html = validated_data.get('html', instance.html) return instance
def put(self, id): comment = Comment.get_by_id(id) if comment is None: if request.is_xhr: abort(404) else: flash(gettext('The comment was not found'), 'error') return redirect(url_for('CommentsView:index')) if not comment.can_edit(): abort(401) if request.method in ['POST','PUT']: if request.is_xhr: try: data = request.get_json() comment.body = unicode(data.body) comment.save() js = [ { "result": "ok" ,"type": "comment", "id" : comment.id, "body" : comment.body, "redirect": url_for('CommentsView:index') } ] return Response(json.dumps(js), mimetype='application/json') except: js = [ { "result": "error" ,"type": "comment", "message" : gettext("Error while updating the comment") } ] return Response(json.dumps(js), mimetype='application/json') else: form = EditCommentForm() if form.validate_on_submit(): try: form.populate_obj(comment) comment.save() flash(gettext('Comment was succesfully saved')) if form.remain.data: return redirect(url_for('CommentsView:get', id=comment.id)) else: return redirect(url_for('CommentsView:index')) except: flash(gettext('Error while updating the comment'),'error') else: message = gettext('Invalid submission, please check the message below') else: form = NewCommentForm(comment) return render_template('admin/comments/edit.html', title = gettext('Edit Comment: %(id)s', id=comment.id), form = form, comment = comment)
def resolve_comments(self, info, object_id, *args, **kwargs): """Retrieve a list of comments associated with the provided object. """ _type, object_id = shortcuts.from_global_id(object_id) content_type = Comment.get_content_type_from_node(_type) filter_kwargs = { 'workspace': info.context.workspace, 'object_id': object_id, 'parent_id': None, 'content_type': content_type, } return Comment.objects.filter(**filter_kwargs).order_by( F('pinned_at').desc(nulls_last=True), F('created_at').asc(), )
def index(self): try: page = int(request.args.get('page', 1)) except ValueError: page = 1 limit = 10 comments, count = Comment.pagination(page=page, limit=limit) pagination = Pagination(page=page, per_page= limit, total= count, record_name= gettext('posts'), alignment = 'right', bs_version= 3) return render_template('admin/comments/index.html', title = gettext('Comments | %(page)s', page=page), comments = comments, pagination = pagination)
def show_post(id): try: post = Post.get_by_id(id) except: post = None if post is None: abort(404) if request.method == 'POST': if not current_user.is_authenticated(): abort(401) form = CommentForm() if form.validate_on_submit(): try: comment = Comment.create() form.populate_obj(comment) comment.user = current_user comment.post = post comment.save() flash(gettext('Comment succesfully created')) return redirect('%s#comment_%s' % (url_for('show_article', cat=post.category.slug, post=post.slug), comment.id)) except: flash(gettext('Error while posting the new comment, please retry later'), 'error') else: flash(gettext('Invalid submission, please check the message below'), 'error') else: if not current_user.is_authenticated() or post.comments.count() > 50: form = None else: form = CommentForm() return render_template("blog/post-detail.html", title=gettext('Post | %(title)s', title=post.title), post=post, form=form)
def index(): return render_template('dashboard/index.html', title="Dashboard", pages=Page.get_recent(Page(), 5), comments=Comment.recent_comments(Comment(), 5), tags=Tag.popular_tags(Tag(), 5))
def create_comment(data, user): c = Comment(**data, author=user) db.session.add(c) db.session.commit() return c
import unittest from .base import BaseTestCase from app.comments.models import Comment comment = Comment() class CommentModelTestCase(BaseTestCase): def test_model_save_normal(self): query = comment.save() self.assertEqual(query, False) def test_model_init(self): keys = comment.config.keys() self.assertIn(list(keys)[0], ['password', 'user', 'database', 'host']) self.assertEqual(len(list(keys)), 4) if __name__ == '__main__': unittest.main()
def get_comments(self): return Comment.get_by_page_id(Comment(), self.page_id)