コード例 #1
0
def delete(target_post: Post):
    try:
        target_post.delete()

        db.session.commit()
    except Exception as e:
        db.session.rollback()
        raise e
コード例 #2
0
def update(target_post: Post, post_data: Post):
    try:
        target_post.content = post_data.content
        target_post.description = post_data.description
        target_post.title = post_data.title

        db.session.commit()
    except Exception as e:
        db.session.rollback()
        raise e
コード例 #3
0
def create(board_id, post: Post, user: User):
    try:
        board = Board.query.get(board_id)
        post.board_id = board.id
        post.user_id = user.id

        db.session.add(post)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        raise e
コード例 #4
0
def post_get(path):
    checked,path=util.checkPostLocation(path)
    if not checked:
        flash("路径参数错误",'danger')
        return render_template('hintInfo.html')
    else:
        abspath=os.path.join(current_app.config['PAGE_DIR'],path)+".md"
        if not os.path.exists(abspath):
            flash("页面不存在!",'danger')
            return render_template('hintInfo.html',canCreate=True,location=path)
        else:
            # with open(abspath,encoding='UTF-8') as f:
            #     content=f.read()
            # #title=content.split('\n\n',1)[0]
            # #content=content.split('\n\n',1)[1]
            # md_ext=util.Constant.md_ext
            # md=markdown.Markdown(output_format='html5',encoding='utf-8',extensions=md_ext)
            # html=util.html_clean(md.convert(content))
            #
            # toc=md.toc
            # meta=md.Meta
            html,toc,meta=utilpost.get_post_content(abspath)
            log.debug('meta %s' % meta)
            post=Post.query.get(path)
            if not post:
                post=Post(location=path)
            # user=User.query.get(post.userId)
            tagNames=[]
            if post.tags:
                tagNames=[tag.name for tag in post.tags]
            return render_template('page.html',content=html,toc=toc,title=meta.get('title',' ')[0],post=post,author=meta.get('author',' ')[0] ,meta=meta,tagNames=tagNames)
コード例 #5
0
def add_comment(target_post: Post, user: User, comment: Comment):
    target_group = target_post.add_comment_group()

    try:
        # new_comment_group은 group에 댓글을 추가하는 책임을 수행한다.
        new_comment = target_group.add_comment(user=user, comment=comment)
    except Exception as e:
        raise e

    return new_comment
コード例 #6
0
def moment(page=1):
    """
    动态列表页面
    :return:
    """
    if request.method == 'GET':
        moments = Moment.get_moments(page=page, limit=10)
        print(moments)
        latest_posts = Post.get_latest_posts(5)
        return render_template("home/moment.html",
                               moments=moments,
                               latest_posts=latest_posts)
コード例 #7
0
def search(page=1):
    from app.function.config import get_config
    pagination = get_home_search_paginate(
        page=page,
        per_page=int(get_config("web_home_posts_pages")),
        query=request.args.get('query'))
    latest_posts = Post.get_latest_posts(5)
    return render_template('home/index.html',
                           posts=pagination.items,
                           latest_posts=latest_posts,
                           pagination=pagination,
                           current_index='index')
コード例 #8
0
ファイル: post.py プロジェクト: ciel002/blog
def add_post():
    """
    写文章页面
    :return:
    """
    navigation = get_navigation_info(title="写文章", sub_title="写一篇新的文章", tag="add_post")
    form = PostForm()
    if request.method == 'GET':
        return render_template("admin/edit_post.html", navigation=navigation, form=form)
    if request.method == 'POST':
        post = Post(
            title=form.title.data,
            abstract=form.abstract.data,
            content=form.content.data,
            uid=current_user.id,
            category_id=form.category_id.data,
            rank=form.rank.data,
            is_top=form.is_top.data,
            post_property=form.post_property.data,
            status=form.status.data)
        post.add_one()
        return redirect(url_for('admin.post'))
コード例 #9
0
ファイル: post.py プロジェクト: FashAm/hackldn2012
 def on_post(self):
     try:
         imgs = []
         for i in range(int(self.request.arguments['numPhotos'][0])):
             img_name = 'myImage' + str(i) 
             imgs.append(self.request.arguments[img_name][0])
         images = self.store_images(imgs) 
         #Create post object
         post = Post()
         post.aid = self.request.arguments['userId'][0]
         
         post.desc = self.request.arguments['description'][0]
         
         for tag in self.request.arguments['tag1'][0].split('\n'):
             post.tags1.append(tag)
         
         for tag in self.request.arguments['tag2'][0].split('\n'):
             post.tags2.append(tag)
             
         phone_no = self.request.arguments['phoneNumber'][0]
         
         for modifier in self.request.arguments['visibility'][0].split(';'):    
             post.visibility.append(modifier)
         
         for image in images:
             post.images.append(image)
         
         post.save()
         self.write('Your photo was successfully fashamified. Very soon other stylish Fashamers will give feedback.')
         
         #Notify the advisors
         #Hacking
         phone_no = phone_no[1:]
         phone_no = "+44" + phone_no
         
         self.notify(customer_name=post.aid, phone_no=phone_no)
     except Exception,e :
         print "Error"+str(e)
