def test_submissionsentiment_model(session): s = Submission.create(session, **MOCK_SUBMISSION) c1 = Comment.create(session, **MOCK_COMMENT1) c1_sentiment = comment_sentiment(c1) c1s = CommentSentiment.create(session, **c1_sentiment) c2 = Comment.create(session, **MOCK_COMMENT2) c2_sentiment = comment_sentiment(c2) c2s = CommentSentiment.create(session, **c2_sentiment) comments = session.query(Comment).options(joinedload("sentiment")).all() comment_sentiments = [] for c in comments: comment_sentiments.append({"polarity": c.sentiment.polarity, "subjectivity": c.sentiment.subjectivity}) submission_sentiment = comment_sentiment_avg(comment_sentiments) submission_sentiment.update({"submission_id": s.id}) ss = SubmissionSentiment.create(session, **submission_sentiment) submission_sentiments = session.query(SubmissionSentiment).all() ss1 = submission_sentiments[0] # test object form assert ss1.id == 1 assert ss1.submission_id == s.id for k in submission_sentiment.keys(): assert getattr(ss1, k) == submission_sentiment[k] # test values assert ss1.polarity < 0.5 and ss1.polarity > -0.5 assert ss1.subjectivity > 0.8
def comment_view(request, identifier): if request.method == 'POST': snippet = Snippet.objects.get(pk=(int(identifier))) c = Comment( snippet=snippet, user=request.user, text=request.POST['text']) c.save() return redirect('/snippet/' + identifier)
def test_commentsentiment_model(session): s = Submission.create(session, **MOCK_SUBMISSION) c1 = Comment.create(session, **MOCK_COMMENT1) c1_sentiment = comment_sentiment(c1) c1s = CommentSentiment.create(session, **c1_sentiment) c2 = Comment.create(session, **MOCK_COMMENT2) c2_sentiment = comment_sentiment(c2) c2s = CommentSentiment.create(session, **c2_sentiment) # test object form for k in c1_sentiment.keys(): assert getattr(c1s, k) == c1_sentiment[k] # test relationship assert c1.sentiment == c1s # test values assert c1s.id == 1 assert c1s.polarity > 0.5 assert c1s.subjectivity > 0.8 assert c2s.id == 2 assert c2s.polarity < -0.5 assert c2s.subjectivity > 0.8
def rebuild(): if config == 'development': with app.app_context(): db.drop_all() db.create_all() Role.insert_roles() admin_me = User(email=app.config['FLASKR_ADMIN'], username=app.config['MY_USERNAME'], password=app.config['MY_PASSWORD'], confirmed=True, name=forgery_py.name.full_name(), location=forgery_py.address.city(), about_me=forgery_py.lorem_ipsum.sentences(10), member_since=forgery_py.date.date(True, min_delta=10)) db.session.add(admin_me) ordinary_me = User(email=forgery_py.internet.email_address(), username='******', password='******', confirmed=True, name=forgery_py.name.full_name(), location=forgery_py.address.city(), about_me=forgery_py.lorem_ipsum.sentences(10), member_since=forgery_py.date.date(True, min_delta=10)) db.session.add(ordinary_me) db.session.commit() User.generate_fake(30) Post.generate_fake(500) Follow.generate_fake(500) Comment.generate_fake(500) else: print('Permission denied.')
def addComment(request): """ Respond to an HTTP request to add a comment to an oligo, at the URL ...app/addComment :param primer: oligo primer :param rating: user's rating :type rating: 1 - 5 :param comment: user's comment :return: new comment list """ if request.method == 'GET': q = request.GET if q.__contains__('primer'): if q.__contains__('rating'): rating = q['rating'] else: rating = 0; if q.__contains__('text'): text = html.escape(q['text']) #escape evil embedded html elif q.__contains__('rating') == False: return HttpResponseBadRequest(json.dumps({'error': 'at least one of rating or text is required'})) else: text = ''; comment = Comment( primer = q['primer'], rating = rating, text = text ) comment.save() return findComments(q['primer']) return HttpResponseBadRequest(json.dumps({'error': 'primer is required'})) return HttpResponseBadRequest(json.dumps({'error':'POST not supported'}))
def article(post_id): login_form = LoginForm() register_form = RegistrationForm() post = Post.query.get_or_404(post_id) if request.method == 'POST': if not current_user.is_authenticated(): return 'please log in ' data = request.get_json(force=True) if 'content' in data.keys(): if 'self_ref_id' in data.keys(): # user cannot be set directly to current_user because this is a context variable proxy object. # the expression current_user._get_current_object() returns the actual User object. # user = current_user._get_current_object() comment = Comment(content=data['content'], user_id=current_user.id, post_id=post_id, self_ref_id=data['self_ref_id']) response_data = {'content': data['content'], 'user': current_user.nickname, 'ref_user': Comment.query.get(int(data['self_ref_id'])).user.nickname} else: comment = Comment(content=data['content'], user_id=current_user.id, post_id=post_id) response_data = {'content': data['content'], 'user': current_user.nickname} comment.save() return json.dumps(response_data) if 'voted' in data.keys(): if data['voted'] == 'False' and not post.was_voted_by(current_user): post.do_vote(current_user) voted = 'True' else: post.cancel_vote(current_user) voted = 'False' return json.dumps({'count': post.votes.count(), 'voted': voted}) comments = Post.query.get(post_id).comments form = CommentOnPostForm() return render_template('blog/post.html', post=post, form=form, comments=comments, login_form=login_form, register_form=register_form)
def comment_new(id): post = Post.get_by_id(id) if post is None or post.is_hidden: abort(404) form = CommentForm() if form.is_submitted(): try: if not form.validate(): raise Exception(_('ERROR_INVALID_SUBMISSION')) comment = Comment(user=current_user, post=post) form.populate_obj(comment) comment.save() flash(_('COMMENT_SAVE_SUCESS')) if comment.parent_comment: send_email('reply_comment', comment) else: send_email('comment', post, comment) return redirect(url_for('stamp.show', id=post.id, _anchor='comment-%s' % comment.id)) except Exception as e: flash(e.message, 'error') return render_template('main/stamp/show.html', post=post, form=form)
def test_notification_list(self): db.create_all() u1 = User(email='*****@*****.**', username='******', password='******') u2 = User(email='*****@*****.**', username='******', password='******') t = Talk(title='t', description='d', author=u1) c1 = Comment(talk=t, body='c1', author_name='n1', author_email='*****@*****.**', approved=True) c2 = Comment(talk=t, body='c2', author_name='n2', author_email='*****@*****.**', approved=True, notify=False) c3 = Comment(talk=t, body='c3', author=u2, approved=True) c4 = Comment(talk=t, body='c4', author_name='n4', author_email='*****@*****.**', approved=False) c5 = Comment(talk=t, body='c5', author=u2, approved=True) c6 = Comment(talk=t, body='c6', author_name='n6', author_email='*****@*****.**', approved=True, notify=False) db.session.add_all([u1, u2, t, c1, c2, c3, c4, c5]) db.session.commit() email_list = c4.notification_list() self.assertTrue(('*****@*****.**', 'n1') in email_list) self.assertFalse(('*****@*****.**', 'n2') in email_list) # notify=False self.assertTrue(('*****@*****.**', 'susan') in email_list) self.assertFalse(('*****@*****.**', 'n4') in email_list) # comment author self.assertFalse(('*****@*****.**', 'n6') in email_list) email_list = c5.notification_list() self.assertFalse(('*****@*****.**', 'john') in email_list) self.assertTrue(('*****@*****.**', 'n4') in email_list) # comment author
def recreate_data(): """Generate fake data for development and testing""" print 'dropping existing tables...' db.drop_all() print 'creating tables...' db.create_all() print 'inserting roles...' Role.insert_roles() print 'creating admin user...' u1 = User(username='******', email='*****@*****.**', password='******', name='Ralph Wen', location='Hangzhou, China', about_me='This is the creator of everything', confirmed=True) db.session.add(u1) print 'creating moderate user...' u2 = User(username='******', email='*****@*****.**', password='******', name='Yadong Wen', location='Hangzhou, China', about_me='Yeah', confirmed=True) db.session.add(u2) db.session.commit() print 'generating 50 normal users...' User.generate_fake(50) print 'generating 500 posts...' Post.generate_fake(500) print 'generating follows...' User.generate_following() print 'generating comments...' Comment.generate_comments() print '...done'
def test_comment_sentiment_avg(session): s = Submission.create(session, **const.MOCK_SUBMISSION) c1 = Comment.create(session, **const.MOCK_COMMENT1) c1_sentiment = sentiment.comment_sentiment(c1) c1s = CommentSentiment.create(session, **c1_sentiment) c2 = Comment.create(session, **const.MOCK_COMMENT2) c2_sentiment = sentiment.comment_sentiment(c2) c2s = CommentSentiment.create(session, **c2_sentiment) comments = session.query(Comment).\ options(joinedload('sentiment')).\ all() comment_sentiments = [] for c in comments: comment_sentiments.append({ "polarity": c.sentiment.polarity, "subjectivity": c.sentiment.subjectivity }) csa = sentiment.comment_sentiment_avg(comment_sentiments) csa.update({'submission_id': s.id}) expected_keys = ['submission_id', 'polarity', 'subjectivity'] assert sorted(csa.keys()) == sorted(expected_keys) assert isinstance(csa['polarity'], float) assert isinstance(csa['subjectivity'], float)
def add_comment(name, email, comments, post_id): comment = Comment(post_id=post_id, name=name, email=email, comments=comments) db.session.add(comment) db.session.commit() CommentService.inc_comments_count(post_id) return comment.to_dict()
def handle(changeset): print ('Received ' + str(changeset)) # Fetch project and pad ids. project_id = changeset['projectId'] pad_id = changeset['padId'] # Fetch project lock or create it, if not exists already. if project_id not in update_locks: update_locks[project_id] = Lock() update_lock = update_locks[project_id] with update_lock: # Fetch next revision number. if project_id not in revisions: revisions[project_id] = {} if pad_id not in revisions[project_id]: revisions[project_id][pad_id] = [Revision('0', None)] # Follow the changeset by all revisions not known by that user. revs = revisions[project_id][pad_id] apply_from = len(revs) for i in range(len(revs), 0, -1): if changeset['baseRev'] == revs[i - 1].id: apply_from = i break for i in range(apply_from, len(revs)): if changeset['baseLen'] == revs[i].changeset['newLen']: apply_from = i + 1 break # Fetch current revision. crtRev, baseRev = changeset['revId'], changeset['baseRev'] for i in range(apply_from, len(revs)): changeset = follow(revs[i].changeset, changeset) # Update base rev. changeset['baseRev'] = baseRev # Create new revision out of this changeset. revisions[project_id][pad_id].append(Revision(crtRev, changeset)) # Update current pad in db. changeset['projectId'], changeset['padId'] = project_id, pad_id changeset['revId'] = crtRev updateDBPad(changeset, crtRev) # Add the new comments to DB. if 'comments' in changeset: for code, comment in changeset['comments'].items(): newComment = Comment(comment['author'], comment['text']) newComment.pad_id = comment['padId'] newComment.code = comment['code'] db.session.add(newComment) db.session.commit() # Include the id of the client that generated the changeset. changeset['clientId'] = request.sid # Broadcast to all clients. emit('server_client_changeset', changeset, room=changeset['projectId']) # Send ACK to the client. emit('server_client_ack', changeset['padId'], room=request.sid)
def event_show(request, event_id): user = request.user event = Event.objects.get(pk=event_id) if request.method == 'POST': # TODO: should really be PUT if user.get_profile().is_funder: grants = [] for item in event.item_set.all(): amount = request.POST.get("item_" + str(item.id), None) if amount: amount = Decimal(amount) grant, _ =\ Grant.objects.get_or_create(funder=user.get_profile(), item=item, defaults={'amount': 0}) amount_funded = sum(grant.amount for grant in Grant.objects.filter(item=item)) amount_funded += item.funding_already_received # if the funder gave too much, # adjust the price to be only enough if amount + amount_funded - grant.amount > item.total: amount = item.total - amount_funded + grant.amount # only append if the amount has changed if grant.amount != amount: grant.amount = amount grant.save() grants.append(grant) if grants: messages.success(request, "Saved grant!") # email the event requester indicating that they've been funded event.status = 'F' # F for FUNDED event.save() event.notify_requester(grants) # try to notify osa, but osa is not guaranteed to exist try: user.get_profile().notify_osa(event, grants) except smtplib.SMTPException: pass if request.POST.get('new-comment', None): comment = Comment(comment=request.POST['new-comment'], funder=user.get_profile(), event=event) comment.save() return redirect(EVENTS_HOME) else: return redirect(EVENTS_HOME) elif request.method == 'GET': if 'id' in request.GET: event.shared_funder = \ User.objects.get(id=request.GET['id']).get_profile() return render_to_response('app/application-show.html', {'event': event}, context_instance=RequestContext(request)) else: return HttpResponseNotAllowed(['POST'])
def generate_fake(): """Generate fake data""" Role.insert_roles() admin = User(email='*****@*****.**', password='******', confirmed=True, username='******') db.session.add(admin) db.session.commit() print('Inserting admin user: [email protected]') User.generate_fake() Post.generate_fake() Comment.generate_fake() Follow.generate_fake()
def commit_comment(request): user = User.objects.get(id = 1) aid = int(request.GET.get('id')) article = Article.objects.get(id = aid) nickname = request.GET.get('nickname') content = request.GET.get('content') if nickname == '': return HttpResponse("1") elif content == '': return HttpResponse("2") comment = Comment(user = user, article = article, nickname = nickname, content =content) comment.save() return HttpResponse('提交成功')
def index(request): user = User.objects.get(id=1) userprofile = UserProfile.objects.get(id = user.id) category_list = Category.objects.filter(user=user) essays_list = Essays.objects.filter(user=user.id)[:8] pages = request.GET.get('page') #print pages if pages == 'category_article_list': #显示分类下的文章列表 category = Category.objects.get(id=request.GET['id']) article_list = Article.objects.filter(category=category) content_dict = {'articles': article_list, 'categories': category_list, 'essays': essays_list, 'category': category, 'page': pages} elif pages == 'article_list': #显示所有文章列表 #article_list = Article.objects.order_by("date", "time") article_list = Article.objects.filter(user=user)[:8] #取最近的5篇文章显示在首页,在模型中已经对文章进行排序 #article_list content_dict = {'articles': article_list, 'categories': category_list, 'essays': essays_list, 'page': pages} elif pages == 'read_article': #显示文章内容 aid = int(request.GET['id']) article = Article.objects.get(id = aid) comment_list = Comment.objects.filter(article = article) content_dict = {'article': article, 'categories': category_list, 'essays': essays_list, 'comments': comment_list, 'page': pages} elif pages == 'all_essays_list': #显示所有随笔列表 all_essays_list = Essays.objects.filter(user=user) content_dict = {'allessays': all_essays_list, 'categories': category_list, 'essays': essays_list, 'page': pages} elif pages == 'read_essays': #显示随笔内容 essay = Essays.objects.get(id = request.GET['id']) content_dict = {'categories': category_list, 'essays': essays_list, 'essay': essay, 'page': pages} elif pages == 'commit_comment': aid = int(request.GET['id']) article = Article.objects.get(id = aid) nickname = request.GET.get('nickname') content = request.GET.get('content') if nickname == '': return HttpResponse("1") elif content == '': return HttpResponse("2") comment = Comment(user = user, article = article, nickname = nickname, content =content) comment.save() #print nickname + content comment_list = Comment.objects.filter(article = article) content_dict = {'article': article, 'categories': category_list, 'essays': essays_list, 'comments': comment_list, 'page': 'read_article'} return HttpResponse("评论成功") elif pages == 'message': article_list = Article.objects.filter(user=user) content_dict = {'categories': category_list, 'essays': essays_list, 'page': pages} else: #其它 article_list = Article.objects.filter(user = user)[:8] content_dict = {'articles': article_list, 'categories': category_list, 'essays': essays_list, 'page': 'index_page', 'user': user, 'userprofile': userprofile} #print content_dict return render(request, 'blog/index.htm', content_dict)
def create_photo_collection_comment(): collection_id = int(request.form.get("comment_owner_id")) photo_collection = PhotoCollection.query.get(collection_id) collection_comment = PhotoCollectionComment() comment = Comment() comment.user_id = current_user.id comment.content = request.form.get("content") comment.date = datetime.now() collection_comment.comment = comment collection_comment.photo_collection = photo_collection db.session.add(comment) db.session.add(collection_comment) db.session.commit() return redirect(url_for("blog", photographer_id=photo_collection.photographer_id))
def post(self, slug): context = self.get_context(slug) form = context.get('form') if form.validate(): comment = Comment() form.populate_obj(comment) comment.author = context.get('author') post = context.get('post') post.comments.append(comment) post.save() return redirect(url_for('posts.detail', slug=slug)) return render_template('posts/detail.html', **context)
def create_comment(): name = parse_json(request.json, str, 'name') content = parse_json(request.json, str, 'content') post_id = parse_json(request.json, str, 'post_id') validate_name(name) comment = Comment(name, content, '192.167.1.1', post_id) db.session.add(comment) db.session.commit() response = jsonify(comment.to_json(), message='Created Comment.') response.status_code = 201 response.headers['Location'] = request.base_url + '/' + str(comment.id) print dir(response), response.mimetype return response
def post(self, post_id): content = self.get_argument('content', None) if content is None: raise exceptions.EmptyFields() else: users, content = at_content(content) username = self.current_user comment = yield gen.maybe_future( Comment.create(username, post_id, content)) # Update gold. update_gold.apply_async(('sb_2l', username, post_id)) update_gold.apply_async(('comment', username)) if users: update_gold.apply_async(('be_comment', users)) # Notify users: be comment, someone @you. notify.apply_async( ('comment', username, post_id, content)) if users: notify.apply_async( ('at', username, users, post_id, content)) raise gen.Return(comment.to_dict())
def post(self, slug, issue_id): form = self.form(request.form) issue = Issue.objects.get_or_404(id=issue_id) if form.validate(): comment = Comment(issue=issue) form.populate_obj(comment) try: comment.process(request.files) except KeyError as e: return redirect(url_for('github_login', _method='GET')) return redirect(url_for('issue_api', slug=slug, id=issue.id, _method='GET')) return redirect(url_for('issue_api', slug=slug, id=issue.id, _method='GET'))
def fake(): "Populate tables using fake data" fake = faker.Faker() upload_dir = os.path.join(manager.app.instance_path, 'uploads') if not os.path.isdir(upload_dir): os.mkdir(upload_dir) users = [User.generate(fake) for _ in range(0, 10)] user = users[0] for obj in users: db.session.add(obj) db.session.commit() pdfdata = base64.decodestring(EMPTY_PDF.strip()) docs = [Document.generate(pdfdata) for _ in range(0, 10)] for doc in docs: comments = [Comment.generate(fake, doc.id) for _ in range(0, 4)] annotations = [Annotation.generate(fake, doc.id, user.id) for _ in range(0, 2)] for obj in docs + comments + annotations: db.session.add(obj) db.session.commit()
def comment_delete(id): comment = Comment.get_by_id(id) if comment is None or not comment.can_delete: abort(403) post = comment.post try: Comment.delete(id) message = _('COMMENT_DELETE_SUCCESS') except Exception as e: message = _('ERROR_COMMENT_DELETE_FAILED', error=e) return render_view(url_for('stamp.show', id=post.id), redirect=True, message=message)
def comment(request): if request.method == "POST": if not request.body is None: if User.objects.filter(user = request.POST['user']).exists() : d = timezone.localtime(timezone.now()) comment = Comment(board = Board.objects.get(id = request.POST['board_id']), user = User.objects.get(user = request.POST['user']), content = request.POST['content'], date = d.strftime('%Y-%m-%d %H:%M:%S') ) comment.save() return JSONResponse('') return HttpResponse(status=400) else : return HttpResponse(status=400) else : return HttpResponse(status=400)
def genfake(): config = os.getenv('FLASK_CONFIG') or 'default' if config == 'default' or config == 'development': print("delete all files ...") db.drop_all() db.create_all() print("creating roles ...") Role.insert_roles() print("creating cities ...") City.insert_cities() print("creating topics ...") Topic.insert_topics() print("creating users ...") User.generate_fake() print("creating conferences ...") Conference.generate_fake() print("creating comments ...") Comment.generate_fake()
def _comment(): data = request.get_json(force=True) content = data['content'] post_id = data['post_id'] # test bar = Post.query.get(post_id).user.pyname hub.add_notice(content, bar) comment_id = int(data['comment_id']) # print type(comment_id), comment_id, type(post_id), post_id, type(current_user.id) if comment_id == 0: comment = Comment(content=content, user_id=current_user.id, post_id=post_id) else: comment = Comment(content=content, user_id=current_user.id, post_id=post_id, ref_comment_id=comment_id) comment.save() return render_template('blog/_comment_item.html', comment=comment)
def post(self): parsed = parser.parse_args() # user_id = db.session.query(User).filter(User.id == g.user['id']).first() comment = Comment(name=parsed['name'], description=parsed['text'], project_id=parsed['task_id']) task_comments = Comment.comments(comment.id, parsed['task_id']) db.session.add(task_comments) db.session.add(comment) db.session.commit() return comment, 201
def test_comment_model(session): s = Submission.create(session, **MOCK_SUBMISSION) c1 = Comment.create(session, **MOCK_COMMENT1) c2 = Comment.create(session, **MOCK_COMMENT2) db_submissions = session.query(Submission).all() db_comments = session.query(Comment).all() assert db_submissions[0].comments[0] == c1 assert db_submissions[0].comments[1] == c2 assert len(db_comments) == 2 db_c1 = db_comments[0] for k in MOCK_COMMENT1.keys(): assert getattr(db_c1, k) == MOCK_COMMENT1[k] # test relationship assert s.comments == db_comments
def add_quote(request): if request.method == 'POST': print request.POST post_quote = '' post_comment = '' post_author = '' quote_form = QuoteForm(request.POST.copy(), prefix='quote') if quote_form.is_valid(): cd = quote_form.cleaned_data post_quote = cd['quote'] post_comment = cd['comment'] post_author = cd['author'] quote = Quote() if post_comment: print 'post_comment',post_comment comment = Comment() comment.text = post_comment comment.save() quote.comment = comment author, created = Author.objects.get_or_create(name__iexact=post_author) if post_author: author.name = post_author else: author.name = 'Anonymous' author.save() quote.author = author quote.quote = post_quote quote.save() else: print "Quote_form is not valid!" data = { 'quote_text': post_quote, 'quote_comment': post_comment, 'quote_author': post_author, } return HttpResponse(simplejson.dumps(data)) raise Http404
def deploy(deploy_type): from flask_migrate import upgrade from app.models import BlogInfo, User, ArticleTypeSetting, Source, \ ArticleType, Plugin, BlogView, Comment # upgrade database to the latest version upgrade() if deploy_type == 'product': # step_1:insert basic blog info BlogInfo.insert_blog_info() # step_2:insert admin account User.insert_admin(email='*****@*****.**', username='******', password='******') # step_3:insert system default setting ArticleTypeSetting.insert_system_setting() # step_4:insert default article sources Source.insert_sources() # step_5:insert default articleType ArticleType.insert_system_articleType() # step_6:insert system plugin Plugin.insert_system_plugin() # step_7:insert blog view BlogView.insert_view() # You must run `python manage.py deploy(product)` before run `python manage.py deploy(test_data)` if deploy_type == 'test_data': # step_1:insert navs Menu.insert_menus() # step_2:insert articleTypes ArticleType.insert_articleTypes() # step_3:generate random articles Article.generate_fake(100) # step_4:generate random comments Comment.generate_fake(300) # step_5:generate random replies Comment.generate_fake_replies(100) # step_4:generate random comments Comment.generate_fake(300)
def post_details_and_comment(request, pk): post = Post.objects.get(pk=pk) if request.method == 'GET': post.likes_count = post.like_set.count() context = { 'post': post, 'form': CommentForm(), 'can_delete': request.user == post.user.user or request.user.is_staff, 'can_edit': request.user == post.user.user or request.user.is_staff, 'can_like': request.user != post.user.user, 'has_liked': post.like_set.filter(user_id=request.user.userprofile.id).exists(), 'can_comment': request.user != post.user.user or request.user.is_staff, } return render(request, 'post_details.html', context) else: form = CommentForm(request.POST) if form.is_valid(): comment = Comment(text=form.cleaned_data['text'], ) comment.post = post comment.user = request.user.userprofile comment.save() return redirect('post details', pk) context = { 'post': post, 'form': form, } return render(request, 'post_details.html', context)
def submit_comment(): form = CommentForm() if form.validate_on_submit(): comment = Comment( text=comment_form.comment.data, user_id=current_user.id, punch_id=form.punch_id.data, event_id=form.event_id.data, ) db.session.add(comment) db.session.commit() if form.punch_id.data: comment.notify( edited_user=user, url=url_for( 'punch.edit', username=user.username, punch_id=punch_id, ), item=f"{user.display_name_short()}'s punch card", ) log_new(comment, 'commented on a punch card') if form.event_id: comment.notify( edited_user=user, url=url_for( 'schedule.leave_edit', username=user.username, leave_id=leave_id, ), item=f"{user.display_name_short()}'s leave request", ) log_new(comment, 'commented on an event') flash('Comment added successfully!', 'success') return redirect(request.referer)
def setUp(self): self.author_Jon = Writer(username='******', password='******', email='*****@*****.**') self.new_blog = Blog(post='some dummy blog', writer=self.author_Jon) self.new_comment = Comment(blog_id=15, body="some rude comment")
def setUp(self): self.new_comment = Comment(id = 1, comment = 'comment', user = self.user_tina, blog_id = self.new_blog)
def test_comments(self): # add two users r = Role.query.filter_by(name='User').first() self.assertIsNotNone(r) u1 = User(email='*****@*****.**', username='******', password='******', confirmed=True, role=r) u2 = User(email='*****@*****.**', username='******', password='******', confirmed=True, role=r) db.session.add_all([u1, u2]) db.session.commit() # add a post post = Post(body='body of the post', author=u1) db.session.add(post) db.session.commit() # write a comment response = self.client.post( '/api/v1/posts/{}/comments/'.format(post.id), headers=self.get_api_headers('*****@*****.**', 'dog'), data=json.dumps({'body': 'Good [post](http://example.com)!'})) self.assertEqual(response.status_code, 201) json_response = json.loads(response.get_data(as_text=True)) url = response.headers.get('Location') self.assertIsNotNone(url) self.assertEqual(json_response['body'], 'Good [post](http://example.com)!') self.assertEqual(re.sub('<.*?>', '', json_response['body_html']), 'Good post!') # get the new comment response = self.client.get(url, headers=self.get_api_headers( '*****@*****.**', 'cat')) self.assertEqual(response.status_code, 200) json_response = json.loads(response.get_data(as_text=True)) self.assertEqual('http://localhost' + json_response['url'], url) self.assertEqual(json_response['body'], 'Good [post](http://example.com)!') # add another comment comment = Comment(body='Thank you!', author=u1, post=post) db.session.add(comment) db.session.commit() # get the two comments from the post response = self.client.get( '/api/v1/posts/{}/comments/'.format(post.id), headers=self.get_api_headers('*****@*****.**', 'dog')) self.assertEqual(response.status_code, 200) json_response = json.loads(response.get_data(as_text=True)) self.assertIsNotNone(json_response.get('comments')) self.assertEqual(json_response.get('count', 0), 2) # get all the comments response = self.client.get( '/api/v1/posts/{}/comments/'.format(post.id), headers=self.get_api_headers('*****@*****.**', 'dog')) self.assertEqual(response.status_code, 200) json_response = json.loads(response.get_data(as_text=True)) self.assertIsNotNone(json_response.get('comments')) self.assertEqual(json_response.get('count', 0), 2)
def setUp(self): self.new_comment = Comment(id=1, comment='Test comment', user=self.user_karanja, blog_id=self.new_blog)
def test_get_comments_by_id(self): self.new_comment.save_comment()() got_comments = Comment.get_comments(1) self.assertTrue(len(got_comments) == 1)
from app import create_app, db from app.models import User, Role, Post, Follow, Comment from flask.ext.script import Manager, Shell from flask.ext.migrate import Migrate, MigrateCommand app = create_app('default') manager = Manager(app) migrate = Migrate(app, db) def make_shell_context(): return dict(app=app, db=db, User=User, Role=Role, Post=Post, Follow=Follow, Comment=Comment) manager.add_command('shell', Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) #数据库迁移指令 ''' 脚本命令 cd E:\Python_project\Flasky python manage.py runserver --host 0.0.0.0 创建数据库迁移仓库: python manage.py db init 迁移脚本 python manage.py db migrate -m "initial migration" 更新数据库: python manage.py db upgrade #运行脚本环境 python manage.py shell Comment.generate_comments() http://gravatar.com/avatar/ http://gravatar.com/avatar/4bc7e8834a6fd8f9334ef878ad58ecf5 ''' if __name__ == '__main__': #app.run(host = '0.0.0.0')
def get_comments(): comment = Comment(**request.json) db.session.add(comment) db.session.commit() return comment.to_dict()
def comment_oppose(comment_id): comment = Comment().query.filter_by(comment_id=comment_id).first() comment.comment_oppose += 1 db.session.add(comment) db.session.commit() return redirect(url_for("main.get_article", article_id=comment.article_id))
def setUp(self): self.new_blog = Blogs(blog='i love life') self.new_comment = Comment(comment='live life', blogs=self.new_blog)
def test_get_comments(self): self.new_comment.save_comment() get = Comment.get_comment(self.new_blog.id) self.assertTrue(len(get) == 1)
def submit_answer(): try: current_user = get_jwt_identity() user = db.session.query(User).filter(User.email==func.binary(current_user)).first() if user is None: return response_error(MESSAGE.USER_INVALID_EMAIL, CODE.USER_INVALID_EMAIL) data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) review_type = request.args.get('type', '') object_id = request.args.get('id', -1) if len(review_type) == 0 or \ object_id == -1: return response_error(MESSAGE.ANSWER_INVALID_INPUT, CODE.ANSWER_INVALID_INPUT) result = answer_bl.is_valid_object_id(review_type, object_id) if result is None: return response_error(MESSAGE.ANSWER_INVALID_INPUT, CODE.ANSWER_INVALID_INPUT) rt = db.session.query(ReviewType).filter(ReviewType.name==func.binary(review_type)).first() ratings = data['ratings'] if ratings is not None: for r in ratings: if answer_bl.is_answer_question(user.id, review_type, object_id, r['question_id']): return response_error(MESSAGE.ANSWER_QUESTION_ALREADY, CODE.ANSWER_QUESTION_ALREADY) rating = Rating( point=r['rating'], question_id=r['question_id'], object_id=object_id, user_id=user.id ) db.session.add(rating) db.session.flush() comment = r['comment'] if comment is not None: c = Comment( desc=comment, rating_id=rating.id ) db.session.add(c) db.session.flush() else: return response_error(MESSAGE.ANSWER_INVALID_INPUT, CODE.ANSWER_INVALID_INPUT) if review_type == CONST.Type['People']: user = User.find_user_by_id(object_id) if user is not None: user.rating_count = people_bl.count_rating_for_object(user, CONST.Type['People']) user.comment_count = people_bl.count_comments_for_object(user, CONST.Type['People']) db.session.flush() elif review_type == CONST.Type['Team']: team = Team.find_team_by_id(object_id) if team is not None: team.rating_count = people_bl.count_rating_for_object(team, CONST.Type['Team']) team.comment_count = people_bl.count_comments_for_object(team, CONST.Type['Team']) db.session.flush() elif review_type == CONST.Type['Company']: company = Company.find_company_by_id(object_id) if company is not None: company.rating_count = people_bl.count_rating_for_object(company, CONST.Type['Company']) company.comment_count = people_bl.count_comments_for_object(company, CONST.Type['Company']) db.session.flush() db.session.commit() return response_ok() except Exception, ex: db.session.rollback() return response_error(ex.message)
def blog(blog_id): blog = Blog.query.filter_by(id=blog_id).first() comments = Comment.get_comments_by_blog_id(blog_id) return render_template('blog.html', blog=blog, comments=comments)
def setUp(self): self.new_comment = Comment(id = 1, comment = 'its cool', user_id = 2 , pitchs_id = 4)
def test_markdown(self): c = Comment() c.body = '# title\n\n## section\n\ntext **bold** and *italic*' self.assertTrue(c.body_html == '<h1>title</h1>\n<h2>section</h2>\n' '<p>text <strong>bold</strong> ' 'and <em>italic</em></p>')
def test_get_pitch_by_id(self): self.new_comment.save_pitch() got_comments = Comment.get_comments(1234) self.assertTrue(len(got_comments) == 1)
user1 = User(nickname="demo", email="*****@*****.**") song1 = Song(title="Song 1", genre="Rap", description="description 1", image_url="image placeholder", song_url="song placeholder", user_id=1, created_at="2020-06-06 16:56:54.271262") song2 = Song(title="Category 2", genre="Pop", description="description 2", image_url="image placeholder 2", song_url="song placeholder 2", user_id=1, created_at="2020-06-06 16:56:54.271262") comment1 = Comment(comment="comment 1", user_id=1, song_id=1) comment2 = Comment(comment="comment 2", user_id=1, song_id=2) db.session.add(user1) db.session.add(song1) db.session.add(song2) db.session.add(comment1) db.session.add(comment2) # db.session.add(user1) # db.session.add(cat1) # db.session.add(cat2) # db.session.add(set1) # db.session.add(set2) # db.session.add(card1) # db.session.add(card2) # db.session.add(card3)
def setUp(self): self.user_john = User(username = '******', password = '******', email = '*****@*****.**') self.new_post = Post(id = 1, post_title = 'Test', post_content = 'This is a test post', category = 'health', user = self.user_john) self.new_comment = Comment(id = 1, comment = 'Test comment', user = self.user_john, post_id = self.new_post)
def archive_last_thousand_comments(self, subreddit_name): # fetch the subreddit ID subreddit = self.db_session.query(Subreddit).filter( Subreddit.name == subreddit_name).first() # fetch the last thousand comment IDs comment_ids = [ x['id'] for x in self.db_session.execute( text( "select id from comments WHERE subreddit_id='{0}' ORDER BY created_utc DESC LIMIT 1000;" .format(subreddit.id))) ] # fetch comments from reddit comments = [] try: limit_found = False after_id = None while (limit_found == False): comment_result = self.r.get_comments( subreddit=subreddit_name, params={"after": after_id}, limit=100) comments_returned = 0 for comment in comment_result: comments_returned += 1 if (os.environ['CS_ENV'] != 'test'): comment = comment.json_dict if (comment['id'] in comment_ids): limit_found = True else: comments.append(comment) after_id = "t1_" + comment['id'] if (comment_result is None or comments_returned == 0): limit_found = True except praw.errors.APIException: self.log.error( "Error querying latest {subreddit_name} comments from reddit API. Immediate attention needed." .format(subreddit_name=subreddit_name)) sys.exit(1) db_comments = [] for comment in comments: if ((comment['id'] in comment_ids) != True): db_comment = Comment( id=comment['id'], subreddit_id=subreddit.id, created_utc=datetime.datetime.utcfromtimestamp( comment['created_utc']), post_id=comment['link_id'].replace("t3_", ""), user_id=comment['author'], comment_data=json.dumps(comment)) db_comments.append(db_comment) try: self.db_session.add_all(db_comments) self.db_session.commit() except sqlalchemy.exc.DBAPIError as e: self.log.error( "Error saving {0} comments to database. Immediate attention needed. Error: {1}" .format(len(db_comments)), str(e)) self.log.info( "Fetching up to the last thousand comments in {subreddit_name}. Total comments archived: {num_comments}" .format(subreddit_name=subreddit.name, num_comments=len(db_comments)))
db.commit() # Insert posts. db.add_all([ Post(title='Donec posuere metus vitae ipsum', post_url='https://buzzfeed.com/in/imperdiet/et/commodo/vulputate.png', user_id=1), Post(title='Morbi non quam nec dui luctus rutrum', post_url='https://nasa.gov/donec.json', user_id=1), Post(title='Donec diam neque, vestibulum eget, vulputate ut, ultrices vel, augue', post_url='https://europa.eu/parturient/montes/nascetur/ridiculus/mus/etiam/vel.aspx', user_id=2), Post(title='Nunc purus', post_url='http://desdev.cn/enim/blandit/mi.jpg', user_id=3), Post(title='Pellentesque eget nunc', post_url='http://google.ca/nam/nulla/integer.aspx', user_id=4) ]) db.commit() # Insert comments. db.add_all([ Comment(comment_text='Nunc rhoncus dui vel sem.', user_id=1, post_id=2), Comment(comment_text='Morbi odio odio, elementum eu, interdum eu, tincidunt in, leo. Maecenas pulvinar lobortis est.', user_id=1, post_id=3), Comment(comment_text='Aliquam erat volutpat. In congue.', user_id=2, post_id=1), Comment(comment_text='Quisque arcu libero, rutrum ac, lobortis vel, dapibus at, diam.', user_id=2, post_id=3), Comment(comment_text='In hac habitasse platea dictumst.', user_id=3, post_id=3) ]) db.commit() # Insert votes. db.add_all([ Vote(user_id=1, post_id=2), Vote(user_id=1, post_id=4), Vote(user_id=2, post_id=4), Vote(user_id=3, post_id=4), Vote(user_id=4, post_id=2)
def setUp(self): self.new_comment = Comment(id=1, comment='Test comment', dateposted=2020 / 5 / 11)
def test_get_comment(self): self.new_comment.save() got_comment = Comment.get_comment(1) self.assertTrue(got_comment is not None)
def setUp(self): self.user_tina = User(username='******', password='******', email='*****@*****.**') self.new_blog = Blog(id=1, title='Test', post='post', user_id=self.user_tina.id) self.new_comment = Comment(id=1, comment ='comment', user_id=self.user_tina.id, blog_id = self.new_blog.id )
def setUp(self): self.user_James = User(username = '******',password = '******', email = '*****@*****.**') self.new_post = Post(id=1234,user_id=6,category='meat',posted_at='5',comments='none') self.new_comment = Comment(id=12345,user_id=6, post_id=7, pitch_comment='Eat food',user = self.user_James,post=self.new_post )
def test_comment(self): comment = Comment(content='love and culture', created_at='', updated_at='') db.session.add(comment) self.assertEqual(comment.content, 'love and culture')
def setUp(self): self.user_wecode = User(id=1, username='******', password='******', email='*****@*****.**') self.new_comment = Comment(id=1, name='Money', pitch_id=1)
def post(post_id): """ 文章详情视图,该视图处理发表评论功能 :param post_id: 文章 id """ post = Post.query.filter_by(id=post_id, trash=False, published=True).first_or_404() reply_id = request.args.get('reply_id') admin = Admin.query.first() per_page = admin.comment_per_page admin_email = admin.email # 该文章下不在回收站中、已审核且不是回复其它评论的评论 Pagination 对象 comment_pagination = Comment.query.with_parent(post).filter_by( trash=False, reviewed=True, replied_id=None).order_by( Comment.create_time.desc()).paginate(per_page=per_page) form = CommentForm(request.form) # 根据用户登录状态设置不同的字段数据 if current_user.is_authenticated: form.author.data = admin.nickname from_admin = True reviewed = True flash_message = '评论已发布。' else: from_admin = False reviewed = False flash_message = '您的评论会尽快被审核,感谢您的评论。' if form.validate_on_submit(): # 如果文章不允许评论,则直接返回 if not post.can_comment: flash('评论已关闭!', 'warning') return redirect_back() with db.auto_commit(): comment = Comment() comment.set_attr(form.data) comment.from_admin = from_admin comment.reviewed = reviewed comment.post = post if reply_id: replied_comment = Comment.query.get_or_404(reply_id) if replied_comment.trash or not replied_comment.reviewed or replied_comment.post.id != post.id: abort(404) comment.replied = replied_comment db.session.add(comment) flash(flash_message, 'primary') # 如果不是已登录用户,则发送邮件通知管理员审核 if not current_user.is_authenticated: send_mail([admin_email], '博客有新的评论需要审核', 'email/new_comment.html', post=post) return redirect( url_for('web.post', post_id=post.id, _anchor="commentResponse")) fields_name, fields_errors = get_form_error_items(form) # 如果是回复评论且表单验证失败,则跳转至专门显示表单错误的页面 if reply_id and form.errors: if request.referrer and is_safe_url(request.referrer): back_url = request.referrer else: back_url = url_for('web.post', post_id=post.id) return redirect( url_for('web.reply_error', fields_errors=','.join(fields_errors), back_url=back_url)) # 如果是主评论表单填写错误,flash 一条信息 if form.errors: flash('评论表单填写有误。', 'danger') return render_template('blog/post.html', post=post, comment_pagination=comment_pagination, form=form, fields_errors=fields_errors, fields_name=fields_name)
def setUp(self): self.user_James = User(username='******', password='******', email='*****@*****.**') self.new_comment = Comment(comment_id=12345, pitch_comment='This is awesome', user=self.user_James)
def create(self, request, apikey, apisignature): print "creating" if not key_check( apikey, apisignature, '/idea/comment/'): return {'error':'authentication failed'} else: print commentForm = CommentForm({"comment":request.POST['comment']}) if commentForm.is_valid(): print "form valid" clean = commentForm.cleaned_data print clean print request.POST idea = Idea.objects.get(id = request.POST['idea_id']) print idea try: print "trying" comment = Comment( text = clean['comment'], user = User.objects.get(id = request.POST['user_id']), idea = idea) print comment except Idea.DoesNotExist: return {'error':'no idea'} except User.DoesNotExist: return {'error':'no user'} else: comment.save() #helpers.filter_tags(clean['tags'], idea) print comment return comment else: return {'error':'no comment'}