def process_comments(self, comments): cmnts_list = [] for c in comments: new_comment = Comments(**c) salon_urls_regex = re.compile("\S+\.salon24\.pl\S*") urls = ";".join(salon_urls_regex.findall(new_comment.content)).strip() new_comment.urls = urls if urls and urls is not "''" else None if not c['author_id']: continue author = self.AuthorService.get_author_by_name(c['author_id'][0]) if author is None: new_author = Authors() name = c['author_id'] new_author.name = ''.join(name).strip().replace('"', '').upper() new_author.bloglink = ''.join(c['author_bloglink']).replace('"', '') session = self.session try: session.add(new_author) session.commit() except: session.rollback() raise new_comment.author_id = new_author.id else: new_comment.author_id = author.id if new_comment.title.startswith('@'): self.match_parent_comment(cmnts_list, new_comment) cmnts_list.append(new_comment) self.session.add(new_comment) self.session.flush() self.session.refresh(new_comment) return cmnts_list
def post(self): logging.info(self.request.body) data = json.loads(self.request.body) # need blog to increment number of posts user_id = self.request.cookies.get("user_id") if user_id and len(user_id) > 0: l = user_id.split("|") if (user_id == Utilities.make_cookie_val(l[0])): logging.info(user_id + " " + l[0]) bp = BlogPosts.get_by_id(long(data['blogid'])) # new Comment to add to data store newcomment = Comments(blogid=str(data['blogid']), comment=data['comment'], commenter=data['username']) added, count, commentid = self.insertCommentAndInc( bp, newcomment) addedstr = datetime.strftime(added, '%b %d, %Y %I:%M %p') self.response.out.write( json.dumps(({ 'added': str(addedstr), 'comments': count, "commentid": commentid }))) else: self.response.headers.add_header('set-cookie', str('user_id=;Path=/')) self.redirect('/blog') else: self.response.headers.add_header('set-cookie', str('user_id=;Path=/')) self.redirect('/blog')
def post(self): logging.info(self.request.body) data = json.loads(self.request.body) user_id = self.request.cookies.get("user_id") if user_id and len(user_id) > 0: l = user_id.split("|") if (user_id == Utilities.make_cookie_val(l[0])): # Get the comment from data store c = Comments.get_by_id(long(data['commentid'])) blogid = c.blogid # and the blogpost itself bp = BlogPosts.get_by_id(long(blogid)) commentsnum = self.deleteCommentInDB(c, bp) self.response.out.write( json.dumps(({ 'blogid': str(blogid), 'commentsnum': commentsnum }))) else: self.response.headers.add_header('set-cookie', str('user_id=;Path=/')) self.redirect('/blog') else: self.response.headers.add_header('set-cookie', str('user_id=;Path=/')) self.redirect('/blog')
def get_all_comments(): # Open a connection to the database with sqlite3.connect("./rare.db") as conn: # Just use these. It's a Black Box. conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Write the SQL query to get the information you want db_cursor.execute(""" SELECT c.id, c.user_id, c.post_id, c.subject, c.content FROM comments c """) # Initialize an empty list to hold all animal representations users = [] # Convert rows of data into a Python list dataset = db_cursor.fetchall() # Iterate list of data returned from database for row in dataset: user = Comments(row['id'], row['user_id'], row['post_id'], row['subject'], row['content']) users.append(user.__dict__) # Use `json` package to properly serialize list as JSON return json.dumps(users)
def get_comment(self, comment_id): '''Retrieves comment id from url. If comment id matches comment in Comments database, returns comment, if not, returns None''' if comment_id: comment = Comments.get_by_id(int(comment_id)) if comment: return comment
def add_comment(): if request.method == 'POST': comment_content = request.form.get('comment') user_id = Userinfo.query.filter_by( userid=session.get('uid', None)).first().userid print(user_id) movie_id = request.form.get('id') # 评论模型 comment = Comments() comment.message = comment_content comment.user_id = user_id comment.movieid = movie_id db.session.add(comment) db.session.commit() return redirect(url_for('view01.single') + "?id=" + movie_id) return render_template(url_for('movie.movie'))
def get(self, post_id, comment_id): key = db.Key.from_path('Post', int(post_id), parent=blog_key()) post = db.get(key) comment = Comments.get_by_id(int(comment_id)) if self.user and comment: if comment.user.name == self.user.name: self.render("editcomment.html", comment=comment) else: return self.redirect("/blog/%s" % str(post.key().id()))
def post(self, post_id): key = db.Key.from_path('Poetry', int(post_id), parent=post_key()) post = db.get(key) if post: comment = self.request.get("comment") if comment: c = Comments(username = retrieve_username(self, 'user_id'), writer = retrieve_username_hash(self, 'user_id'), comment = comment, post_id=post.key().id()) c.put() self.redirect('/post/%s' % str(post.key().id())) else: key = db.Key.from_path('Poetry', int(post_id), parent=post_key()) post = db.get(key) self.redirect('/post/%s' % str(post.key().id())) else: self.render("errorexist.html")
def post(self, company_id, release_id): """ :return: json """ text = request.form["text"] name = request.form["name"] dt = datetime.now(pytz.timezone('Asia/Tokyo')).strftime('%Y-%m-%d %H:%M') c = Comments(company_id=company_id, release_id=release_id, name=name, text=text, posted_at=dt) db.session.add(c) db.session.commit() return jsonify({'response': 'ok'})
def get(self, post_id): key = db.Key.from_path('Post', int(post_id), parent=blog_key()) post = db.get(key) comments = Comments.all().filter("post = ", post) if not post: self.error(404) return if not self.user: return self.redirect('/blog') self.render("permalink.html", post=post, comments=comments)
def post(self): post_id = self.request.get("post_id") key = db.Key.from_path('Post', int(post_id), parent=blog_key()) post = db.get(key) if not post: self.error(404) return if self.user: comment = self.request.get("comment_content") user = User.by_name(self.user.name) if comment: newComment = Comments(user=user, post=post, comment=comment) newComment.put() return self.redirect("/blog/%s" % str(post.key().id())) else: comment_error = "Please enter text in comment box." self.render("permalink.html", post=post, comment_error=comment_error) else: return self.redirect("/blog")
def post(self, post_id, comment_id): key = db.Key.from_path('Post', int(post_id), parent=blog_key()) post = db.get(key) if self.request.get("save"): comment = Comments.get_by_id(int(comment_id)) if self.user and comment: if comment.user.name == self.user.name: comment.comment = self.request.get("comment") comment.put() return self.redirect("/blog/%s" % str(post.key().id())) else: save_error = \ "Only the author of the comment can make changes." self.render("editcomment.html", comment=comment, error=save_error) if self.request.get("cancel"): return self.redirect("/blog/%s" % str(post.key().id()))
def get_single_comment(id): with sqlite3.connect("./rare.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute( """ SELECT a.id, a.user_id, a.post_id, a.subject, a.content FROM comments a WHERE a.id = ? """, (id, )) data = db_cursor.fetchone() comment = Comments(data['id'], data['user_id'], data['post_id'], data['subject'], data['content']) return json.dumps(comment.__dict__)
def post(self): post_id = self.request.get("post_id") comment_id = self.request.get("comment_id") key = db.Key.from_path('Post', int(post_id), parent=blog_key()) post = db.get(key) if not post: self.error(404) return if self.user: comment = Comments.get_by_id(int(comment_id)) if comment is not None and comment.user.name == self.user.name: db.delete(comment) return self.redirect("/blog/%s" % str(post.key().id())) else: delete_error = "Failed to delete comment" self.render("permalink.html", post=post, delete_error=delete_error) else: return self.redirect("/blog")
def close_spider(self, spider): try: if len(self.data) > 0: latest_comment_id = self.__get_latest_comment_id( self.data[0]['news_id']) # Handle data (update, filter, clean) columns = ['comment_id', 'news_id', 'comment_time', 'comment'] df = pd.DataFrame(self.data, columns=columns) df = df.dropna().drop_duplicates().query( f'comment_id > {latest_comment_id}') df['sentiment'] = df['comment'].apply(self.__sentiment) data = [ Comments(comment=item['comment'], news_id=item['news_id'], comment_id=item['comment_id'], comment_time=item['comment_time'].to_pydatetime(), sentiment=item['sentiment']) for item in df.to_dict('records') ] self.dbUtils.insert(data) except Exception as ex: self.logger.error( "Exception occurred handling data when spider is closed.", ex)
def post(self): logging.info(self.request.body) data = json.loads(self.request.body) # Get the comment from data store user_id = self.request.cookies.get("user_id") if user_id and len(user_id) > 0: l = user_id.split("|") if (user_id == Utilities.make_cookie_val(l[0])): c = Comments.get_by_id(long(data['commentid'])) c.comment = data['updatedcomment'] c.put() self.response.out.write( json.dumps(({ "added": datetime.strftime(c.added, '%b %d, %Y %I:%M %p') }))) else: self.response.headers.add_header('set-cookie', str('user_id=;Path=/')) self.redirect('/blog') else: self.response.headers.add_header('set-cookie', str('user_id=;Path=/')) self.redirect('/blog')
def add_comment(self, post, user, comment_text): '''Adds comment''' comment = Comments(user=user, post=post, text=comment_text) comment.put() redirect = '/blog/pl/%s' % str(post.key().id()) return redirect
def get(self, company_id, release_id): comments = db.session.query(Comments).filter_by(release_id=release_id).filter_by(company_id=company_id) comments = [Comments.to_dict(c) for c in comments] return jsonify({"comments": format_comments(comments)})