def post_comments(userid, picid, content, time, reply_to): result = models.Comment(userId=userid, content=content, time=time, reply_to=reply_to, picId=picid) db.session.add(result) db.session.commit() return {'created': 'Post the comment .'}
def handle(self, *args, **options): for order in models.Order.objects.all(): for timeslot in order.timeslot_set.filter(comment__isnull=True): fake_comment = models.Comment() fake_comment.score = timeslot.id % 5 + 1 fake_comment.content = "fake comment {id}".format( id=timeslot.id) fake_comment.save() timeslot.comment = fake_comment timeslot.save()
def add_comment(): if request.form.get("comment"): com_obj = models.Comment(user_id=session['id'], content=request.form.get("comment"), movie_id=request.args.get('movie_id')) mysql_db.session.add(com_obj) mysql_db.session.commit() else: flash('请填写评论!!', category='add') return redirect( url_for('home.play') + '?id={}'.format(request.args.get('movie_id')))
def create_comment(db: Session, comment: schemas.CommentCreate, current_user): post = db.query( models.Post).filter(models.Post.id == comment.post_id).first() if not post: raise HTTPException(status_code=404, detail="Post not found") new_comment = models.Comment(comment=comment.comment, owner_id=current_user.id, post_id=comment.post_id) db.add(new_comment) db.commit() db.refresh(new_comment) return new_comment
def post(subreddit, pid): form = PostCommentForm(request.form) post = models.Post.query.filter(models.Post.id == pid).one() comments = models.Comment.query.filter(models.Comment.post_id == pid).all() if request.method == 'POST': comment = models.Comment(post_id=pid, text=form.text.data) db.session.add(comment) db.session.commit() return redirect('/r/%s/%s' % (subreddit, pid)) return render_template('post.html', form=form, post=post, comments=comments)
def poll(poll): poll1 = poll.replace('-', ' ') poll1 = poll1.replace('~', '?') vote_form = VoteForm() voted = False var = models.isVoted.query.filter_by(user_id=g.user.id) vote_list = [x for x in var] if vote_list: for vote in vote_list: if vote.poll_id == models.Poll.query.filter_by( body=poll1).first().id: voted = True #vote form ki choice field me choices add (to make a dynamic list for selection) vote_form.choice.choices = [ (str(x.choice_id), str(x.value)) for x in models.Poll.query.filter_by(body=poll1).first().choices.all() ] #adding pie chart c = [x for x in models.Poll.query.filter_by(body=poll1).first().choices] choice_vote = [['choice', 'votes']] for choice in c: choice_vote.append([str(choice), int(choice.votes)]) if vote_form.validate_on_submit(): # add a vote to the choice models.Choice.query.get(vote_form.choice.data).vote() voted = models.isVoted( user_id=g.user.id, poll_id=int(models.Poll.query.filter_by(body=poll1).first().id), option_id=vote_form.choice.data) #update the isVoted table db.session.add(voted) if vote_form.comment.data is not None and vote_form.comment.data != '': comment = models.Comment(choice_id=vote_form.choice.data, user_id=g.user.id, body=vote_form.comment.data, anonymous=vote_form.anonymous.data) db.session.add(comment) db.session.commit() flash('Voted Successfully') return redirect(url_for('poll', poll=poll)) return render_template( 'vote.html', poll=models.Poll.query.filter_by(body=poll1).first(), form=vote_form, voted=voted, choice_vote=choice_vote)
def send_reply(request): new_comment = models.Comment() pid = request.POST.get('p_id', -1) oid = request.POST.get('o_id', -1) properti = models.Property.objects.get(id=pid) orderr = models.Order.objects.get(id=oid) if properti and orderr: new_comment.star_rate = request.POST.get('star_rate', 80) new_comment.content = request.POST.get('msg', '') new_comment.tenantID = request.user new_comment.propertyID = properti new_comment.save() orderr.commented = True orderr.save() return HttpResponse(1) else: return HttpResponse(0)
def comment_ok(): form_post_id = request.form['post_id'] form_nick = request.form['nickname'] form_email = request.form['email'] form_comment = request.form['comment'] try: c = models.Comment() c.post_id = int(form_post_id) c.nickname = form_nick c.email = form_email c.body = form_comment db.session.add(c) db.session.commit() except: flash("Comment wasn't saved. Try again?") return redirect(url_for('view_post', post_id = form_post_id)) return redirect(url_for('view_post', post_id = form_post_id))
def home(): say_something_form = forms.SaySomething() captcha = CAPTCHA.create() messages = models.Comment.query.with_entities(models.Comment.author, models.Comment.message, models.Comment.datetime) if request.method == 'GET': return render_template("home.j2", title="Home", form=say_something_form, messages=messages, subject_name=app.config['SUBJECT_NAME'], captcha=captcha, retain_author="", retain_message="") if request.method == 'POST': if say_something_form.validate_on_submit(): c_hash = request.form.get('captcha-hash') c_text = request.form.get('captcha-text') author = say_something_form.author.data message = say_something_form.message.data if c_text == "" or CAPTCHA.verify(c_text, c_hash) == False: flash("Captcha Incorrect.") elif CAPTCHA.verify(c_text, c_hash): remote_addr = request.remote_addr comment = models.Comment(author=author, message=message, remote_addr=remote_addr) db.session.add(comment) try: db.session.commit() except: flash("Something went wrong.") return render_template("home.j2", title="Home", form=say_something_form, messages=messages, subject_name=app.config['SUBJECT_NAME'], captcha=captcha, retain_author=author, retain_message=message)
def new_comment(advert_id): if request.method == 'POST': post_data = request.get_json() if not validator.new_comment(post_data): return jsonify({ "comment": 'None', "error": "you must provide a valid data" }), 400 advert_obj = models.Advert.query.get(advert_id) comment = models.Comment(text_comment=post_data["data"], timestamp=datetime.utcnow(), user_id=current_identity.id, advert_id=advert_obj.id) db.session.add(comment) db.session.commit() # return redirect('/adverts/%s/comments/%s' % (advert_id, comment.id)), 201 return jsonify({"comment_id": comment.id}), 201 return jsonify({"comment": None}), 500
def post_comment(): user_id = int(request.form['user_id']) post_id = int(request.form['post_id']) user= models.User.query.get(user_id) post = models.Post.query.get(post_id) print request.form['comment'], request.form['post_id'], request.form['user_id'] comment = models.Comment(text= request.form['comment'], usr = user) post.comments.append(comment) db.session.add(comment) db.session.commit() return redirect(url_for('post',post_id= post_id))
def thread_reply(): if g.user is not None and g.user.is_authenticated(): thread_id = request.form['thread_id'] text = request.form['text'] new_comment = models.Comment() new_comment.thread_id = thread_id new_comment.text = text new_comment.username = g.user.username db.session.add(new_comment) thread = models.Thread.query.filter( models.Thread.id == thread_id).first() thread.last_updated = datetime.utcnow() db.session.add(thread) db.session.commit() return make_response("Success", 200) else: return make_response("You need to be logged in to post a comment.", 401)
def new_thread(): if g.user is not None and g.user.is_authenticated(): title = request.form['title'] text = request.form['text'] new_thread = models.Thread() new_thread.title = title new_thread.username = g.user.username db.session.add(new_thread) db.session.flush() db.session.refresh(new_thread) # So we can get the new thread's id first_comment = models.Comment() first_comment.text = text first_comment.username = g.user.username first_comment.thread_id = new_thread.id db.session.add(first_comment) db.session.commit() return make_response("Success", 200) else: return make_response("You need to be logged in to create a thread.", 401)
def comment(context): """ 코멘트를 작성하는 API 작성 후 맨 아래로 스크롤되어짐 """ permanent_id = request.json['content_pid'] comment_data = request.json['comment'] content = db.session.query(models.Content).\ filter(models.Content.permanent_id == permanent_id).\ first() comment = models.Comment(created_at=datetime.now(), uid=context.user.id, data=comment_data, cid=content.id) if 'parent_id' in request.json: comment.parent_id = request.json['parent_id'] db.session.add(comment) db.session.commit() return ujson.dumps(comment.to_json())
def parse_comments(self, bs, content, params): comments = session.query(models.Comment).\ filter(models.Comment.cid == content.id).\ all() if len(comments) > 0: print('alread updated') return comment_top = bs.find('div', id='comment_top') last_page = self.get_comment_last_page(comment_top) before_comment = None for i in range(last_page + 1): param = params params['cpage'] = i res = BeautifulSoup(requests.get(self.base_url, params).text, 'html.parser') comment_list = res.find('div', id='commentbox').find('div', attrs={'class': 'comment-list'}) # for comment_box in comment_list.findAll(lambda x: x.name == 'div' and 'class' in x.attrs and 'depth' not in x.attrs['class'] and 'comment-item' in x.attrs['class']): for comment_box in comment_list.findAll(lambda x: x.name == 'div' and 'class' in x.attrs and 'comment-item' in x.attrs['class']): box = comment_box.select('> div')[0].select('> div')[0] try: text = box.find('div', attrs={'class': 'xe_content'}).text except Exception as e: continue if not text: before_comment = None print('continued') break date = box.find('div').findAll('div')[-1].find('span').text delta = None if '일 전' in date: delta = timedelta(days=int(date[0])) if '시간 전' in date: delta = timedelta(hours=int(date[0])) if '분 전' in date: delta = timedelta(minutes=int(date[0])) if delta is not None: date = datetime.utcnow() + timedelta(hours=9) - delta else: date = datetime.strptime(date, '%Y.%m.%d') selected = box.select('div.comment-bar > div') if len(selected) == 0: selected = box.select('div.comment-bar-author > div') writer = selected[0].text.strip() # writer = box.select('a.ed.link-reset')[0].text writer = hashlib.shake_128(writer.encode()).hexdigest(length=4) user = session.query(models.User).\ filter(models.User.nickname == writer).\ first() if user is None: user = models.User(nickname=writer) session.add(user) session.flush() comment = models.Comment(data=text, cid=content.id, created_at=date, uid=user.id) if 'depth' in comment_box.attrs['class'] and before_comment: target = box.select('span.ed.label-primary')[0].text.strip()[1:] target = hashlib.shake_128(target.encode()).hexdigest(length=4) comment.data = f'@{target} {comment.data}' comment.parent_id = before_comment.id else: before_comment = comment exist = session.query(models.Comment).\ filter(models.Comment.uid == user.id).\ first() if not exist: session.add(comment) session.flush() print(text) session.commit() return content
def create_comment(post_id): error = None message = None success = False results = None if request.is_json: try: data = request.get_json() if not data: error = 'Json data is missen' return jsonify({ 'success': success, 'data': results, 'message': message, 'error': error }) except Exception as e: error = 'Json data is missen' return jsonify({ 'success': success, 'data': results, 'message': message, 'error': error }) try: clean_data = schema_post.comment_schema.load(data) except ValidationError as e: error = e.normalized_messages() return jsonify({ 'success': success, 'data': results, 'message': message, 'error': error }) try: user = models.User.query.filter_by( id=clean_data['commented_by']).first() if not user: error = 'Invalid user_id parsed' return jsonify({ 'success': success, 'data': results, 'message': message, 'error': error }) except Exception as e: error = 'Invalid user_id parsed' return jsonify({ 'success': success, 'data': results, 'message': message, 'error': error }) try: post = models.Post.query.filter_by(id=post_id).first() if not post: error = 'Post not found' return jsonify({ 'success': success, 'data': results, 'message': message, 'error': error }) new_comment = models.Comment( body=clean_data['body'], post_id=post_id, commented_by=clean_data['commented_by']) post.comments.append(new_comment) post.no_comments += 1 db.session.add(new_comment) db.session.commit() success = True message = "Post comment successfully!!!" results = schema_post.post_schema.dump(post) results['liked_by'] = [] results['comments'] = [] for liked in post.liked_post: results['liked_by'].append(liked.user.username) for com in post.comments: data = { 'body': com.body, 'user_id': com.commented_by, 'comment_date': com.comment_date } results['comments'].append(data) except Exception as e: error = 'Post not found' else: error = 'Only Json data is required' return jsonify({ 'success': success, 'data': results, 'message': message, 'error': error })
def setUp(self): #pylint: disable=invalid-name super(BaseUnitTest, self).setUp() self.accounts = self.get_accounts() for user in self.accounts.values(): user.put() self.courses = { "first": models.Course(institution="UC Awesome a", instructor=[self.accounts['admin'].key]), "second": models.Course(institution="UC Awesome b", instructor=[self.accounts['admin'].key]), } for course in self.courses.values(): course.put() self.enroll("student0", "first", STUDENT_ROLE) self.enroll("student1", "first", STUDENT_ROLE) self.enroll("student2", "second", STUDENT_ROLE) self.enroll("staff", "first", STAFF_ROLE) self.assignments = { "first": models.Assignment(name="first", points=3, creator=self.accounts["admin"].key, course=self.courses['first'].key, display_name="first display", templates="{}", max_group_size=3, due_date=datetime.datetime.now()), "second": models.Assignment(name="second", points=3, creator=self.accounts["admin"].key, course=self.courses['second'].key, display_name="second display", templates="{}", max_group_size=3, due_date=datetime.datetime.now()), "empty": models.Assignment(name="empty", points=3, creator=self.accounts["admin"].key, course=self.courses['first'].key, display_name="second display", templates="{}", max_group_size=4, due_date=datetime.datetime.now()), } for assign in self.assignments.values(): assign.put() self.backups = { "first": models.Backup( submitter=self.accounts["student0"].key, assignment=self.assignments["first"].key, ), "second": models.Backup( submitter=self.accounts["student1"].key, assignment=self.assignments["first"].key, ), "third": models.Backup( submitter=self.accounts["student2"].key, assignment=self.assignments["second"].key, ), } for backup in self.backups.values(): backup.put() self.submissions = { "first": models.Submission(backup=self.backups["first"].key), "second": models.Submission(backup=self.backups["second"].key), "third": models.Submission(backup=self.backups["third"].key), } for submission in self.submissions.values(): submission.put() self.groups = { 'group1': models.Group(member=[ self.accounts['student0'].key, self.accounts['student1'].key ], assignment=self.assignments['first'].key) } self.groups['group1'].put() group_backup = models.Backup( submitter=self.accounts['student0'].key, assignment=self.assignments['first'].key, ) group_backup.put() self.backups['group'] = group_backup group_submission = models.Submission(backup=group_backup.key) group_submission.put() self.submissions['group'] = group_submission self.queues = { "first": models.Queue( assignment=self.assignments["first"].key, assigned_staff=[self.accounts["staff"].key], ), } for queue in self.queues.values(): queue.put() self.diffs = {"first": models.Diff()} for diff in self.diffs.values(): diff.put() self.comments = { "first": models.Comment(author=self.accounts['student0'].key, diff=self.diffs["first"].key, message="First comment"), } for comment in self.comments.values(): comment.put() self.user = None
def vocab_analysis(comments, username): vocab = {} newWords = [] uniqueWords = [] commentWords = {} databaseWords = (db.session.execute( "SELECT SUM(totalUse) AS wordSum FROM words").first()).wordSum if databaseWords is None: databaseWords = 0 newUser = True if models.Username.query.get(username) is not None: newUser = False if debug: print "old user" else: if debug: print "new user" Username = models.Username(Username=username) db.session.add(Username) for comment in comments: commentID = comment.id.encode('ascii', 'ignore') if debug: print "commentID: " + commentID text = comment.body if debug: print "Text: " + repr(text) noPunctText = translate_non_alphanumerics(text) words = noPunctText.encode('ascii', 'ignore').lower().split() if models.Comment.query.get(commentID) is None: '''processes all the words from new comments, new words are added to the list''' if debug: print "New comment" for word in words: if len(word) < 20: if debug: print "added " + word + " to new comments words" commentWords[word] = commentWords.get(word, 0) + 1 db.session.add(models.Comment(comment=commentID)) else: if debug: print "Old comment" for word in words: '''puts all appropriate words into the vocab dict''' if len(word) < 20: '''Consider parsing for links etc''' if debug: print "added " + word + " to vocab list" vocab[word] = vocab.get(word, 0) + 1 for word in commentWords: if db.session.query( models.Word).filter(models.Word.word == word).count() == 0: if debug: print "new word: " + word + "!" newWordEntry = models.Word(word=word, totalUse=commentWords[word]) db.session.add(newWordEntry) newWords.append(word) else: if debug: print "old word: " + word vocab[word] = vocab.get(word, 0) + 1 db.session.query( models.Word).filter(models.Word.word == word).update( {models.Word.totalUse: models.Word.totalUse + 1}) for word in vocab: otherUses = (models.Word.query.get(word).totalUse) if otherUses == vocab[word]: uniqueWords.append(word) else: vocab[word] = float(vocab[word]) / float(otherUses) for word in uniqueWords: del vocab[word] db.session.commit() if debug: print "newWords: " + str(newWords) if debug: print vocab return dict( sorted(vocab.iteritems(), key=operator.itemgetter(1), reverse=True)[:20]), newWords, uniqueWords
def app(): dt_format = '%Y-%m-%dT%H:%M:%S' app = create_app(is_test=True) with app.app_context(): db.drop_all() db.create_all() user1 = models.User( id=1, username='******', logins=2, note='primary admin', created=datetime.strptime('2020-01-01T01:01:00', dt_format), ) user2 = models.User( id=2, username='******', is_active=False, logins=100, note='backup admin', created=datetime.strptime('2021-01-01T01:01:00', dt_format), ) user3 = models.User( id=3, username='******', logins=51, created=datetime.strptime('2021-01-01T06:01:00', dt_format), supervisor=user1, ) odduser = models.User(id=4, username='******', logins=500, created=datetime.strptime( '2021-03-05T07:30:00', dt_format)) admin_role = models.Role( id=1, name='admin', users=[ user1, user2, ], ) operator_role = models.Role( id=2, name='operator', users=[ user1, user3, ], ) comment1 = models.Comment( id=1, user=user1, body='some text', created=datetime.strptime('2021-03-05T07:30:00', dt_format), ) comment2 = models.Comment( id=2, user=user1, body='a response', created=datetime.strptime('2021-03-06T07:30:00', dt_format), ) comment3 = models.Comment( id=3, user=user1, body='additional text', created=datetime.strptime('2021-03-07T07:30:00', dt_format), ) comment4 = models.Comment( id=4, user=user2, body='keep going', created=datetime.strptime('2021-03-08T07:30:00', dt_format), ) comment5 = models.Comment( id=5, user=user2, body='ongoing discussion', created=datetime.strptime('2021-03-09T07:30:00', dt_format), ) comment6 = models.Comment( id=6, user=user3, body='talking to myself', created=datetime.strptime('2021-03-10T07:30:00', dt_format), ) db.session.add_all([ user1, user2, user3, odduser, admin_role, operator_role, comment1, comment2, comment3, comment4, comment5, comment6, ]) db.session.flush() db.session.commit() yield app