コード例 #1
0
def index():
    form = PostsForm()
    if form.validate_on_submit():
        # 判断是否登录
        if current_user.is_authenticated:
            # 获取原始的用户对象
            u = current_user._get_current_object()
            # 创建对象
            p = Posts(content=form.content.data, user=u)
            # 保存到数据库
            db.session.add(p)
            flash('发表成功')
            return redirect(url_for('main.index'))
        else:
            flash('登录之后才可以发表')
            return redirect(url_for('user.login'))
    # 读取博客
    # posts = Posts.query.filter(Posts.id == 0)
    # 分页查询
    page = request.args.get('page', 1, int)  # 将获取的页码参数转为int类型
    pagination = Posts.query.filter(Posts.rid == 0).paginate(page,
                                                             per_page=10,
                                                             error_out=False)
    posts = pagination.items
    return render_template('main/index.html',
                           form=form,
                           pagination=pagination,
                           posts=posts)
コード例 #2
0
def index():
    form = PostsForm()
    if form.validate_on_submit():
        if current_user.is_authenticated:
            u = current_user._get_current_object()
            p = Posts(content=form.content.data, user=u)
            db.session.add(p)
            flash("发表成功")
            return redirect(url_for('main.index'))
        else:
            flash("登录后才可发表")
            return redirect(url_for("user.login"))
    # 读取博客
    # posts = Posts.query.filter(Posts.rid==0).order_by(Posts.timestamp.desc()).all()
    page = request.args.get("page", 1, type=int)
    pagination = Posts.query.filter(Posts.rid == 0).order_by(
        Posts.timestamp.desc()).paginate(page=page,
                                         per_page=5,
                                         error_out=False)
    # 当前页码的数据
    posts = pagination.items
    return render_template('main/index.html',
                           form=form,
                           posts=posts,
                           pagination=pagination)
コード例 #3
0
ファイル: main.py プロジェクト: c727657851/flask_blog
def index():
    # 发表
    form = PostsForm()

    if form.validate_on_submit():
        # 用户想发表内容必须先登录  并且获取当前登录用户名
        if current_user.is_authenticated:
            # 获取该用户对象
            u = current_user._get_current_object()
            p = Posts(content=form.content.data, user=u)
            db.session.add(p)
            db.session.commit()
            return redirect(url_for('main.index'))
        else:
            flash('请先登录')
            return redirect(url_for('users.login'))

    # posts = Posts.query.filter_by(rid=0).all()  # 获取发表的内容
    # 获取用户查看第几页
    page = request.args.get('page', 1, type=int)

    #
    pagination = Posts.query.filter_by(rid=0).order_by(
        Posts.timestamp.desc()).paginate(page, per_page=5, error_out=False)
    posts = pagination.items  # 当前对象的所有数据

    return render_template('main/index.html',
                           form=form,
                           posts=posts,
                           pagination=pagination)
コード例 #4
0
def userPosts(user_id):

    #Gets the current user to add/display posts to
    user = db.session.query(Users).get(user_id)

    form = PostsForm()
    if request.method == "POST" and form.validate_on_submit() == True:
        caption = form.caption.data
        photo = assignPath(form.photo.data)
        post = Posts(photo, caption, user_id)
        db.session.add(post)
        db.session.commit()

        #Flash message to indicate a post was added successfully
        success = "Successfully created a new post"
        return jsonify(message=success), 201

    elif request.method == "GET":
        posts = []
        for post in user.posts:
            p = {
                "id": post.id,
                "user_id": post.user_id,
                "photo": post.photo,
                "description": post.caption,
                "created_on": post.created_on
            }
            posts.append(p)
        return jsonify(posts=posts)

    #Flash message to indicate an error occurred
    failure = "Failed to create/display posts"
    return jsonify(error=failure)
