示例#1
0
文件: admin.py 项目: yobin/saepy-log
    def post(self, id=""):
        act = self.get_argument("act", "")
        if act == "findid":
            eid = self.get_argument("id", "")
            self.redirect("%s/admin/comment/%s" % (BASE_URL, eid))
            return

        tf = {"true": 1, "false": 0}
        post_dic = {
            "author": self.get_argument("author"),
            "email": self.get_argument("email", ""),
            "content": safe_encode(self.get_argument("content").replace("\r", "\n")),
            "url": self.get_argument("url", ""),
            "visible": self.get_argument("visible", "false"),
            "id": id,
        }
        post_dic["visible"] = tf[post_dic["visible"].lower()]

        if MYSQL_TO_KVDB_SUPPORT:
            obj = Comment.get_comment_by_id(id)
            for k, v in obj.items():
                if k not in post_dic:
                    post_dic[k] = v

        Comment.update_comment_edit(post_dic)
        clear_cache_by_pathlist(["post:%s" % id])
        self.redirect("%s/admin/comment/%s" % (BASE_URL, id))
        return
示例#2
0
 def get(self):
     recentComments = Comment.all().order('-commentTime').fetch(10)
     recentBlogs = Blog.all().order('-createTimeStamp').fetch(5)
     links = Link.all()
     template_values = {
         'recentComments': recentComments,
         'recentBlogs': recentBlogs,
         'links': links
     }
     blogid = self.param('p')
     if (blogid):
         blogid = int(blogid)
         blogs = Blog.all().filter('blog_id =', blogid).fetch(1)
         blog = blogs[0]
         comments = Comment.all().filter("ownerBlog =",
                                         blog).order('commentTime')
         template_values.update({'blog': blog, 'comments': comments})
         self.generateBasePage('singleblog.html', template_values)
     else:
         pageIndex = self.param('page')
         if (pageIndex):
             pageIndex = int(pageIndex)
         else:
             pageIndex = 1
         blogs = Blog.all().order('-createTimeStamp')
         pager = PageManager(query=blogs,
                             items_per_page=blogSystem.posts_per_page)
         blogs, links = pager.fetch(pageIndex)
         template_values.update({'blogs': blogs, 'pager': links})
         self.generateBasePage('main.html', template_values)
     return
示例#3
0
文件: admin.py 项目: yobin/saepy-log
 def post(self, secret=""):
     pcomm = (self.get_argument("pcomm", ""),)
     if pcomm and secret:
         if secret == getAttr("MOVE_SECRET"):
             Comment.set_pcomm(encode_special_txt(pcomm[0]))
             return self.write("1")
     return self.write("Fail")
示例#4
0
文件: admin.py 项目: yobin/saepy-log
 def post(self, secret=""):
     comments = (self.get_argument("comments", ""),)
     if comments and secret:
         if secret == getAttr("MOVE_SECRET"):
             Comment.set_comms(comments[0])
             return self.write("1")
     return self.write("Fail")
示例#5
0
    def extract_comments(self, sid, text):
        """
        Extracts comments from a XML string. The parsing is done
        using feedparser library.

            :param sid: the id of the new.
            :param text: the RSS xml.

    """
        parsed = feedparser.parse(text)
        try:
            published = parsed.feed.published
        except AttributeError:
            published = parsed.feed.updated

        comments = []
        for comment in parsed.entries:
            meneame_comment = Comment(sid)
            meneame_comment.order = comment['meneame_order']
            meneame_comment.karma = comment['meneame_karma']
            meneame_comment.user = comment['meneame_user']
            meneame_comment.votes = comment['meneame_votes']
            meneame_comment.id = comment['meneame_comment_id']
            try:
                meneame_comment.published = comment.published
            except AttributeError:
                meneame_comment.published = comment.updated
            meneame_comment.summary = comment.summary
            comments.append(meneame_comment)

        return comments, published
示例#6
0
文件: admin.py 项目: yobin/saepy-log
    def post(self, id=''):
        act = self.get_argument("act", '')
        if act == 'findid':
            eid = self.get_argument("id", '')
            self.redirect('%s/admin/comment/%s' % (BASE_URL, eid))
            return

        tf = {'true': 1, 'false': 0}
        post_dic = {
            'author':
            self.get_argument("author"),
            'email':
            self.get_argument("email", ''),
            'content':
            safe_encode(self.get_argument("content").replace('\r', '\n')),
            'url':
            self.get_argument("url", ''),
            'visible':
            self.get_argument("visible", 'false'),
            'id':
            id
        }
        post_dic['visible'] = tf[post_dic['visible'].lower()]

        if MYSQL_TO_KVDB_SUPPORT:
            obj = Comment.get_comment_by_id(id)
            for k, v in obj.items():
                if k not in post_dic:
                    post_dic[k] = v

        Comment.update_comment_edit(post_dic)
        clear_cache_by_pathlist(['post:%s' % id])
        self.redirect('%s/admin/comment/%s' % (BASE_URL, id))
        return
示例#7
0
文件: admin.py 项目: yobin/saepy-log
 def post(self, secret="", id=""):
     comment = (self.get_argument("comment", ""),)
     if id and comment and secret:
         if secret == getAttr("MOVE_SECRET"):
             Comment.set_comm(id, encode_special_txt(comment[0]))
             return self.write("1")
     return self.write("Fail")
