def post(self):
        subject = self.request.get('subject')
        content = self.request.get('content')

        if self.user and subject and content:
            b = Blog(subject=subject,
                     content=content,
                     author=self.user)
            b.put()
            time.sleep(0.1)  # sleep is used due to lag time
            self.redirect('/%d' % b.key.id())  # redirect to permalink
        else:
            self.render('newpost.html', subject=subject, content=content)
Exemple #2
0
def init_blog_db():
    blog1 = Blog(title="954.二倍数对数组")
    blog1.url_id = gen_blog_url_id()

    cat1 = BlogCategory(name="LeetCode")
    cat2 = BlogCategory(name="Python3")
    cat3 = BlogCategory(name="AI&ML")
    cat4 = BlogCategory(name="C++")

    blog1.category = cat1

    db.session.add_all([blog1])
    db.session.add_all([cat1, cat2, cat3, cat4])
    db.session.commit()
    def get(self, blog_id):
        blog_key = Blog.get_by_id(int(blog_id))
        comment_key = Comments.gql("WHERE blog_id = %s "
                                   "ORDER BY created DESC" % int(blog_id))

        # render the blog object and all of it's comment
        self.render("blogpost.html", blogs=[blog_key], comments=comment_key)
Exemple #4
0
def get_all_month():
    res_list = set()
    for item in Blog.objects(delete_time=None):
        res_list.add(format_datetime(item.create_time, '%Y-%m'))
    res_list = list(res_list)
    res_list.sort(reverse=True)
    return res_list
Exemple #5
0
def blogs():
    if request.method == 'GET':
        page = request.args.get('page', 1, int)
        per_page = 10
        if current_user.is_authenticated is False:
            visible = [Blog.VISIBLE_ALL]
        else:
            visible = [Blog.VISIBLE_ALL, Blog.VISIBLE_LOGIN, Blog.VISIBLE_OWNER]
        blogs = list()
        for item in Blog.objects(delete_time=None, visible__in=visible):
            if item.visible == Blog.VISIBLE_OWNER and item.author != current_user.id:
                continue
            else:
                blogs.append(item.as_dict())
        # blogs = [item.as_dict() for item in Blog.objects(delete_time=None)]
        blogs.sort(key=lambda item: item['create_time'], reverse=True)
        total = len(blogs)
        blogs = blogs[per_page * (page - 1): per_page * page]
    else:
        pass

    monthes = get_all_month()

    return render_template('home/blog.html', blogs=blogs, monthes=monthes, total=total, per_page=per_page, page=page,
                           keyword='', tags=get_tags_cloud(), blog_count=get_blog_count(), next_page_url='blogs')
    def get(self, blog_id):
        key = Blog.get_by_id(int(blog_id))

        if self.user:
            # rendering the blog post using blog_id
            self.render("editpost.html", blogs=[key])
        else:
            self.redirect("/login")
    def post(self, blog_id):
        key = int(blog_id)  # get id and turns into integer
        post = Blog.get_by_id(key)  # use id to fine the blog post item

        if self.user.name == post.author.name:
            post.key.delete()  # delete the found item
            time.sleep(0.1)  # sleep is used because of replication lag time

        self.redirect('/')  # redirect to home
Exemple #8
0
def get_blog_count():
    """
    获得自己的博客数量
    user_id 是ObjectId
    """
    if not current_user.is_active:
        return 0
    count = Blog.objects(author=current_user.id, delete_time=None).count()
    return count
    def post(self, blog_id):
        key = int(blog_id)
        post = Blog.get_by_id(key)

        if post and self.user:
            post.like -= 1
            like = Likes(blog_id=key, author=self.user)
            like.put()
            post.put()
            time.sleep(0.2)
            self.redirect('/%s' % key)
        else:
            self.redirect('/login')
Exemple #10
0
def show_blog(id):
    blog = Blog.objects.with_id(ObjectId(id))
    if not blog:
        return jsonify(success=False, error='不存在该日志')
    if (blog.visible in [Blog.VISIBLE_LOGIN, Blog.VISIBLE_OWNER] and current_user.is_authenticated is False) \
        or (blog.visible == Blog.VISIBLE_OWNER and current_user.id != blog.author):
        return abort(403)

    # 增加观看量
    Blog.objects(id=ObjectId(id)).update(inc__view_count=1)
    # 设置上个观察者的ip
    Blog.objects(id=ObjectId(id)).update(set__last_view_ip=request.remote_addr)
    # 设置上个观看者的用户id
    Blog.objects(id=ObjectId(id)).update(set__last_view_user=current_user.id if current_user.is_active and current_user.is_anounymous is False else None)
    # 设置上次观看的时间
    Blog.objects(id=ObjectId(id)).update(set__last_view_time=now_lambda())

    prev, next = Blog.get_prev_next(unicode(blog.id), current_user)
    monthes = get_all_month()
    return render_template('home/blog_detail.html', blog=blog.as_dict(), prev=prev, next=next, monthes=monthes, tags=get_tags_cloud())
    def post(self, blog_id):
        key = int(blog_id)
        post = Blog.get_by_id(key)
        subject = self.request.get('subject')
        content = self.request.get('content')

        # current user.name has to match
        # with author's name
        if self.user.name == post.author.name:
            if subject and content:
                post.subject = subject  # updating the subject
                post.content = content  # updating the content
                post.put()
                time.sleep(0.1)
                self.redirect('/%s' % key)  # redirect to the blog post
            else:
                msg = "Something went wrong. Please try again."
                self.render("editpost.html", blogs=[key], error_message=msg)
        else:
            self.redirect('/login')