コード例 #5
0
ファイル: main.py プロジェクト: lei375809291/Flask
def index():
    form = PostsForm()
    if form.validate_on_submit():
        if not current_user.is_authenticated:
            flash('登录后才可发表')
            return redirect(url_for('user.login'))
        u = current_user._get_current_object()
        p = Posts(content=form.content.data, user=u)
        db.session.add(p)
        flash('发表成功')
        return redirect(url_for('main.index'))
    # 读取所有发表博客的数据(不分页)
    # posts= Posts.query.filter(Posts.rid==0).order_by(Posts.timestamp.desc()).all()
    # 分页查询发表博客的数据
    # 获取当前页码
    page = request.args.get('page', 1, int)
    pagination = Posts.query.filter(Posts.rid == 0).order_by(
        Posts.timestamp.desc()).paginate(page=page,
                                         per_page=10,
                                         error_out=False)
    posts = pagination.items
    return render_template('main/index.html',
                           form=form,
                           posts=posts,
                           pagination=pagination)
コード例 #6
0
ファイル: main.py プロジェクト: meiubug/xxxxxx
def index():
    form = PostsForm()
    if form.validate_on_submit():
        if current_user.is_authenticated:
            # 获取当前登录用户对象
            user = current_user._get_current_object()
            # 创建对象
            p = Posts(content=form.content.data, user=user)
            # 保存到数据库
            db.session.add(p)
            flash('发表成功')
            return redirect(url_for('main.index'))
        else:
            flash('请登录后再发表')
            return redirect(url_for('user.login'))
    # 查询博客
    # posts = Posts.query.filter(Posts.rid == 0).order_by(Posts.timestamp.desc())
    # 分页查询
    page = request.args.get('page', 1, int)
    pagination = Posts.query.filter(Posts.rid == 0).order_by(
        Posts.timestamp.desc()).paginate(page, per_page=3, error_out=False)
    posts = pagination.items
    return render_template('main/index.html',
                           form=form,
                           posts=posts,
                           pagination=pagination)
コード例 #7
0
def index():
    form = PostsForm()
    if form.validate_on_submit():
        # 判断是否登录
        if current_user.is_authenticated:
            # 获取当前用户
            u = current_user._get_current_object()
            # 创建博客对象
            p = Posts(content=form.content.data, user=u)
            # 保存到数据库
            db.session.add(p)
            return redirect(url_for('main.index'))
        else:
            flash('用户尚未登录。请登录后发表')
            return redirect(url_for('user.login'))
    # 分页读取数据
    # 获取get参数里的页码,默认为当前页
    page = request.args.get('page', 1, type=int)
    # 获取数据库中博客的数据,按时间排序(pagination是个对象)
    pagination = Posts.query.filter_by(rid=0).order_by(Posts.timestamp.desc()).paginate(page, per_page=5,
                                                                                        error_out=False)
    # 读取每页数据
    posts = pagination.items
    for post in posts:
        post.count = post.users.count()
    return render_template('main/index.html', form=form, pagination=pagination, posts=posts)
コード例 #8
0
def index():
    form = PostsForm()
    if form.validate_on_submit():
        # 判断是否登录
        if current_user.is_authenticated:
            u = current_user._get_current_object()
            # 根据表单提交的数据常见对象
            p = Posts(content=form.content.data, user=u)
            # 然后写入数据库
            db.session.add(p)
            return redirect(url_for('main.index'))
        else:
            flash('登录后才能发表博客')
            return redirect(url_for('user.login'))
    # 从数据库中读取博客,并分配到模板中,然后在模板中渲染
    # 安装发表时间,降序排列
    # 只获取发表的帖子,过滤回复的帖子
    #posts = Posts.query.filter_by(rid=0).order_by(Posts.timestamp.desc()).all()
    # 分页处理
    # 获取当前页码,没有认为是第一页
    page = request.args.get('page', 1, type=int)
    pagination = Posts.query.filter_by(rid=0).order_by(
        Posts.timestamp.desc()).paginate(page, per_page=1, error_out=False)
    posts = pagination.items
    return render_template('main/index.html',
                           form=form,
                           posts=posts,
                           pagination=pagination)