示例#8
0
文件: admin.py 项目: yobin/saepy-log
 def post(self, secret='', id=''):
     comment = self.get_argument("comment", ''),
     if id and comment and secret:
         if secret == getAttr('MOVE_SECRET'):
             Comment.set_comm(id, encode_special_txt(comment[0]))
             return self.write('1')
     return self.write('Fail')
    def _get_comments(self, foreign_id=None):
        comments = []
        comments_counter = 0
        comments_page_counter = 0
        while True:
            comments_page_counter += 1
            response = requests.get(self._comments_url.format(foreign_id, comments_page_counter))
            if response.status_code == 404:
                return comments
            json_top_comments_list = json.loads(response.content)['data']
            for json_top_comment in json_top_comments_list:
                comments_counter += 1
                sub_comments_counter = 0
                top_comment = json_top_comment['Comment']
                top_comment_original_id = top_comment['id']

                top_text = top_comment['text']
                top_comment_id = str(comments_counter)
                parent_id = top_comment['parent_id']
                comments.append(Comment(top_comment_id, parent_id, top_text))
                if 'SubComment' not in json_top_comment:
                    continue
                else:
                    json_sub_comments = json_top_comment['SubComment']
                sub_comment_ids = []
                for json_sub_comment in json_sub_comments:
                    sub_comment_ids.append(json_sub_comment['id'])
                    sub_comments_counter += 1
                    sub_text = json_sub_comment['text']
                    sub_id = "%s-%d" % (top_comment_id, sub_comments_counter)
                    sub_parent_id = top_comment_id
                    comments.append(Comment(sub_id, sub_parent_id, sub_text))
                comments.extend(
                    self._get_sub_comments(foreign_id, top_comment_original_id, sub_comment_ids, top_comment_id))
示例#10
0
文件: blog.py 项目: yibin001/pyblog
    def post(self, postId):

        post = Post.get_post_by_id(postId)
        if not post or post.status != 0 or post.commentstatus == 1:
            self.write('抱歉,评论功能已关闭。')
        else:
            username = self.get_argument('username', '')
            email = self.get_argument('email', '')
            content = self.get_argument('comment', '')
            parentid = int(self.get_argument('parentid', 0))
            if self.islogin:
                curr_user_info = self.get_current_user_info
                username = curr_user_info.username
                email = curr_user_info.email

            if username == '' or content == '' or not isemail(email):
                self.flash(u'错误:称呼、电子邮件与内容是必填项')
                self.redirect(post.url + '#comments')
                return
            username = username[:20]
            content = content[:512]
            if not self.islogin:
                is_spam = spam_check(content, self.request.remote_ip)
            else:
                is_spam = 0
            if is_spam:
                self.flash(u'sorry,your comment is not posted')
                self.redirect(post.url+'#comments')
            location = get_location_byip(self.request.remote_ip)
            Comment.post_comment(postid=postId, username=username, email=email, content=content, parentid=parentid,
                                 ip=self.request.remote_ip, isspam=is_spam, location=location)
            if is_spam:
                self.flash(u'您的评论可能会被认定为Spam')
            self.set_comment_user(username, email)
            self.redirect(post.url + '#comments')
示例#11
0
def comment():
    """
        comment handler, add a new comment to DB
        give a new notification to post poster
        and send a validate email
    """
    zid = session['zid']
    user = User.findByKey(zid)
    if not user:
        return redirect(url_for('login'))
    pid = request.form.get('pid')
    poster_zid = request.form.get('poster_zid')
    m_user = User.findByKey(poster_zid)
    message = request.form.get('message')
    new_comment = Comment(pid=pid, zid=zid, message=message)
    new_comment.save()
    flash('Success: you have post a new comment.')
    notification = Notifications(from_zid=user.zid, to_zid=poster_zid, noti_type='reply', from_name=user.full_name, from_img=user.image, pid=pid)
    # notification.pid = pid
    notification.save()
    mail = MailUtils('*****@*****.**', 'MateLook Team', m_user.full_name)
    mail.notificaion()
    post = Post.findByKey(pid)
    poster = User.findByKey(post.zid)
    page = int(request.args.get('page', '1'))
    total = len(post.getComments())
    pag = Pagination(page, total)
    return redirect(url_for('postlook', pid=pid, page=page))
示例#12
0
 def post(self, post_id):
     blogpost = self.get_blogpost(post_id)
     user = self.get_user_object()
     if user:
         if blogpost:
             # To detect which form is sent, the like or the comment
             if "likeBtn" in self.request.POST:
                 if blogpost.author.key().id() == user.key().id():
                     error = "You cannot like your own post!"
                     comments = self.get_comments(blogpost)
                     self.render_content(blogpost=blogpost,
                                         user=user,
                                         comments=comments,
                                         error_like=error)
                 else:
                     like = LikePost(user=user, blogpost=blogpost)
                     like.put()
                     self.redirect('/%s' % post_id)
             else:
                 content = self.request.get("comment")
                 if content:
                     comment = Comment(user=user,
                                       blogpost=blogpost,
                                       content=content)
                     comment.put()
                     self.redirect('/%s' % post_id)
                 else:
                     error = "Please write something before posting!"
                     comments = self.get_comments(blogpost)
                     self.render_content(blogpost=blogpost,
                                         user=user,
                                         comments=comments,
                                         error_comment=error)
     else:
         self.redirect("/login")
示例#13
0
文件: admin.py 项目: yobin/saepy-log
 def post(self, secret=''):
     pcomm = self.get_argument("pcomm", ''),
     if pcomm and secret:
         if secret == getAttr('MOVE_SECRET'):
             Comment.set_pcomm(encode_special_txt(pcomm[0]))
             return self.write('1')
     return self.write('Fail')
示例#14
0
文件: admin.py 项目: yobin/saepy-log
 def post(self, secret=''):
     comments = self.get_argument("comments", ''),
     if comments and secret:
         if secret == getAttr('MOVE_SECRET'):
             Comment.set_comms(comments[0])
             return self.write('1')
     return self.write('Fail')
