def post(self, gid, pid): u = request.authorization # this gives dict uid = User.objects.get( username=u['username']) # this gives user object user_id = str(uid.id) # this gives the user id in string format body = request.get_json() user = User.objects.get(id=user_id) group = Group.objects.get(id=gid) post = Post.objects.get(id=pid) if post.approval: if user_id in group.role_dict: comment = Comment(**body, post_id=ObjectId(pid)) comment.date_created = datetime.now() comment.save() # update last active status for user temp_dict = group.last_active_dict temp_dict[user_id] = datetime.now() group.update(set__last_active_dict=temp_dict) content = "{name} has posted a comment today".format( name=user.username) queue.enqueue( printhello()) # this is just a check that q works queue.enqueue(send_mail, user.email, content) # queue.enqueue(send_email(user.email, content)) # send_email(user.email, content) return {'comment_id': str(comment.id)}, 200 else: return "You ain't a member of this group", 200
def run(): """Analyse reddit comments from a subreddit.""" print input_path = config.INPUT_PATH comment_row_list = csv_util.read_csv(input_path) comment_list = [] pos_list = [] neg_list = [] # calculate sentiment for each comment for comment_row in comment_row_list: comment = Comment(comment_row) comment = calculate_sentiment(comment) comment_list.append(comment) if comment.compound_score > 0.2: pos_list.append(comment.body) elif comment.compound_score < -0.2: neg_list.append(comment.body) # write out CSV with sentiment score for each comment output_path = config.OUTPUT_PATH csv_util.write_row(output_path, comment=None, header=HEADER) for comment in comment_list: csv_util.write_row(output_path, comment=comment) # distribution analysis (pos_res, all_words_pos, neg_res, all_words_neg) = calculate_word_distributions(pos_list, neg_list)
def parser_song(song_id, art): tree = get_tree(SONG_URL.format(song_id)) song = session.query(Song).filter_by(id=song_id).all() r = post(COMMENTS_URL.format(song_id)) if r.status_code != 200: print('API error: Song: {}'.format(song_id)) return data = r.json() if not song: for404 = tree.xpath('//div[@class="n-for404"]') if for404: return try: song_name = tree.xpath('//em[@class="f-ff2"]/text()')[0].strip() except IndexError: try: song_name = tree.xpath( '//meta[@name="keywords"]/@content')[0].strip() except IndexError: print('Fetch limit!') time.sleep(10) return parser_song(song_id, art) song = Song(id=song_id, name=str(song_name), art_id=art.id, comment_count=int(data['total'])) session.add(song) session.commit() else: song = song[0] for comment_ in data['hotComments']: comment_id = comment_['commentId'] content = comment_['content'] like_count = comment_['likedCount'] user_ = comment_['user'] if not user_: continue user = session.query(User).filter_by(id=user_['userId']).all() if not user: user = User(id=user_['userId'], name=user_['nickname'], picture=user_['avatarUrl']) try: session.add(user) session.commit() except Exception as e: continue else: user = user[0] comment = session.query(Comment).filter_by(id=comment_id).all() if not comment: comment = Comment(id=comment_id, use_id=user.id, song_id=song.id, content=content, like_count=like_count) session.add(comment) session.commit() return song
def post(self, slug): context = self.get_context(slug) form = context.get('form') if form.validate(): comment = Comment() form.populate_obj(comment) 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 post(self): # If not a logged in user redirect to login if not self.user: self.redirect('/login') else: comment = self.request.get('comment') post_id = int(self.request.get('post_id')) post = Post.get_by_id(post_id, parent=blog_key()) author = self.user if not comment: return # do nothing if empty comment else: c = Comment(content=comment, author=author.key, post=post.key) c.put() comment = Comment.render_single_comment(c) # return JSON to Ajax self.write(json.dumps(({'comment': comment})))
def insertComment(self, jokeid, userid, content): if jokeid == '': self.status = 201 self.message = 'jokeid不能为空' jsonStr = self.getJsonResult() self.write(jsonStr) elif userid == '': self.status = 201 self.message = 'userid不能为空' jsonStr = self.getJsonResult() self.write(jsonStr) elif content == '': self.status = 201 self.message = 'content不能为空' jsonStr = self.getJsonResult() self.write(jsonStr) elif not self.checkUser(userid): self.status = 201 self.message = '该userid不存在' jsonStr = self.getJsonResult() self.write(jsonStr) elif not self.checkJoke(jokeid): self.status = 201 self.message = '该jokeid不存在' jsonStr = self.getJsonResult() self.write(jsonStr) else: commentid = uuid.uuid1().hex newcomment = Comment() newcomment.commentid = commentid newcomment.userid = userid newcomment.jokeid = jokeid newcomment.content = content self.db.add(newcomment) self.db.commit() self.db.close() self.status = 200 jsonStr = self.getJsonResult() self.write(jsonStr)
def add_post_comment(): groups = Group.objects for group in groups: temp_dict = group.last_active_dict for user_id in group.role_dict.keys(): temp_dict[user_id] = datetime.now() name = ''.join([ random.choice(string.ascii_letters + string.digits) for k in range(9) ]) content1 = "post is {name}".format(name=name) post = Post(user_id=ObjectId(user_id), group_id=ObjectId(group.id), content=content1).save() content2 = "comment is {name}".format(name=name) Comment(user_id=ObjectId(user_id), post_id=post.id, content=content2).save() group.update(set__last_active_dict=temp_dict)
def post(self, topic_id): user = users.get_current_user() time = datetime.datetime.now() csrf_token = self.request.get("csrf_token") mem_token = memcache.get(key=csrf_token) if mem_token: return self.write("Hacker at the doors") comment = self.request.get("comment") topic = Topic.get_by_id(int(topic_id)) new_comment = Comment(content=comment, topic_id=topic.key.id(), author_email=user.email(), topic_title=topic.title, created=time) new_comment.put() return self.redirect_to("topic-details", topic_id=topic.key.id())
def from_sql(engine: Engine, post_id: int, comment_id: int) -> Optional[Comment]: """Generate a Comment object from a SQL table :param engine: SQLAlchemy engine object :param post_id: Entry identifier in comments table :param comment_id: Comment identifier in comments table :return: populated Comment object """ comments = get_comments(engine, post_id, comment_id) comment = None # populate comment if 'id' exists if len(comments) > 0: c = comments[0] comment = Comment(c['post_id'], c['name'], c['content'], c['email']) return comment
def store_comment(post_id: int, request: MultiDict, engine: Engine) -> str: """Extract comment information from request object; validate and store :param post_id: post 'id' to which the comment refers :param request: Flask request object :param engine: SQLAlchemy engine object """ # fill in comment form form = CommentForm(request.form) # validate response, comment and store comment in database if request.method == 'POST': if form.validate(): comment = Comment(post_id, request.form.get('name'), request.form.get('content'), request.form.get('email'), request.form.get('occupation')) if comment.to_sql(engine): return 'success' # indicate source of error on failed validation elif len(request.form.get('content')) > 1000: return 'Comment too long. A maximum of 1000 characters is allowed.' elif len(request.form.get('content')) < 5: return 'Comment too short. At least 5 characters are required.' elif len(request.form.get('name')) > 20: return 'Name too long. A maximum of 20 characters is allowed.' elif len(request.form.get('email')) > 50: return 'Email address too long. A maximum of 50 characters is allowed.' elif len(request.form.get('email')) < 5: return 'Email address too short. At least 5 characters are required.' elif len(request.form.get('occupation')) > 100: return 'Occupation name too long. A maximum of 100 characters is allowed.' return ''