コード例 #9
0
def index():
    form = PostsForm()
    if form.validate_on_submit():
        # 判断用户是否是登录状态
        if current_user.is_authenticated:
            user = current_user._get_current_object()
            posts = Posts(content=form.content.data, user=user)
            db.session.add(posts)
            return redirect(url_for('main.index'))
        else:
            flash('登录后才能发表')
            return redirect(url_for('user.login'))
    # 分页读取数据,然后展示
    # 从请求的参数中获取当前页码,没有page参数默认为第一页
    page = request.args.get('page', 1, type=int)
    # paginate参数介绍
    # page:唯一的必须参数,表示当前的页码
    # per_page:可选参数,表示每页显示的记录数,默认20条
    # error_out:可选参数,页码超出范围时是否显示404错误,默认为True
    pagination = Posts.query.filter_by(rid=0).order_by(
        Posts.timestamp.desc()).paginate(page, per_page=5, error_out=False)
    # 获取当前页的记录
    posts = pagination.items
    return render_template('main/index.html',
                           form=form,
                           posts=posts,
                           pagination=pagination)
コード例 #10
0
def handlePosts(user_id):
    form = PostsForm()
    if request.method == "POST":
        if form.validate_on_submit():
            caption = form.caption.data
            photo = form.photo.data
            filename = photo.filename
            photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            post = Posts(user_id, filename, caption)

            try:

                db.session.add(post)
                db.session.commit()

                #Flash message for a successfully added post
                response = "A new post was added successfully"
                return jsonify(message=response), 201
            except Exception as e:
                print(e)

                response = "An error as occurred"
                return jsonify(error=response), 401

        response = form_errors(form)
        return jsonify(error=response)

    if request.method == "GET":
        if form.validate_on_submit():
            try:
                #Retrieve the user's posts
                posts = db.session.query(Posts).filter_by(
                    user_id=user_id).all()

                allPosts = []
                for post in posts:
                    post_detail = {
                        "id": post.id,
                        "user_id": post.user_id,
                        "photo": post.photo,
                        "caption": post.caption
                    }
                    allPosts.append(post_detail)

                return jsonify(posts=allPosts)
            except Exception as e:
                print(e)
                response = "An error has occurred"
                return jsonify(error=response), 401

        response = form_errors(form)
        return jsonify(error=response), 400

    #Flash message for errors
    response = "An error occurred trying to display posts"
    return jsonify(error=response), 401
コード例 #11
0
def userPosts(user_id):
    form = PostsForm()
    if request.method == "POST" and form.validate_on_submit() == True:
        try:
            caption = form.caption.data
            photo = assignPath(form.photo.data)
            post = Posts(photo, caption, user_id)
            db.session.add(post)
            db.session.commit()

            #Flash message to indicate a post was added successfully
            success = "Successfully created a new post"
            return jsonify(message=success), 201
        except Exception as e:
            print(e)

            error = "Internal server error"
            return jsonify(error=error), 401

    else:
        try:
            #Gets the current user to add/display posts to
            userPosts = db.session.query(Posts).filter_by(
                user_id=user_id).all()

            posts = []
            for post in userPosts:
                p = {
                    "id": post.id,
                    "user_id": post.user_id,
                    "photo": os.path.join(app.config['GET_FILE'], post.photo),
                    "description": post.caption,
                    "created_on": post.created_on.strftime("%d %b %Y")
                }
                posts.append(p)

            return jsonify(posts=posts)
        except Exception as e:
            print(e)

            error = "Internal server error"
            return jsonify(error=error), 401

    #Flash message to indicate an error occurred
    failure = "Failed to create/display posts"
    return jsonify(error=failure), 401