示例#15
0
def add_comment():
    
    comment = request.form.get("comment")
    question_id = request.form.get("question_id")

    question_info = Question.query.get(question_id)
    question_author = User.query.filter(User.user_id == question_info.user_id).first()

    date_string = datetime.today().strftime('%Y-%m-%d')
    commented_item = Comment(user_id = session["user_id"], comment_timestamp = date_string, question_id = question_id, comment = comment) 
    db.session.add(commented_item)
    db.session.commit()

    comment_author = User.query.filter(User.user_id == commented_item.user_id).first()
    comment_auth_image = comment_author.images[0]
    

    result = {'comment_id': commented_item.comment_id, 
              'vote': commented_item.vote_count(),
              'comment_author': comment_author.username,
              'comment_auth_image':comment_auth_image.image, 
              'comment_timestamp': commented_item.comment_timestamp,
              'user_id': comment_author.user_id}

    notify_author_comment(commented_item.comment, question_author.email, question_author.username, question_info.question, question_info.title_question, comment_author.username)


    return jsonify(result)
示例#16
0
def register_MMP_RecordParsers():  #bruce 071019
    """
    Register MMP_RecordParser subclasses for the model objects that can be read
    from mmp files, and whose parsers are not hardcoded into files_mmp.py.
    """
    import model.Comment as Comment
    Comment.register_MMP_RecordParser_for_Comment()

    import analysis.GAMESS.jig_Gamess as jig_Gamess
    jig_Gamess.register_MMP_RecordParser_for_Gamess()

    import model.PovrayScene as PovrayScene
    PovrayScene.register_MMP_RecordParser_for_PovrayScene()

    try:
        import dna.model.DnaMarker as DnaMarker
        DnaMarker.register_MMP_RecordParser_for_DnaMarkers()
    except:
        print_compact_traceback(
            "bug: ignoring exception in register_MMP_RecordParser_for_DnaMarkers: "
        )
        pass

    # TODO: add more of these.

    return
示例#17
0
def commentscreate():
    data = request.forms.getunicode('data')
    data = json.loads(data)
    Comment.create(data)
    openid = data['openid']
    user = User.find_by_id(openid)
    data['type'] = 'comment'
    Message.create(user, '', data)
示例#18
0
def api_comments(*, page='1'):
    page_index = get_page_index(page)
    num = yield from Comment.findNumber('count(id)')
    p = Page(num, page_index)
    if num == 0:
        return dict(page=p, comments=())
    comments = yield from Comment.findAll(orderBy='created_at desc', limit=(p.offset, p.limit))
    return dict(page=p, comments=comments)
def api_comments(*,page='1'):
    page_index  = get_page_index(page)
    num = yield from Comment.findNumber('count(id)')
    p = Page(num,page_index)
    if num == 0 :
        return dict(page=p,comments = ())
    comments = yield from Comment.findAll(orderBy='created_at desc',limit=(p.offset,p.limit))
    return dict(page=p,comments=comments)
示例#20
0
    def _get_facebook_comments(self, **kwargs):
        """
        Scrape all Facebook comments using Facebook comments URL.
        :param facebook_id: Facebook ID
        :param domain: domain
        :param url: url
        :return:
        """
        comments = []
        fb_comments_response = requests.get(
            self._comments_url.format(kwargs['facebook_id'], kwargs['domain'],
                                      kwargs['url'])).content.decode('utf-8')
        fb_comments_json = json.loads(
            re.search(r'handleServerJS\(({\"instances\".*)\);\}',
                      fb_comments_response).group(1))
        target_fb_id = fb_comments_json['require'][2][3][0]['props']['meta'][
            'targetFBID']

        fb_pager_url = "https://www.facebook.com/plugins/comments/async/{}/pager/time".format(
            target_fb_id)
        top_comments_response = requests.post(fb_pager_url,
                                              data={
                                                  '__a': 1,
                                                  'limit': 5000
                                              }).content.decode('utf-8')
        top_comments_json = json.loads(
            re.search('({.*})', top_comments_response).group())

        top_comments_list = top_comments_json['payload']['commentIDs']
        top_comments_counter = 0
        for top_comment_id in top_comments_list:
            top_comments_counter += 1
            comments.append(
                Comment(comment_id=str(top_comments_counter),
                        parent_comment_id=',',
                        text=top_comments_json['payload']['idMap']
                        [top_comment_id]['body']['text']))

            sub_comments_url = 'https://www.facebook.com/plugins/comments/async/comment/{}/pager'.format(
                top_comment_id)
            sub_comments_response = requests.post(sub_comments_url,
                                                  data={
                                                      '__a': '1'
                                                  }).content.decode('utf-8')
            sub_comments_json = json.loads(
                re.search('({.*})', sub_comments_response).group())

            sub_comments_counter = 0
            for sub_comment_id in sub_comments_json['payload']['commentIDs']:
                sub_comments_counter += 1
                sub_comment_text = sub_comments_json['payload']['idMap'][
                    sub_comment_id]['body']['text']
                comments.append(
                    Comment(comment_id="%d-%d" %
                            (top_comments_counter, sub_comments_counter),
                            parent_comment_id=str(top_comments_counter),
                            text=sub_comment_text))
        return comments