コード例 #10
0
ファイル: category.py プロジェクト: ciel002/blog
def category(category_sub_name, page=1):
    from app.function.config import get_config
    pagination = get_home_category_paginate(
        page=page,
        per_page=int(get_config("web_home_posts_pages")),
        category_sub_name=category_sub_name)
    latest_posts = Post.get_latest_posts(5)
    return render_template(
        'home/index.html',
        current_category=category_sub_name,
        posts=pagination.items,
        latest_posts=latest_posts,
        pagination=pagination,
    )
コード例 #11
0
    def post(self):
        try:
            title = request.json['title']
            contents = request.json['contents']
            user_name = request.json['user_name']
        except Exception as e:
            return jsonify({
                "messege": "need post info",
                "exception": str(e)
            }), 400

        posts = Post.insert(title=title, content=contents, user=user_name)
        posts.execute()

        return '글작성 완료', 200
コード例 #12
0
def index():
    posts_count = Post.get_posts_count()
    comments_count = PostComment.get_comments_count()
    users_count = User.get_users_count(0)
    explore_count = get_explore_count()
    context = {
        'posts_count': posts_count,
        'comments_count': comments_count,
        'users_count': users_count,
        'explore_count': explore_count,
    }
    navigation = get_navigation_info(title="仪表盘", sub_title="控制器", tag="index")
    return render_template("admin/index.html",
                           navigation=navigation,
                           **context)
コード例 #13
0
    def post(self):
        try:
            user_id = get_jwt_identity()
            body = request.get_json()
            search_all = Search.objects(owner=user_id).first()
            if search_all == None:
                search_all = Search(owner=user_id).save()
            Search.objects(owner=user_id).update_one(
                push__history_search=body["keyword"])
            users = json.loads(
                User.objects(username__icontains=body["keyword"]).to_json())
            posts = json.loads(
                Post.objects(described__icontains=body["keyword"]).to_json())
            for index, post in enumerate(posts):
                like = Like.objects.get(post=post["id"])
                is_liked = like.is_liked(user_id)
                posts[index]["is_liked"] = is_liked
            data = []

            for index, user in enumerate(users):
                if str(user["id"]) == str(user_id):
                    del users[index]
                items = {}
                items["username"] = user["username"]
                items["id"] = user["id"]
                friend = Friend.objects.get(owner=user["id"])
                if friend.is_friend(user_id):
                    items["is_friend"] = True
                else:
                    items["is_friend"] = False
                data.append(items)

            self.res["user"] = data
            self.res["posts"] = posts[::-1]
        except DoesNotExist:
            self.res = response.user_is_invalid
        except Exception:
            self.res = response.internal_server()
            raise Exception
        return jsonify(self.res)
コード例 #14
0
    def get(self, id):
        try:
            user_id = get_jwt_identity()
            like = Like.objects.get(post=id)
            for userEmbed in like.user_like:
                if str(userEmbed["user"]) == user_id:
                    self.check_user = True
                    like.update(pull__user_like=userEmbed)
            
            if not self.check_user:
                raise Exception

            post = Post.objects(id=id).first()
            if post.like < 0:
                raise Exception
            post.update(dec__like=1)
            self.res = resCon.like_convert(post)
        except DoesNotExist:
            self.res = response.post_is_not_exit()
        except Exception:
            self.res = response.internal_server()
        return jsonify(self.res)
コード例 #15
0
ファイル: user.py プロジェクト: ciel002/blog
def my_posts():
    posts = Post.get_posts_info_by_user(current_user.id)
    print(posts[0].keys())
    return render_template("home/user_my_posts.html", user=user, posts=posts)
コード例 #16
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')
コード例 #17
0
ファイル: main.py プロジェクト: Gaegul/flask_minitwit
    def get(self):
        main_post = Post.select().order_by(Post.create_at).dicts()
        res = list(main_post)

        return jsonify(res), 200
コード例 #18
0
ファイル: index.py プロジェクト: ciel002/blog
def index(page=1):
    from app.function.config import get_config
    pagination = get_home_index_paginate(page=page, per_page=int(get_config("web_home_posts_pages")))
    latest_posts = Post.get_latest_posts(limit=3)
    return render_template('home/index.html', posts=pagination.items
                           , latest_posts=latest_posts, pagination=pagination, current_index='index')