def comments(request, subdomain, article_id): try: wiki = models.Wiki.objects.get(subdomain=subdomain) story = models.Story.objects.get(id=article_id, wiki=wiki) except ObjectDoesNotExist: return four_oh_four(request) if request.method == "POST" and request.user.is_authenticated(): text = request.POST.get('text') if text is not None and text.strip() is not "": parent_id = request.POST.get('parent_id') if parent_id is not None: try: parent = models.Comment(id=parent_id, story=story) new_comment = models.Comment(story=story, parent=parent, text=text, user=request.user) new_comment.save() except ObjectDoesNotExist: pass else: new_comment = models.Comment(story=story, text=text, user=request.user) new_comment.save() current_comments = [ c for c in models.Comment.objects.filter(id=article_id) ] return render_to_response('comments.html', dict(story=story, comments=current_comments, wiki=wiki, comment_form=CommentForm()), context_instance=RequestContext(request))
def exchanger(r): ex = db.session.query(models.Exchangers).filter_by(id=r).first() if not ex: abort(404) ex_data = [ex.name, ex.country, ex.description, ex.comments, ex.positives, ex.complains, ex.link, ex.id, ex.ownerId, ex.image, ex.dateOfCreation] badges = [] if ex.badges: badges = ex.badges.split(',') form = CommentForm() form1 = EditForm() comments = db.session.query(models.Comment).filter(models.Comment.exchangerId == r) comments = comments[::-1] recent = comments[:5] if form.validate_on_submit(): if len(form.review.data) > 5: if current_user.id == ex.ownerId: new_comment = models.Comment(review=str(form.review.data), type=str(form.type.data), userId=current_user.id, userName=current_user.name, exchangerId=r, byAdmin=1) else: new_comment = models.Comment(review=str(form.review.data), type=str(form.type.data), userId=current_user.id, userName=current_user.name, exchangerId=r, byAdmin=0) db.session.add(new_comment) # db.session.commit() if current_user.id != ex.ownerId: if form.type.data == 'Positive': ex.positives = ex.positives + 1 elif form.type.data == 'Complain': ex.complains = ex.complains + 1 else: ex.comments = ex.comments + 1 db.session.commit() return redirect('/exchanger/{}'.format(r)) ex = db.session.query(models.Exchangers).filter_by(id=r).first() if form1.validate_on_submit(): if form1.name.data: ex.name = form1.name.data if form1.url.data: ex.link = form1.url.data if form1.description.data: ex.description = form1.description.data # if form1.picURL.data: # ex.image = form1.picURL.data db.session.commit() return redirect('/exchanger/{}'.format(r)) return render_template('exchanger.html', ex_data=ex_data, form=form, comments=comments, recent=recent, form1=form1, badges=badges)
def sandwich_comment(sandwich_id): name = request.form.get('name') comment = request.form.get('comment') if name == '' or comment == '': # no name or comment, return to page return redirect(request.referrer) #get the idea by id try: sandwich = models.Sandwich.objects.get(id=sandwich_id) except: # error, return to where you came from return redirect(request.referrer) # create comment comment = models.Comment() comment.name = request.form.get('name') comment.comment = request.form.get('comment') # append comment to idea sandwich.comments.append(comment) # save it sandwich.save() return redirect('/sandwiches/%s' % sandwich.slug)
def post(self, post_id: int): if str(request.url_rule) != self.URL_RULE_POST_COMMENTS: abort(404) user = utils.Auth.verify_authorization(request=request) if user is None: abort(400) form_data = request.form if not form_data: abort(400) post = models.Post.query.filter_by(data_id=post_id).first() if post is None: abort(400) comment = models.Comment() comment.save(form_data=form_data, post=post, user=user) response_message = { 'message': 'Comment successfully inserted!', 'comment': comment.output_with_permissions(user) } return make_response(jsonify(response_message), 201)
def AddComment(article_id: int = Path(..., title="Article ID"), username: str = Form(..., min_lenght=3, max_length=32), content: str = Form(..., max_length=2048), db: Session = Depends(get_db)): ''' Adds a comment to an article.\n Response model: `Comment` ''' content = html.escape(content, True) username = html.escape(username, True) if get(f"https://github.com/{username}.png").ok: avatar = f"https://github.com/{username}.png" else: avatar = "" now = datetime.now() db_comment = models.Comment(username=username, content=content, date=now, parent_id=article_id, avatar=avatar) db.add(db_comment) db.commit() db.refresh(db_comment) return dict(db_comment)
def dream_comment(dream_id): name = request.form.get('name') comment = request.form.get('comment') if name == '' or comment == '': # no name or comment, return to page return redirect(request.referrer) #get the dreams by id try: dream_post = models.Dreamology.objects.get(id=dream_id) except: # error, return to where you came from return redirect(request.referrer) # create comment commentary = models.Comment() commentary.name = request.form.get('name') commentary.comment = request.form.get('comment') # append comment to dream dream_post.comments.append(commentary) # save it dream_post.save() return redirect('/dream/%s' % dream_post.slug)
def post(self): #the user is attempting to comment #verify the user is logged in otherwise send them to log in] authResp = authUser() if(isinstance(authResp,webapp2.Response)): return authResp#redirect to correct page #user must be logged in at this point #get the user gUser = users.get_current_user() user = models.User.get_by_id(gUser.user_id()) comment = self.request.get('commentText') new_comment = models.Comment(comText = comment, comAuthor = user.key) new_comment_key = new_comment.put(); post_key = ndb.Key(urlsafe=self.request.get('post_id')) post = post_key.get() post.comments.append(new_comment_key) commentList = post.comments template = jinja_env.get_template("templates/viewPost.html") postInfo = { "post": post, "Image": jinja2.Markup('<img id = "size" class="postImage" src="/img?img_id=%s"></img>' % post.key.urlsafe()), "comments_info": commentList, } postInfo.update(getAccountHtml()) self.response.write(template.render(postInfo)) post.put()
def detail(slug): if current_user.is_authenticated(): # session.get('logged_in'): # query = models.Entry.query.all() entries = models.Entry.query.filter_by(slug=slug) else: entries = models.Entry.public() if entries.count() == 0: abort(404) else: entry = entries.first() if request.method == 'POST': c = request.form.get("comment") comment = models.Comment(page_inst=entry, username=current_user.uid_trim(), comment=c, visible=True) models.db.session.add(comment) entry.views = entry.views + 1 models.db.session.add(entry) models.db.session.commit() # entry = models.Entry.query.get_or_404(slug = slug) return render_template('detail.html', entry=entry)
def addNote(payload): id_location = None author = M.User.objects.get(pk=payload["id_author"]) #do we need to insert a location ? if "id_location" in payload: location = M.Location.objects.get(pk=payload["id_location"]) else: location = M.Location() location.source = M.Source.objects.get(pk=payload["id_source"]) location.ensemble = M.Ensemble.objects.get(pk=payload["id_ensemble"]) location.y = payload["top"] location.x = payload["left"] location.w = payload["w"] location.h = payload["h"] location.page = payload["page"] location.section = M.Membership.objects.get(user=author, ensemble=location.ensemble, deleted=False).section location.save() comment = M.Comment() if "id_parent" in payload: comment.parent = M.Comment.objects.get(pk=payload["id_parent"]) comment.location = location comment.author = author comment.body = payload["body"] comment.type = payload["type"] comment.signed = payload["signed"] == 1 comment.save() return comment
async def social_api_post_createPost(request, imgId, imgSrcIndex, title): """ 创建一个帖子(需要登陆) :param request: 请求 :param imgId: 图像Id :param imgSrcIndex: 图像索引 :param title: 标题 :return: 返回帖子对象 """ # 获取用户 ID username = get_loggined_username_or_denied(request) # 创建 Post 对象 postObj = models.Post(title=title, imageId=imgId, imageSourceIndex=imgSrcIndex, username=username) # 保存指定的 ORM 对象 dbm = request.__dbManager__ await dbm.insert(postObj) # 这里有个问题,如果没任何的评论和点赞信息,那么无法床获得对应的帖子。所以添加一个对应的默认点赞信息和评论信息 postId = postObj.postId defaultliked = models.Like(postId=postId, username='******', liked=True) defaultComment = models.Comment(postId=postId, comment="添加第一条评论吧", username="******", to_username=None) await dbm.insert(defaultComment) await dbm.insert(defaultliked) # 返回指定的对象 return {'postInfo': postObj}
def post(self, name): topic = models.Topic.get_topic(self.current_site, name) if not topic: raise tornado.web.HTTPError(404) if not self.current_user: if self.get_argument('skill_test', None) != '8': return self.reload(message='skill_test') reply_to = self.get_argument('reply_to', None) if reply_to: reply_to = models.Comment.get_by_id(int(reply_to)) comment = models.Comment(author=self.current_user, topic=topic, reply_to=reply_to, text=self.get_argument('text')) comment.update_score() topic.n_comments += 1 if self.current_user: self.current_user.n_comments += 1 db.put([topic, comment, self.current_user]) else: db.put([topic, comment]) parent_author = reply_to.author if reply_to else topic.author if parent_author and parent_author != comment.author: message = models.Message(to=parent_author, type='comment_reply', comment=comment) parent_author.n_messages += 1 db.put([message, parent_author]) self.redirect(self.request.path + '#c' + str(comment.id))
async def social_api_post_insertComment(request, postId, comment, replyUsername=None): """ 插入一个帖子中的评论 :param request: :param postId: 帖子 ID :param comment: 评论的内容(不超过200字符) :param replyUsername: 回复的用户名 :return: """ username = get_loggined_username_or_denied(request) dbm = request.__dbManager__ # 检查评论是否存在 postObj = await dbm.query(models.Post, postId=postId) if not postObj: return {'status': 1} # 新建评论 aComment = models.Comment(commentId=next_id(), username=username, comment=comment, postId=postId, to_username=replyUsername) await dbm.insert(aComment) return {'status': 0, 'comment': aComment}
def detail(slug): comment_form = CommentForm() form = ContactForm() if request.method == 'GET': db.session.rollback() selected_post = models.Entry.query.filter_by(slug=slug).first_or_404( description='Post does not exist') comments = selected_post.comments list_of_comments = [i for i in comments] no_of_comments = (len(list_of_comments)) categories = models.Entry.query.with_entities( models.Entry.category).all() return render_template('blog-post.html', post=selected_post, comment_form=comment_form, form=form, slug=slug, comments=comments, no_of_comments=no_of_comments, categories=categories) else: selected_post = models.Entry.query.filter_by(slug=slug).first() if comment_form.validate_on_submit(): comment = models.Comment(body=comment_form.body.data, name=comment_form.name.data, email=comment_form.email.data, article=selected_post, website=comment_form.website.data) models.Comment.save(comment) flash("Your comment has been added to the post", "success") return redirect(url_for('detail', slug=slug))
def setup(self): self.user = models.User(id=1, username='******') self.post = models.Post(id=1, user_id=1) self.post.user = self.user self.comment = models.Comment( post_id=1, user_id=1, text='Test text', created='2020-01-02', ) self.subcomment = models.SubComment(comment_id=1, user_id=1, text='Test text', created='2020-01-02') self.subcomment.user = self.user self.comment.user = self.user self.comment.post = self.post self.comment.subcomments = [self.subcomment] self.app = flask_init.app.test_client() self.app.testing = True
def idea_comment(idea_id): name = request.form.get('name') comment = request.form.get('comment') if name == '' or comment == '': # no name or comment, return to page return redirect(request.referrer) #get the idea by id try: idea = models.Idea.objects.get(id=idea_id) except: # error, return to where you came from return redirect(request.referrer) # create comment comment = models.Comment() comment.name = request.form.get('name') comment.comment = request.form.get('comment') # append comment to idea idea.comments.append(comment) # save it idea.save() return redirect('/ideas/%s' % idea.slug)
def pow(val): form = CommentForm() deleteform = DeleteForm() if form.validate_on_submit() and form.comment.data: comment = models.Comment(comment=form.comment.data, userid=current_user.id, powid=val) db.session.add(comment) db.session.commit() # elif deleteform.validate_on_submit(): # return redirect('/about') comments = models.Comment.query.filter(models.Comment.powid == val).all() pow = models.Prisoner.query.filter_by(id=val).first_or_404() surname = pow.surname capture = pow.Capture firstnames = pow.first_names if firstnames == None: firstnames = pow.initial count = models.Prisoner.query.filter(models.Prisoner.capture == capture.id).count() # grammar for prisoner page if isinstance(capture.date, str) == True: inor = "on" sent = "on this date" else: inor = "in" sent = "at this location" return render_template("prisoner.html", val=val, prisoner=pow, first_names=firstnames, inor=inor, sent=sent, count=count, form=form, comments=comments)
def create_comment(db: Session, comment: schemas.CommentBase): '插入评论表' print(comment) db_comment = models.Comment(**comment.dict()) db.add(db_comment) db.commit() db.refresh(db_comment) return db_comment
def create_comment(db: Session, comment: schemas.CommentCreate): db_comment = models.Comment(name=comment.name, description=comment.description, image_id=comment.image_id) db.add(db_comment) db.commit() db.refresh(db_comment) return db_comment
def create_comment(db: Session, comment: schemas.CommentCreate): db_comment = models.Comment(writer=comment.writer, contents=comment.contents, article_id=comment.article_id, parent_id=comment.parent_id) db.add(db_comment) db.commit() db.refresh(db_comment) return db_comment
def post(self): body = request.get_json() # TODO validation comment = models.Comment(**body).save() serialized_data = { 'id': str(comment.id), 'message': 'Comment {0} successfully created.'.format(comment.id) } return Response(json.dumps(serialized_data), mimetype="application/json", status=201)
def comment(): form = CommentForm(request.form) if request.method == 'POST' and form.validate(): comment = models.Comment(str(uuid.uuid4()),str(form.suggestionid.data),str(session['uuid']),form.comment.data,datetime.datetime.now()) models.db.session.add(comment) models.db.session.commit() flash('Your comment was posted successfully') return redirect(url_for('getonesuggestion',suggestid=form.suggestionid.data)) return redirect(url_for('getonesuggestion',suggestid=form.suggestionid.data))
def comment_new(post_id): post = models.Post.query.get(post_id) form = forms.CommentForm() if form.validate_on_submit(): comment = models.Comment(form.commenter.data, form.body.data, post_id) db.session.add(comment) db.session.commit() return redirect(url_for('.show', id=post_id)) return render_template('post/show.slim', post=post, form=form)
def comment(): form = CommentForm(request.form) if request.method == 'POST' and form.validate(): comment = models.Comment(str(uuid.uuid4()),str(form.suggestionid.data),str(session['uuid']),form.comment.data,datetime.datetime.now()) models.db.session.add(comment) models.db.session.commit() flash('Thanks for the comment') return redirect('/suggestion') return redirect('/suggestion')
def post_comment(data): """Posts a given comment to the comments""" # Add comment to DB the_comment = models.Comment(data["post_id"], data["username"], data["pfp"], data["comment_text"]) DB.session.add(the_comment) DB.session.commit() # Update comments client-side emit_comments(data["post_id"]) emit_likes(data["post_id"], data["username"])
def post(self): gUser = users.get_current_user() Author = models.User.get_by_id(gUser.user_id()).key comment = self.request.get('comments') new_comment = models.Comment(comText = comment) new_comment_key = new_comment.put(); commentList = models.Comment.query().fetch() commentList.append(new_comment_key.get()) comment_template = jinja_env.get_template("templates/comments.html") self.response.write(comment_template.render({'comments_info' : commentList}))
def create_new_comment(): logging.info("creating new comment") logging.info(request.json) comment = models.Comment( text=request.json.get('text'), author=request.json.get('author') ) comment.put() response.content_type = 'application/json' return models.comment_to_json(comment)
def mutate(self, info, username, small_app_id, **kwargs): user = User.get_query(info).filter( models.User.name == username).first() assert user is not None, f"User '{username}' does not exist" small_app = SmallApp.get_query(info).filter( models.SmallApp.id == small_app_id).first() assert small_app is not None, f"Small app '{small_app_id}' does not exist" new_comment = models.Comment(user=user, small_app=small_app, **kwargs) db_session.add(new_comment) db_session.commit() return CreateComment(comment=new_comment, ok=True)
def timeline(): if current_user.is_authenticated: posts = dbmanager.new_posts_for_user(current_user) else: posts = dbmanager.new_posts_public() for i, post in enumerate(posts): post.commentform = CommentForm(prefix='comment{0}'.format(i)) post.likeform = IncreaseLikeForm(prefix='like{0}'.format(i)) if request.method == 'POST': for post in posts: if current_user.is_authenticated: post.commentform.author.data = current_user.name if 'prefix' in request.form and request.form['prefix'] == post.likeform._prefix: post.n_likes += 1 db.session.commit() logging.info('Increased like count for {0}'.format(post)) if 'safari' in request.headers.get('User-Agent').lower(): return redirect(url_for('timeline')) else: return '', 304 elif (post.commentform.author.data or post.commentform.text.data) and post.commentform.validate_on_submit(): logging.info('Comment is submitted for Post {0}'.format(post)) logging.info('post.commentform.author.data = {0}'.format(post.commentform.author.data.encode('utf-8', 'replace'))) logging.info('post.commentform.text.data = {0}'.format(post.commentform.text.data.encode('utf-8', 'replace'))) logging.info('post.commentform.visibility.data = {0}'.format(post.commentform.visibility.data.encode('utf-8', 'replace'))) comment = models.Comment( author = post.commentform.author.data, text = post.commentform.text.data, post = post ) comment.groups.append(dbmanager.group_by_name(post.commentform.visibility.data)) if current_user.is_authenticated: comment.user = current_user db.session.add(comment) db.session.commit() notify_new_comment( post.commentform.author.data, post.commentform.visibility.data, comment ) if not current_user.is_authenticated and post.commentform.visibility.data == 'admin': flash( 'Your comment is submitted, ' 'but you set it to \'private\' and are not logged in, ' 'so you will not be able to see it' ) else: flash('Your comment is submitted!') return redirect(url_for('timeline')) logging.info('is_admin: {0}'.format(current_user_is_admin())) return render_template('timeline.html', posts=posts, is_admin=current_user_is_admin())
def add_comment(self): try: pid = int(self.get_argument('pid', '')) cid = int(self.get_argument('cid', '')) cdata = json.loads(self.get_argument('post', '')) cdata['poster_name'] = tornado.escape.xhtml_escape( cdata['poster_name']) cdata['poster_email'] = tornado.escape.xhtml_escape( cdata['poster_email']) cdata['contents'] = markdown2.markdown(cdata['contents'], safe_mode='escape') if cid == -1: co = models.Comment( post_id=pid, poster_name=cdata['poster_name'], poster_email=cdata['poster_email'], time=datetime.datetime.now( pytz.timezone(self.get_app_config()['timezone'])), contents=cdata['contents']) else: co = models.Comment( parent_id=cid, poster_name=cdata['poster_name'], poster_email=cdata['poster_email'], time=datetime.datetime.now( pytz.timezone(self.get_app_config()['timezone'])), contents=cdata['contents']) self.application.db_session.add(co) self.application.db_session.commit() except: self.send_error(400) return # del cdata['pid']; # del cdata['cid']; cdata['id'] = str(co.id) cdata['time'] = modules.time_to_string(co.time) self.write(json.dumps(cdata))
def comment(request, id): username = request.session.get("myuser") user = models.Fuser.objects.get(username=username) good = models.Goods.objects.get(id=id) if request.method == "POST": comm = request.POST.get('comment') print comm cobj = models.Comment(comment=comm, user=user, goods=good) cobj.save() url = "/item/%s/" % (id) return HttpResponseRedirect(url) return render(request, 'comment.html', {'good': good})