示例#21
0
def example_data():
    """Create some sample data for tests file to use."""

    # Create some fake users
    u1 = User(user_id=1,
              email="*****@*****.**",
              name="Jessi DiTocco",
              password="******")
    u2 = User(user_id=2,
              email="*****@*****.**",
              name="Liz Lee",
              password="******")

    # Create some fake events
    e1 = Event(event_id="43104373341",
               name="Aristophanes @ Cafe du Nord",
               start_time="Friday, February 16 at 9:30PM+",
               end_time="Saturday, February 17 at 2:00AM",
               address="2174 Market Street, San Francisco, CA 94114",
               latitude=37.7649659,
               longitude=-122.431,
               venue_name="Slate")
    e2 = Event(event_id="41465350981",
               name="Funk",
               start_time="Friday, February 15 at 9:30PM+",
               end_time="Saturday, February 18 at 2:00AM",
               address="4123 Market Street, San Francisco, CA 94114",
               latitude=39.7649659,
               longitude=-122.431,
               venue_name="The Jam")

    # Create some bookmark types
    bt1 = BookmarkType(bookmark_type_id=1, bookmark_type="going")
    bt2 = BookmarkType(bookmark_type_id=2, bookmark_type="interested")

    # Create some fake bookmarks
    b1 = Bookmark(bookmark_id=1,
                  user_id=1,
                  event_id="43104373341",
                  bookmark_type_id=2)
    b2 = Bookmark(bookmark_id=2,
                  user_id=2,
                  event_id="43104373341",
                  bookmark_type_id=1)

    # Create some fake Comments
    c1 = Comment(comment_id=1,
                 user_id=1,
                 event_id="43104373341",
                 comment="HI!")
    c2 = Comment(comment_id=2,
                 user_id=2,
                 event_id="43104373341",
                 comment="HI!")

    db.session.add_all([u1, u2, e1, e2, bt1, bt2, b1, b2, c1, c2])
    db.session.commit()
示例#22
0
文件: admin.py 项目: yibin001/pyblog
 def get(self):
     page = int(self.get_argument('page', 1))
     if self.get_argument('act', '') == 'delete':
         Comment.delete_comment_by_id(int(self.get_argument('id', 0)))
     pagesize = 20
     rtn = Comment.get_comments(pagesize=pagesize)
     self.datamap['comments'] = rtn[1]
     self.datamap['count'] = rtn[0]
     self.datamap['pagecount'] = int(math.ceil(float(rtn[0]) / pagesize))
     self.write(render_admin.comment(self.datamap))
示例#23
0
def create_a_comment(body):
    try:
        with create_session() as s:
            o = Comment()
            o.body = body
            s.add(o)
        return ''
    except Exception as e:
        logging.warning(e)
        return 'Write a comments failed'
示例#24
0
def get_comment(msg_id, page):
    """return certain page of comments of message msg_id"""
    res = flatten_double(Comment.find_original_comment(msg_id, page * 10, 10))
    # the number of pages of comments, 10 comments per page
    count = (Comment.count_original_comment(msg_id) - 1) // 10 + 1
    for c in res:
        c['reply_list'] = flatten_double(
            Comment.find_reply_by_comment(c['comment_id']))

    return jsonify((count, res))
示例#25
0
    def post(self, type, identifier):
        """
        ---
        description: Create new comment
        security:
            - bearerAuth: []
        tags:
            - comment
        requestBody:
            description: Comment content
            content:
              application/json:
                schema: CommentSchemaBase
        parameters:
            - in: path
              name: type
              schema:
                type: string
                enum: [file, config, blob, object]
              description: Type of target object
            - in: path
              name: identifier
              schema:
                type: string
              description: Commented object's id
        responses:
            200:
                description: Comment object after addition
                content:
                  application/json:
                    schema: CommentSchema
        """
        schema = CommentSchemaBase()
        obj = schema.loads(request.get_data(as_text=True))

        if obj.errors:
            return {"errors": obj.errors}, 400

        db_object = authenticated_access(Object, identifier)

        db_comment = Comment()
        db_comment.comment = obj.data["comment"]
        db_comment.user_id = g.auth_user.id
        db_comment.object_id = db_object.id

        db.session.add(db_comment)
        db.session.commit()

        logger.info('comment added', extra={'comment': db_comment.object_id})

        db.session.refresh(db_comment)
        schema = CommentSchema()
        return schema.dump(db_comment)
示例#26
0
def commentvote():
    postuserid = request.forms.getunicode('postuserid')
    openid = request.forms.getunicode('openid')
    user = User.find_by_id(openid)
    cid = request.forms.getunicode('cid')
    comment = Comment(cid)
    flag = comment.incrThumbs(openid)
    if flag:
        data = {'type': 'tcomment', 'index': cid}
        Message.create(user, postuserid, data)
    else:
        comment.decrThumbs(openid)
示例#27
0
def init_comment(game, content, speaker_name):
    player_i = cu.get_ints(content.split('号发言')[0])[0]
    content_trimed = content.split('号发言')[1]
    player = game.init_player(speaker_name, player_i)
    game.set_current_speaker(player)
    comment = Comment(player, game.day, content_trimed)
    if game.day <= 1:
        if not game.shreff:
            player.is_shreff_cadidate = True
            comment.is_shreff_run = True
    game.add_comment(comment)
    return build_message(vocab.start_comment.gen())
def api_create_comment(id,request,*,content):
    user = request.__user__
    if user is None:
        raise APIPermissionError('please signin first...')
    if not content or not content.strip():
        raise APIValueError('content')
    blog = yield from Blog.find(id)
    if blog is None:
        raise APIResourceNotFoundError('Blog')
    comment  = Comment(blog_id = blog.id ,user_id = user.id,user_name=user.name,user_image = user.image,content = content.strip())
    yield from comment.save()
    return comment
示例#29
0
def api_create_comment(id, request, *, content):
    user = request.__user__
    if user is None:
        raise APIPermissionError('Please signin first.')
    if not content or not content.strip():
        raise APIValueError('content')
    blog = yield from Blog.find(id)
    if blog is None:
        raise APIResourceNotFoundError('Blog')
    comment = Comment(blog_id=blog.id, user_id=user.id, user_name=user.name, user_image=user.image, content=content.strip())
    yield from comment.save()
    return comment
示例#30
0
def api_craete_commnet(id, request, content):
	if not id or not id.strip():
		raise APIValueError('id','empty id')
	if not content or not content.strip():
		raise APIValueError('content','empty content')

	commnet = Comment(blog_id=id, user_id=request.__user__.id, user_name=request.__user__.name, user_image=request.__user__.image, content=content)
	yield from commnet.save()

	r = aiohttp.web.Response()
	r.content_type = 'application/json'
	r.body = json.dumps(commnet,ensure_ascii=False).encode('utf-8')
	return r
