示例#1
0
def index(page=1):
    user = current_user
    form = PostForm()

    if form.validate_on_submit():
        post_body = form.post.data
        user_id = user.id
        nickname = user.nickname
        userController = UserController()
        userController.addpost(user_id=user_id,
                               nickname=nickname,
                               post_body=post_body)
        return redirect(url_for('index'))

    # get posts
    followed_posts_results = current_user.followed_posts(page=page)
    posts = followed_posts_results['posts']
    has_pre_page = followed_posts_results['has_pre_page']
    pre_page_num = followed_posts_results['pre_page_num']
    has_next_page = followed_posts_results['has_next_page']
    next_page_num = followed_posts_results['next_page_num']

    template_naeme = 'posts.html'
    return render_template(template_naeme,
                           title='Posts',
                           posts=posts,
                           user=user,
                           form=form,
                           has_next_page=has_next_page,
                           next_page_num=next_page_num,
                           has_pre_page=has_pre_page,
                           pre_page_num=pre_page_num)
示例#2
0
def index():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post is now live!')
        return redirect(url_for('index'))
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('index',
                       page=posts.next_num) if posts.has_next else None
    prev_url = url_for('index',
                       page=posts.prev_num) if posts.has_prev else None
    return render_template('index.html',
                           title='Home Page',
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url)
示例#3
0
def index(page=1):
    '''
    user = {'nickname':'Miguel'}  #fake user
    template_name ='index.html'
    return render_template(template_name,title='Home',user=user)
    '''
    userController = UserController()
    form = PostForm()
    user = current_user
    if form.validate_on_submit():
        post_body = form.post.data
        user_id = user.id
        user_nickname = user.nickname
        # userController = UserController()
        userController.addpost(user_id=user_id, nickname=user_nickname, post_body=post_body)
        flash('Your post is now living!')

        return redirect(url_for('index'))

    # fakearray of posts
    '''posts=[{'author':{'nickname':'John'},'body':'Beautiful day in Portland!'},
           {'author':{'nickname':'Susan'},'body':'The Avengers movie was so coolbbbbbb!!'}]'''

    followed_posts_results = current_user.followed_posts(page=page)
    # posts =current_user.show_all_posts()
    # posts = current_user.show_all_posts()
    posts = followed_posts_results['posts']

    has_pre_page = followed_posts_results['has_pre_page']
    pre_page_num = followed_posts_results['pre_page_num']
    has_next_page = followed_posts_results['has_next_page']
    next_page_num = followed_posts_results['next_page_num']

    template_name = 'posts.html'

    return render_template(template_name, title='Home', user=user, posts=posts, form=form,
                           has_pre_page=has_pre_page, pre_page_num=pre_page_num,
                           has_next_page=has_next_page, next_page_num=next_page_num)
示例#4
0
def post_edit(path):
    path = util.urlDirPathFormat(path)
    abspath = os.path.join(current_app.config['PAGE_DIR'],
                           path.replace('/', os.sep)) + ".md"
    if not os.path.exists(abspath):
        flash("文章不存在", 'warning')
        return render_template('hintInfo.html')
    isAdmin = util.checkAdmin()

    post = Post.query.filter_by(location=path).first()

    if post and post.userId != str(current_user.id) and (not isAdmin):
        flash("您没有权限编辑此文章!", 'warning')
        return render_template('hintInfo.html')

    if utilpost.isPostLocked(path):
        flash("文章已被锁定,您暂时无权编辑")
        return render_template('hintInfo.html')
    utilpost.createPostLock(path)

    with open(abspath, encoding='UTF-8') as f:
        content = f.read()
        # print('fcontent'+fcontent)
        # form.content.data=fcontent
    meta = content.split('\n\n', 1)[0]
    meta = util.parsePostMeta(meta)  # a dict
    content = content.split('\n\n', 1)[1]

    tags = ''
    location = path

    if post:
        tags = ','.join([t.name for t in post.tags])
        location = post.location

    fileModifyAt = datetime.fromtimestamp(
        os.stat(abspath).st_mtime).strftime('%Y-%m-%d %H:%M:%S')
    form = PostForm(title=meta.get('title', ''),
                    content=content,
                    location=location,
                    tags=tags,
                    createAt=meta.get('createAt', ''),
                    modifyAt=meta.get('modifyAt', ' '),
                    fileModifyAt=fileModifyAt)

    return render_template('editor.html',
                           isPost=True,
                           action=url_for('.post_save'),
                           form=form)
