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)
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)