Exemple #12
0
def get_archive_blogs(month):
    """返回某一月的blog"""
    page = request.args.get('page', 1, int)
    per_page = 10
    if current_user.is_authenticated is False:
        visible = [Blog.VISIBLE_ALL]
    else:
        visible = [Blog.VISIBLE_ALL, Blog.VISIBLE_LOGIN, Blog.VISIBLE_OWNER]
    blogs = list()
    for item in Blog.objects(delete_time=None, visible__in=visible,
                             create_time__gte=to_datetime(month + '-01 00:00:00', '%Y-%m-%d %H:%M:%S'),
                             create_time__lt=to_datetime(get_next_month(month) + '-01 00:00:00', '%Y-%m-%d %H:%M:%S')):
        if item.visible == Blog.VISIBLE_OWNER and item.author != current_user.id:
            continue
        else:
            blogs.append(item.as_dict())

    blogs.sort(key=lambda item: item['create_time'], reverse=True)
    total = len(blogs)
    blogs = blogs[per_page * (page - 1): per_page * page]
    monthes = get_all_month()
    return render_template('home/blog.html', blogs=blogs, monthes=monthes, total=total, per_page=per_page, page=page,
                           keyword='', tags=get_tags_cloud(), blog_count=get_blog_count(), next_page_url='blog-archive/%s' % month)
Exemple #13
0
def create_blog(cat_id):
    if request.method == 'GET':
        cat_all = BlogCategory.query.filter().all()
        blog_cat = BlogCategory.query.filter(BlogCategory.id == int(cat_id)).first()

        dicts = {
            'cat_all': cat_all,
            'note_cat': blog_cat,
            'catid': cat_id
        }
        return render_template('blog/create_blog.html', **dicts)
    else:
        title = request.form.get('docTitle')
        if title:
            new_blog = Blog(title=title)
            new_blog.url_id = gen_blog_url_id()

            username = session.get('username')
            # 指定用户
            if username:
                user = User.query.filter(User.username == username).first()
            else:
                user = User.query.filter().first()
            new_blog.user = user
            # 设定类别
            note_cat = BlogCategory.query.filter(BlogCategory.id == int(cat_id)).first()
            new_blog.category = note_cat

            # 记录内容
            content = request.form.get('docContent')
            path = FILESERVER + PATHSEP + 'blogs' + PATHSEP + cat_id + secure_filename(''.join(lazy_pinyin(note_cat.name))) + PATHSEP
            full_filename = path + secure_filename(''.join(lazy_pinyin(title))) + '.md'
            if not os.path.exists(path):
                os.makedirs(path)
            sec_writefile(full_filename, content)
            new_blog.content_path = full_filename
            # 更新数据库
            db.session.add(new_blog)
            db.session.commit()

        return redirect(url_for('main.blogs_cat', note_catid=int(cat_id)))
Exemple #14
0
def test_prev_next():
    print Blog.get_prev_next('56c462de59acd1470c262e04')
Exemple #15
0
def blog_edit():
    if request.method == 'GET':
        tags = get_tags()
        tags = map(lambda x: x['name'], tags)
        blog = None
        _id = request.args.get('id', '')
        if _id:
            blog = Blog.objects.with_id(_id)
            for tag in blog.tags:
                if tag in tags:
                    tags.remove(tag)
        tag_list = tags
        tags = json.dumps(tags)
        if blog:
            return render_template('home/blog_edit2.html', blog=blog, data=json.dumps(blog.as_dict()), tags=tags,
                                   tag_list=tag_list)
        else:
            return render_template('home/blog_edit2.html', blog=None, data=json.dumps({}), tags=tags, tag_list=tag_list)
    else:
        _id = request.form.get('id', '').strip()
        if _id:
            blog = Blog.objects.with_id(_id)
        else:
            blog = Blog()
        title = request.form.get('title', '').strip()
        content = request.form.get('content', '').strip()
        visible = request.form.get('visible', 1, int)
        tags = request.form.getlist('tags[]')
        blog.title = title
        blog.content = content
        blog.author = current_user.id
        blog.visible = visible
        blog.tags = tags
        if _id:
            blog.update_time = now_lambda()
        else:
            blog.create_time = now_lambda()
            blog.update_time = blog.create_time
        try:
           blog.save()
        except ValidationError, e:
            return jsonify(success=False, error='save failed %s' % e)

        # 保存tag
        for tag in tags:
            blog_tag = BlogTag.objects(name=tag).first()
            if not blog_tag:
                blog_tag = BlogTag(name=tag, count=1, last_use_time=now_lambda(), create_time=now_lambda())
                blog_tag.save()
            else:
                blog_tag.update_time = now_lambda()
                blog_tag.last_use_time = now_lambda()
                blog_tag.count += 1
                blog_tag.save()
        return jsonify(success=True, error='提交成功', blog=blog.reload().as_dict())