示例#31
0
文件: dota.py 项目: OldDonke/Guided
def add_comment():
    """添加评论操作"""
    context = request.form.get('comment')
    comment = Comment(context=context)
    community_id = request.form.get('community_id')
    community = Community.query.filter(Community.id == community_id).first()
    comment.community = community
    username = session.get('user_name')
    author = User.query.filter(User.username == username).first()
    comment.author = author
    db.session.add(comment)
    db.session.commit()
    return redirect(url_for('question_detail', community_id=community_id))
示例#32
0
    def post(self, 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
        """
            While commenting, a comment datastore object is created and stored,
            with respect to each user and post.
        """
        c = ""
        if (self.user):
            # On clicking like, post-like value increases.
            if (self.request.get('like')
                    and self.request.get('like') == "update"):
                likes = db.GqlQuery("select * from Like where post_id= " +
                                    post_id + " and user_id= " +
                                    str(self.user.key().id()))

                if self.user.key().id() == post.user_id:
                    self.redirect("/blog/" + post_id +
                                  "?error= You cannot like your own post")
                    return
                elif likes.count() == 0:
                    l = Like(parent=blog_key(),
                             user_id=self.user.key().id(),
                             post_id=int(post_id))
                    l.put()

            # On commenting, it creates new comment tuple
            if (self.request.get('comment')):
                c = Comment(parent=blog_key(),
                            user_id=self.user.key().id(),
                            post_id=int(post_id),
                            comment=self.request.get('comment'))
                c.put()
        else:
            self.redirect("/blog/" + post_id + "?error= Need to Login Please.")
            return

        comments = db.GqlQuery("select * from Comment where post_id = " +
                               post_id + "order by created desc")

        likes = db.GqlQuery("select * from Like where post_id=" + post_id)

        self.render("permalink.html",
                    post=post,
                    comments=comments,
                    no_of_likes=likes.count(),
                    new=c)
示例#33
0
    def post(self):
        self.options()
        username = self.request.get('username')
        post_id = self.request.get('post_id')
        content = self.request.get('content')

        if username != None and post_id != None and content != None:
            comment_post = Comment(username=username,
                                   post_id=post_id,
                                   content=content)
            comment_post.put()
            self.response.out.write("Complete")
        else:
            self.response.out.write("Fail")
示例#34
0
    def post(self):
        if self.user.state == UserState.PROPOSED:
            proposal_key_str = self.request.get('proposal_key_str')
            proposal_key = ndb.Key(urlsafe=proposal_key_str)
            content = self.request.get('content')
            Comment.create_comment(proposal_key, self.user.username, content)

            comments = proposal_key.get().get_comments()
            comments_rendered = ''
            for comment in comments:
                comments_rendered += self.render_str('comment.html', comment=comment)

            self.write(comments_rendered)
        else:
            self.abort(400)
示例#35
0
def add_comment():
    content = request.form.get('comment-content')
    question_id = request.form.get('question_id')

    comment = Comment(content=content)
    user_id = session.get('user_id')
    user = User.query.filter(User.id == user_id).first()
    comment.author = user
    question = Question.query.filter(Question.id == question_id).first()
    comment.question = question

    db.session.add(comment)
    db.session.commit()

    return redirect(url_for('detail', question_id=question_id))
示例#36
0
 def post(self):
     text = self.request.get('comment')
     if len(text) > 0:
         date_time = self.request.get('date_time')
         post_key = Post.query(Post.date_time == date_time).fetch()[0].key
         name = self.request.get('author_name')
         author_key = Key('User', self.session.get('user_key_id'))
         comment = Comment(author_key = author_key,
                           post_key = post_key,
                           text = text,
                           author_name = name,
                           date_time = datetime.now().strftime('%m/%d/%y/%H/%M/%S/%f'))
         comment.put()
         time.sleep(0.1)
     self.redirect('/index')
示例#37
0
    def post(self):
        # this method is reserved for AJAX call to this object
        # json response
        result = {'message': ""}
        comment_id = self.request.POST.get("comment_id", "")
        operation = self.request.POST.get("operation", "")
        logging.info("CommentManager, post data: comment_id = %s, operation = %s" % (comment_id, operation))
        if comment_id:
            comment = Comment.get_by_id(long(comment_id))
            if comment:
                if operation == "delete":
                    # update entry.commentcount
                    comment.entry.commentcount -= 1
                    comment.entry.put()
                    # delete this comment
                    comment.delete()
                    result['message'] = "comment '%s' has been deleted" % (comment_id)
                else:
                    result['message'] = "unknown operation %s" % (operation)
            else:
                result['message'] = "unknown comment id %s" % (comment_id)
        else:
            result['message'] = "empty comment id"

        json_response = json.encode(result)
        logging.info("json response: %s" % (json_response))

        self.response.content_type = "application/json"
        return self.response.out.write(json_response)
示例#38
0
    def get(self, page_slug=""):
        if page_slug:
            t_values = {}

            posts = Entry.all().filter("is_external_page =", True).filter("entrytype =", 'page').filter("slug =", page_slug)
            if posts.count() == 1:
                logging.warning("find one page with slug=%s" % (page_slug))
                posts = posts.fetch(limit=1)
                post = posts[0]
                t_values['post'] = post
                # dump(post)

                # find all comments
                comments = Comment.all().filter("entry =", post).order("date")
                t_values['comments'] = comments
            else:
                logging.warning("%d entries share the same slug %s" % (posts.count(), page_slug))

            links = Link.all().order("date")
            t_values['links'] = links

            categories = Category.all()
            t_values['categories'] = categories

            pages = Entry.all().filter("is_external_page =", True).filter("entrytype =", 'page').order("date")
            t_values['pages'] = pages

            return self.response.out.write(render_template("page.html", t_values, "basic", False))
        else:
            self.redirect(uri_for("weblog.index"))
示例#39
0
    def get(self, name = ''):
        objs = Category.get_cat_page_posts(name, 1)

        catobj = Category.get_cat_by_name(name)
        if catobj:
            pass
        else:
            self.redirect(BASE_URL)
            return

        allpost =  catobj.id_num
        allpage = allpost/EACH_PAGE_POST_NUM
        if allpost%EACH_PAGE_POST_NUM:
            allpage += 1

        output = self.render('index.html', {
            'title': "%s - %s"%( catobj.name, getAttr('SITE_TITLE')),
            'keywords':catobj.name,
            'description':getAttr('SITE_DECR'),
            'objs': objs,
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'archives': Archive.get_all_archive_name(),
            'page': 1,
            'allpage': allpage,
            'listtype': 'cat',
            'name': name,
            'namemd5': md5(name.encode('utf-8')).hexdigest(),
            'comments': Comment.get_recent_comments(),
            'links':Link.get_all_links(),
            'isauthor':self.isAuthor(),
            'Totalblog':get_count('Totalblog',NUM_SHARDS,0),
        },layout='_layout.html')
        self.write(output)
        return output
示例#40
0
 def get(self):
     try:
         objs = Article.get_post_for_homepage()
     except:
         self.redirect('/install')
         return
     if objs:
         fromid = objs[0].id
         endid = objs[-1].id
     else:
         fromid = endid = ''
     
     allpost =  Article.count_all_post()
     allpage = allpost/EACH_PAGE_POST_NUM
     if allpost%EACH_PAGE_POST_NUM:
         allpage += 1
     
     output = self.render('index.html', {
         'title': "%s - %s"%(SITE_TITLE,SITE_SUB_TITLE),
         'keywords':KEYWORDS,
         'description':SITE_DECR,
         'objs': objs,
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': 1,
         'allpage': allpage,
         'listtype': 'index',
         'fromid': fromid,
         'endid': endid,
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     return output
示例#41
0
 def get(self, name = ''):
     objs = Tag.get_tag_page_posts(name, 1)
     
     catobj = Tag.get_tag_by_name(name)
     if catobj:
         pass
     else:
         self.redirect(BASE_URL)
         return
     
     allpost =  catobj.id_num
     allpage = allpost/EACH_PAGE_POST_NUM
     if allpost%EACH_PAGE_POST_NUM:
         allpage += 1
         
     output = self.render('index.html', {
         'title': "%s - %s"%( catobj.name, SITE_TITLE),
         'keywords':catobj.name,
         'description':SITE_DECR,
         'objs': objs,
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': 1,
         'allpage': allpage,
         'listtype': 'tag',
         'name': name,
         'namemd5': md5(name.encode('utf-8')).hexdigest(),
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     return output
示例#42
0
def get_comment_list(id, start_page=1, max_page=50):
    """获取评论列表"""
    url = "https://m.weibo.cn/api/comments/show?id=" + str(id)
    page = start_page
    session = requests.session()
    comments_list = []
    while page <= max_page:
        req = prepare_requset(url=url + "&page=" + str(page))
        datas = get_page(req=req, session=session).json()
        if datas.get('ok') != 1:
            break
        else:
            for data in datas.get('data'):
                user = data.get('user')
                text = data.get('text')
                comment = Comment(id=data.get('id'),
                                  user_id=user.get('id'),
                                  user_name=user.get('screen_name'),
                                  source=data.get('source'),
                                  created_at=data.get('created_at'),
                                  text=re.sub(r'<.*?>', '|', text),
                                  reply=data.get('reply_id'))
                comments_list.append(comment)
            page += 1
    return comments_list
示例#43
0
	def post(self,page):
		code=page.param("code")
		OptionSet.setValue("Akismet_code",code)
		rm=page.param('autorm')
		if rm and int(rm)==1:
			rm=True
		else:
			rm=False
		oldrm = OptionSet.getValue("Akismet_AutoRemove",False)
		if oldrm!=rm:
			OptionSet.setValue("Akismet_AutoRemove",rm)
		spam=page.param("spam")
		spam = len(spam)>0 and int(spam) or 0
		sOther = ""
		if spam>0:
			cm = Comment.get_by_id(spam)
			try:
				url = Blog.all().fetch(1)[0].baseurl
				self.SubmitAkismet({
					'user_ip' : cm.ip,
					'comment_type' : 'comment', 
					'comment_author' : cm.author.encode('utf-8'),
					'comment_author_email' : cm.email,
					'comment_author_url' : cm.weburl,
					'comment_content' : cm.content.encode('utf-8')
				},url,"Spam")
				sOther = u"<div style='padding:8px;margin:8px;border:1px solid #aaa;color:red;'>评论已删除</div>"
				cm.delit()
			except:
				sOther = u"<div style='padding:8px;margin:8px;border:1px solid #aaa;color:red;'>无法找到对应的评论项</div>"
		return sOther + self.get(page)
示例#44
0
 def get(self, direction = 'next', page = '2', base_id = '1'):
     if page == '1':
         self.redirect(BASE_URL)
         return
     objs = Article.get_page_posts(direction, page, base_id)
     if objs:
         if direction == 'prev':
             objs.reverse()            
         fromid = objs[0].id
         endid = objs[-1].id
     else:
         fromid = endid = ''
     
     allpost =  Article.count_all_post()
     allpage = allpost/EACH_PAGE_POST_NUM
     if allpost%EACH_PAGE_POST_NUM:
         allpage += 1
     output = self.render('index.html', {
         'title': "%s - %s | Part %s"%(SITE_TITLE,SITE_SUB_TITLE, page),
         'keywords':KEYWORDS,
         'description':SITE_DECR,
         'objs': objs,
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_hot_tag_name(),
         'page': int(page),
         'allpage': allpage,
         'listtype': 'index',
         'fromid': fromid,
         'endid': endid,
         'comments': Comment.get_recent_comments(),
         'links':Link.get_all_links(),
     },layout='_layout.html')
     self.write(output)
     return output
示例#45
0
    def get(self):
        try:
            objs = Article.get_post_for_homepage()
        except:
            self.redirect('/install')
            return
        if objs:
            fromid = objs[0].id
            endid = objs[-1].id
        else:
            fromid = endid = ''

        allpost = Article.count_all_post()
        allpage = allpost / EACH_PAGE_POST_NUM
        if allpost % EACH_PAGE_POST_NUM:
            allpage += 1

        output = self.render('index.html', {
            'title': "%s - %s" % (SITE_TITLE, SITE_SUB_TITLE),
            'keywords': KEYWORDS,
            'description': SITE_DECR,
            'objs': objs,
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'page': 1,
            'allpage': allpage,
            'listtype': 'index',
            'fromid': fromid,
            'endid': endid,
            'comments': Comment.get_recent_comments(),
            'links': Link.get_all_links(),
        },
                             layout='_layout.html')
        self.write(output)
        return output
示例#46
0
    def get(self, name=''):
        objs = Tag.get_tag_page_posts(name, 1)

        catobj = Tag.get_tag_by_name(name)
        if catobj:
            pass
        else:
            self.redirect(BASE_URL)
            return

        allpost = catobj.id_num
        allpage = allpost / EACH_PAGE_POST_NUM
        if allpost % EACH_PAGE_POST_NUM:
            allpage += 1

        output = self.render('index.html', {
            'title': "%s - %s" % (catobj.name, SITE_TITLE),
            'keywords': catobj.name,
            'description': SITE_DECR,
            'objs': objs,
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'page': 1,
            'allpage': allpage,
            'listtype': 'tag',
            'name': name,
            'namemd5': md5(name.encode('utf-8')).hexdigest(),
            'comments': Comment.get_recent_comments(),
            'links': Link.get_all_links(),
        },
                             layout='_layout.html')
        self.write(output)
        return output
示例#47
0
def test_comments():
    comment = request.form.get('comment')

    #Comment Location data
    start = session.get('start')
    end = session.get('end')
    article_id = session.get('article_id')

    user_id = session.get('user_id')

    phrase_key = (article_id, start, end)

    new_comment = Comment(phrase_id=phrase_key,
                          user_id=user_id,
                          article_id=article_id,
                          comment=comment)
    db.session.add(new_comment)
    db.session.commit()

    user = User.query.get(user_id)

    user_name = user.first_name

    image = user.image

    commentData = [{
        'userName': user_name,
        'userComment': comment,
        'userImage': image
    }]

    print "\n\n\n\n\n\n %s \n\n\n\n\n\n" % commentData
    return jsonify(commentData=commentData)
示例#48
0
def post_comment():

    comment = request.form['comment']
    site_id = request.form['site_id']

    print comment

    new_comment = Comment(comment_string=comment,
                          user_id=session['user_id'],
                          site_id=site_id,
                          date=datetime.datetime.today().date())

    db.session.add(new_comment)
    db.session.commit()

    #get the user's profile photo and base64 encode it
    #send the comment and photo in a JSON
    profile_photo = base64.b64encode(new_comment.user.photo)

    success = {
        'comment': new_comment.comment_string,
        "commenter_fname": new_comment.user.fname,
        "commenter_lname": new_comment.user.lname,
        "profile_photo": profile_photo
    }

    return jsonify(success)
示例#49
0
文件: cache.py 项目: fly2014/XBLOG
	def update_basic_info(
		update_categories=False,
		update_tags=False,
		update_links=False,
		update_comments=False,
		update_archives=False,
		update_pages=False):

		from model import Entry,Archive,Comment,Category,Tag,Link
		basic_info = ObjCache.get(is_basicinfo=True)
		if basic_info is not None:
			info = ObjCache.get_cache_value(basic_info.cache_key)
			if update_pages:
				info['menu_pages'] = Entry.all().filter('entrytype =','page')\
							.filter('published =',True)\
							.filter('entry_parent =',0)\
							.order('menu_order').fetch(limit=1000)
			if update_archives:
				info['archives'] = Archive.all().order('-year').order('-month').fetch(12)
			if update_comments:
				info['recent_comments'] = Comment.all().order('-date').fetch(5)
			if update_links:
				info['blogroll'] = Link.all().filter('linktype =','blogroll').fetch(limit=1000)
			if update_tags:
				info['alltags'] = Tag.all().order('-tagcount').fetch(limit=100)
			if update_categories:
				info['categories'] = Category.all().fetch(limit=1000)

			logging.debug('basic_info updated')
			basic_info.update(info)
示例#50
0
def api_delete_comments(id, request):
    check_admin(request)
    c = yield from Comment.find(id)
    if c is None:
        raise APIResourceNotFoundError('Comment')
    yield from c.remove()
    return dict(id=id)
示例#51
0
    def post(self, post_id):
        post_id = int(post_id)
        post = Post.id(post_id)
        if not post:
            #TODO 404
            return
        
        pdict = self.request.POST
        
        nickname = pdict.get("author")
        email = pdict.get("email")
        website = pdict.get("url")
        comment = pdict.get("comment")
        logging.info(website)

        #def new(cls, belong, nickname, email, author=None, re=None, ip=None, website=None, hascheck=True, commenttype=CommentType.COMMENT):
        try:
            c = Comment.new(belong=post,
                            nickname=nickname,
                            email=email,
                            website=website,
                            content=comment,
                            ip=self.request.client_ip)
        except Exception, ex:
            logging.info(traceback.format_exc())
示例#52
0
    def get(self, path):
        gdict = self.GET
        path = urllib.unquote(path)
        if path == config.FEED_SRC: #FEED
            self.set_content_type("atom")
            posts = Post.get_feed_post(config.FEED_NUMBER) 
            self.render("feed.xml", {"posts": posts })
            return

        post = Post.get_by_path(path)
        if post:
            p = gdict.get("p", None)
            p = int(p) if p and p.isdigit() else 1

            def post_comment_filter(query):
                query = query.filter("belong =", post)
                if config.COMMENT_NEEDLOGINED:
                    query = query.filter("hashcheck =", True)
                query = query.order("date_created")
                return query

            post_comments = Comment.fetch_page(p, config.COMMENT_PAGE_COUNT, func=post_comment_filter, realtime_count=True)
            context = {"post": post,
                       "post_comments": post_comments, } 
            self.render("single.html", context)
            return 
示例#53
0
def get_blog(id):
	blog = yield from Blogs.find('id=?',[id])
	comments = yield from Comment.findAll('blog_id=?',[id],orderby='created_at DESC')
	return {
	'__template__':'blog.html',
	'blog':blog,
	'comments':comments
	}
示例#54
0
def get_data():
    query = Comment.select()
    num_data = []
    corpuses = []
    for comment in query:
       data, corpus = create_row(comment) 
       num_data.append(data)
       corpuses.append(corpus)
    return (np.array(num_data), np.array(corpuses))
示例#55
0
 def get(self, id = ''):
     obj = None
     if id:
         obj = Comment.get_comment_by_id(id)
         if obj:
             act = self.get_argument("act",'')
             if act == 'del':
                 Comment.del_comment_by_id(id)
                 clear_cache_by_pathlist(['post:%d'%obj.postid])
                 self.redirect('%s/admin/comment/'% (BASE_URL))
                 return
     self.echo('admin_comment.html', {
         'title': "管理评论",
         'cats': Category.get_all_cat_name(),
         'tags': Tag.get_all_tag_name(),
         'obj': obj,
         'comments': Comment.get_recent_comments(),
     },layout='_layout_admin.html')
示例#56
0
    def get(self, page_id="", operation=""):
        # find all comments, and list all comments
        t_values = {}
        logging.info("CommentManager get")

        # show all comments
        comments = Comment.all().order("entry")
        t_values['comments'] = comments
        return self.response.out.write(render_template("comments.html", t_values, "", True))
示例#57
0
    def get(self, id = '', title = ''):
        tmpl = ''
        obj = Article.get_article_by_id_detail(id)
        if not obj:
            self.redirect(BASE_URL)
            return
        #redirect to right title
        try:
            title = unquote(title).decode('utf-8')
        except:
            pass
        if title != obj.slug:
            self.redirect(obj.absolute_url, 301)
            return
        #
        if obj.password and THEME == 'default':
            rp = self.get_cookie("rp%s" % id, '')
            if rp != obj.password:
                tmpl = '_pw'
        elif obj.password and BLOG_PSW_SUPPORT:
            rp = self.get_cookie("rp%s" % id, '')
            print 'rp===%s' % (str(rp))
            if rp != obj.password:
                tmpl = '_pw'

        keyname = 'pv_%s' % (str(id))
        increment(keyname)#yobin 20120701
        self.set_cookie(keyname, '1', path = "/", expires_days =1)
        self.set_header("Last-Modified", obj.last_modified)
        output = self.render('page%s.html'%tmpl, {
            'title': "%s - %s"%(obj.title, getAttr('SITE_TITLE')),
            'keywords':obj.keywords,
            'description':obj.description,
            'obj': obj,
            'cobjs': obj.coms,
            'postdetail': 'postdetail',
            'cats': Category.get_all_cat_name(),
            'tags': Tag.get_hot_tag_name(),
            'archives': Archive.get_all_archive_name(),
            'page': 1,
            'allpage': 10,
            'comments': Comment.get_recent_comments(),
            'links':Link.get_all_links(),
            'isauthor':self.isAuthor(),
            'hits':get_count(keyname),
            'Totalblog':get_count('Totalblog',NUM_SHARDS,0),
            'listtype': '',
        },layout='_layout.html')
        self.write(output)

        if obj.password and BLOG_PSW_SUPPORT:
            return output
        elif obj.password and THEME == 'default':
            return
        else:
            return output
示例#58
0
文件: admin.py 项目: yobin/saepy-log
 def get(self, id=""):
     obj = None
     if id:
         obj = Comment.get_comment_by_id(id)
         if obj:
             act = self.get_argument("act", "")
             if act == "del":
                 Comment.del_comment_by_id(id)
                 if MYSQL_TO_KVDB_SUPPORT:
                     clear_cache_by_pathlist(["post:%d" % obj["postid"]])
                 else:
                     clear_cache_by_pathlist(["post:%d" % obj.postid])
                 self.redirect("%s/admin/comment/" % (BASE_URL))
                 return
     self.echo(
         "admin_comment.html",
         {"title": "管理评论", "obj": obj, "comments": Comment.get_recent_comments(ADMIN_RECENT_COMMENT_NUM)},
         layout="_layout_admin.html",
     )
示例#59
0
文件: blog.py 项目: sunruijia/simblog
 def post(self):
     try:
         checkList = self.request.get_all('checks')
         for key in checkList:
             keyID = int(key)
             comment=Comment.get_by_id(keyID)
             comment.delete()
     finally:
         self.redirect('/admin/comments')
     return
示例#60
0
 def get(self,commID):
   comm = Comment.get_by_id(int(commID))
   if comm is None:
     return self.redirect('/')
   post = comm.post
   post.commentcount -= 1
   link = comm.post.full_permalink()
   comm.delete()
   util.flushRecentComment()
   return self.redirect(link)