コード例 #12
0
ファイル: main.py プロジェクト: huangkun2214/mygit
def pzl():
    print('从数据库中加载')
    form = PostsForm()
    next = request.args.get('next')

    if next:
        form.content.data = next
    if form.validate_on_submit():
        # 判断用户是否登录
        if current_user.is_authenticated:
            suffix = os.path.splitext(form.pic.data.filename)[1]
            filename = random_string() + suffix
            # 保存文件print (form.pic.data)
            print(form.pic.data)
            photos.save(form.pic.data, name=filename)

            # 拼接完整的路径名
            pathname = os.path.join(current_app.config['UPLOADED_PHOTOS_DEST'],
                                    filename)
            # 生成缩略图
            img = Image.open(pathname)
            # 重新设置尺寸
            img.thumbnail((128, 128))
            # 重新保存
            img.save(pathname)

            p = Post(content=form.content.data,
                     category=form.category.data,
                     users_id=current_user.id,
                     pic=filename)
            db.session.add(p)
            form.content.data = ''
            flash('发布成功')
            return redirect(url_for('main.pzl'))
        else:
            flash('登录后才能发布微博哦')
            return redirect(url_for('users.login', next=form.content.data))
    # posts = Post.query.filter_by(rid=0).order_by(Post.timestamp.desc()).all()
    page = request.args.get('page', 1, type=int)
    pagination = Post.query.filter_by(rid=0).\
        order_by(Post.timestamp.desc()).paginate(page, per_page=3,error_out=False)
    posts = pagination.items
    return render_template('common/index.html',
                           form=form,
                           posts=posts,
                           pagination=pagination)
コード例 #13
0
def new_user_post():
    """Used for adding posts to the user's feed"""
    form = PostsForm()
    if request.method == "POST" and form.validate_on_submit():
        userid = user_id
        caption = request.form['caption']
        photo_posted = request.file['photo']
        date_now = datetime.datetime.now()
        photo_file = secure_filename(photo_posted.photo_file)
        post = Posts(userid=user_id,
                     caption=caption,
                     created_on=date_now,
                     photo_posted=photo)
        db.session.add(post)
        db.session.commit()
        photo_posted.save(os.path.join(filefolder, photo_file))
        info = [{"message": "Post successfully created"}]
        return jsonify(result=info)
コード例 #14
0
def index():
    form = PostsForm()
    if form.validate_on_submit():
        if current_user.is_authenticated:
            u = current_user._get_current_object()
            p = Posts(content=form.content.data, user=u)
            db.session.add(p)
            return redirect(url_for('main.index'))
        else:
            flash('登录后才能发表')
            return redirect('user.login')
    # posts = Posts.query.filter_by(rid=0).order_by(Posts.timestamp.desc()).all()
    page = request.args.get('page', 1, type=int)
    pagination = Posts.query.filter_by(rid=0).order_by(
        Posts.timestamp.desc()).paginate(page, per_page=3, error_out=False)
    posts = pagination.items
    return render_template('main/index.html',
                           form=form,
                           posts=posts,
                           pagination=pagination)
コード例 #15
0
ファイル: main.py プロジェクト: ginharu/mycode
def index():
    # 发布博客
    form = PostsForm()
    repform = RelyForm()
    if form.submit1.data and form.validate():
        # 判断是否登录
        if current_user.is_authenticated:
            # 创建帖子对象
            user = current_user._get_current_object()
            p = Posts(content=form.content.data, user=user)
            # 保存到数据库
            db.session.add(p)
            return redirect(url_for('main.index'))
        else:
            flash('登录后才能发表')
            return redirect(url_for('user.login'))
    # 读取帖子
    #posts = Posts.query.filter_by(rid=0).order_by(Posts.timestamp.desc()).all()
    # 发表回复
    if repform.submit2.data and repform.validate():
        if current_user.is_authenticated:
            postid = repform.hidden.data
            user = current_user._get_current_object()
            r = Replys(content = form.content.data,user=user)
            post= Posts.query.filter_by(id=postid).first()
            r.posts.append(post)
            db.session.add(r)
            return redirect(url_for('main.index'))
        else:
            flash('登录后才能发表')
            return redirect(url_for('user.login'))
    # 读取分页数据
    # 获取页码
    page = request.args.get('page', 1, type=int)
    pagination = Posts.query.filter_by(rid=0).order_by(Posts.timestamp.desc()).paginate(page, per_page=5, error_out=False)
    posts = pagination.items

    replys = Replys.query.all()

    return render_template('main/index.html', form=form, posts=posts, pagination=pagination,repform=repform,replys=replys)