示例#5
0
def post_new(path):
    checked,path=util.checkPostLocation(path)
    if not checked:
        flash("路径参数错误",'danger')
        return render_template('hintInfo.html')
    else:
        if utilpost.isPostLocked(path):
            flash("文章已被锁定,其他人正在编辑,您暂时无法编辑.")
            return render_template('hintInfo.html')

        utilpost.createPostLock(path)
        
        abspath=os.path.join(current_app.config['PAGE_DIR'],path)+".md"
        if not os.path.exists(abspath):
            form=PostForm()
            form.location.data=path
            flash('文章不存在,新建文章','info')
            return render_template('editor.html',title='新建文章',action=url_for('.post_save'),form=form,isPost=True)
示例#6
0
def post_save():
    form=PostForm()
    if form.validate_on_submit():
        checked,location=util.checkPostLocation(form.location.data)
        if not checked:
            flash('文章地址不合法', 'danger')
            return render_template('hintInfo.html')

        postExist=os.path.exists(util.getAbsPostPath(location))
        post=Post.query.filter_by(location=location).first()
        isAdmin=util.checkAdmin()

        isNew=True if not post else False
        if isNew and postExist and not isAdmin:
            flash("文章早已存在,您没有权限操作",'info')
            return redirect(url_for('.post_get',path=location))

        meta=dict(title=form.title.data,author=current_user.username or current_user.email,
            createAt=form.createAt.data,location=location
            ,modifyAt=util.getNowFmtDate())

        if isNew:
            meta['createAt']=util.getNowFmtDate()
            post=Post()
            post.location = location
            post.userId = current_user.id
            db.session.add(post)
            # else:
            #     flash('error location for post!','danger')
            #     return
        abspath=util.getAbsPostPath(post.location)
        if(form.fileModifyAt.data) and os.path.exists(abspath):
            orginModifyAt=datetime.fromtimestamp(os.stat(abspath).st_mtime).strftime('%Y-%m-%d %H:%M:%S')
            #如果文件修改时间对不上,说明文件已经被修改过了
            if form.fileModifyAt.data!=orginModifyAt:
                flash("保存失败,在您编辑文章过程中,文件已经被修改过了!")
                return render_template('hintInfo.html')

        tags=form.tags.data.lower().split(',')
        tagsList=[]
        if isinstance(tags,list):
            for tagStr in tags:
                tagObj=Tag.query.filter_by(name=tagStr).first()
                if not tagObj:
                    # db.session.add(Tag(tagStr))
                    tagsList.append(Tag(tagStr))
                else:
                    # db.session.add(tagObj)
                    tagsList.append(tagObj)
        else:
            tagObj = Tag.query.filter_by(name=tags[0]).first()
            if not tagObj:
                # db.session.add(Tag(tagStr))
                tagsList.append(Tag(tags[0]))
            else:
                # db.session.add(tagObj)
                tagsList.append(tagObj)

        #post=db.session.merge(post)
        #print(post in db.session)
        post.tags=tagsList


        abspath=util.getAbsPostPath(post.location)

        if post.location.find(os.sep)>0:
            dir=abspath.rsplit(os.sep,1)[0]

            if not os.path.exists(dir):
                os.makedirs(dir)
        with open(abspath,'w+',encoding='UTF-8') as f:
            # 这一步很坑,一定要去掉\r,否则每次编辑器显示都会多出空行
            content = form.content.data.replace('\r', '')
            # print(meta)
            f.write(util.fmtPostMeta(meta)+content)
        postvo=vo.SearchPostVo(content=content,summary=content[:100],**meta)
        if isNew:
            searchutil.indexDocument([postvo])
        else:
            searchutil.updateDocument([postvo])

        utilpost.releasePostLock(post.location)
        utilpost.delete_post_cache(abspath)
        return redirect(url_for('.post_get',path=post.location))

    flash('保存失败', 'danger')
    return render_template('hintInfo.html')