コード例 #16
0
ファイル: posts.py プロジェクト: 2339379789/zhang_blog
def blogs():
    form = PostsForm()
    if form.validate_on_submit():
        u = current_user._get_current_object()
        p = Posts(content=form.content.data, user=u)
        db.session.add(p)
        flash('你的博客已经发表成功,点击继续发表可继续发表,点击返回可返回首页')
        return redirect(url_for('posts.blogs_continue'))
    # 读取分页数据 'page':当前页码,默认第一页
    page = request.args.get('page', 1, type=int)
    # 只保留我发表的博客,然后按照时间倒序排列
    pagination = Posts.query.filter_by(rid=0).filter_by(
        uid=current_user.id).order_by(Posts.timestamp.desc()).paginate(
            page, per_page=5, error_out=False)
    # 获取当前分页所有数据
    posts = pagination.items
    for p in posts:
        p.count = Posts.query.filter_by(rid=p.id).count()
    return render_template('posts/blogs.html',
                           form=form,
                           posts=posts,
                           pagination=pagination)
コード例 #17
0
def send_posts():
    form = PostsForm()
    #对发表帖子的用户进行验证
    if form.validate_on_submit():
        # print('11')
        if current_user.is_authenticated:
            u = current_user._get_current_object()
            p = Posts(content=form.content.data,user=u)
            db.session.add(p)
            flash('帖子发表成功')
            return redirect(url_for('main.index'))
        else:
            flash('您还没有登录,请登录之后在发表')
            return redirect(url_for('user.login'))
    return render_template('posts/send_posts.html',form=form)
コード例 #18
0
def add(post_id=None):
    """

    :param post_id:
    :return:
    """
    posts_form = PostsForm()
    if posts_form.is_submitted():
        if not posts_form.validate():
            return jsonify(models.BaseResult(1, str(posts_form.errors)))
        utils.verify_code((posts_form.verify_code.data))
        user = current_user.user
        if not user.get('is_active', False) or user.get('is_disabled', False):
            return jsonify(code_msg.USER_NOT_ACTIVE_OR_DISABLED)

        user_coin = user.get('coin', 0)
        if posts_form.reward.data > user_coin:
            return jsonify(
                models.Response.ok('悬赏金币不能大于拥有的金币,当前帐号的金币为:' + str(user_coin)))
        posts = {
            'title': posts_form.title.data,
            'catalog_id': ObjectId(posts_form.catalog_id.data),
            'is_closed': False,
            'content': posts_form.content.data,
        }
        post_index = posts.copy()
        post_index['catalog_id'] = str(posts['catalog_id'])
        msg = '发帖成功'
        reward = posts_form.reward.data
        if post_id:
            posts['modify_time'] = datetime.now()
            mongo.db.posts.update_one({'_id': post_id}, {'$set': posts})
            msg = '修改成功!'
        else:
            posts['create_time'] = datetime.utcnow()
            posts['reward'] = reward
            posts['user_id'] = user['_id']
            # 扣除用户发帖悬赏
            if reward > 0:
                mongo.db.users.update_one({'_id': user['_id']},
                                          {'$inc': {
                                              'coin': -reward
                                          }})
            mongo.db.posts.save(posts)
            post_id = posts['_id']
        # 更新索引文档
        update_index(mongo.db.posts.find_one_or_404({'_id': post_id}))
        return jsonify(
            models.Response.ok(msg).put('action', url_for('index.index')))
    else:
        verify_code = utils.generate_verify_code()
        session['verify_code'] = verify_code['answer']
        posts = None
        if post_id:
            posts = mongo.db.posts.find_one_or_404({'_id': post_id})
        title = "发帖" if post_id is None else "编辑帖子"
        return render_template('jie/add.html',
                               page_name='jie',
                               verify_code=verify_code['question'],
                               form=posts_form,
                               is_add=post_id is None,
                               post=posts,
                               title=title)