def index(): flask_whooshalchemyplus.index_one_model(Post) form = PostForm() page = request.args.get('page', 1, type=int) if form.validate_on_submit() and current_user.can(Permission.WRITE_ARTICLES): tag = Tag.query.filter_by(name=form.tag.data.strip()).first_or_404() if tag == None: tag = Tag(name=form.tag.data.strip()) db.session.add(tag) # current_user._get_current_object().tags = [tag] post = Post(body = form.body.data, title=form.title.data, tags = [tag], author = current_user._get_current_object()) db.session.add(post) db.session.commit() return redirect(url_for('.index')) show_followed = False if current_user.is_authenticated: show_followed = bool(request.cookies.get('show_followed', '')) if show_followed: query = current_user.followed_posts else: query = Post.query pagination = query.order_by(Post.timestamp.desc()).paginate( page, per_page=current_app.config['POSTS_PER_PAGE'], error_out=False ) posts = pagination.items return render_template('index.html', form=form, posts = posts, show_followed=show_followed, pagination=pagination)
def write_page(): """ save to mysql 文章表单保存到mysql """ form = WriteForm() if request.method == "GET": return render_template('user/write.html', form=form) if request.method == "POST": page_id = get_page_id() if form.title.data != "" or form.body.data != "": content_temp = form.body.data r = 'src="(.+?.(?:bmp|jpg|png|gif))"' # 正则表达式,获取第一张图片路径 temp = "" if not re.findall(r, content_temp) else re.findall( r, content_temp)[0] keyword = ','.join( get_page_key(content_temp)) # 转化str list Mysql not save page = PageInfo(title=form.title.data, content=form.body.data, content_see=0, content_good=0, is_public=False, user_id=current_user.id, content_img=temp, page_id=page_id) db.session.add(page), db.session.commit() flask_whooshalchemyplus.index_one_model(PageInfo) # 增加文章就加入索引index key = PageKeyWord(title=form.title.data, content_keyword=keyword, page_id=page_id) db.session.add(key), db.session.commit() return redirect( url_for('auth.user_manage', user=current_user.username)) else: return render_template('user/write.html', msg="文章或标题不能为空")
def index(): """主页:显示所有帖子""" context = { 'community_context': Community.query.order_by('-create_time').all() } flask_whooshalchemyplus.index_one_model(Community) return render_template('index.html', **context)
def submit(): user_name = request.form.get('user_name') user_depart = request.form.get('user_depart') reason = request.form.get('reason') start_hour = request.form.get('start_hour') end_hour = request.form.get('end_hour') select_week = request.form.get('select_week', '0') office = request.form.get('office').strip() office_model = OfficeModel.query.filter(OfficeModel.desc == office).first() if not office_model: return '未能查到办公室' + '"' + office + '"' new_order = OrderModel(user_name=user_name, depart_name=user_depart, reason=reason, order_from=start_hour, order_to=end_hour, office_id=office_model.id) new_order.order_day = time_offset(select_week) db.session.add(new_order) db.session.commit() flask_whooshalchemyplus.index_one_model(OrderModel) return ''
def new_post(): form = PostForm() if form.validate_on_submit(): post = Post(title=form.title.data, content=form.content.data, author=current_user) #tag = [] #for tag in form.tags.data.split(','): #if tag: print '*' * 40, post.tags tag_str_list = form.tags.data.split(',') for tag_str in tag_str_list: tag = Tag.query.filter_by(name=tag_str).first() if not tag: # new post tag tag = Tag(name=tag_str) db.session.add(tag) post.tags.append(tag) category = Category.query.filter_by(name=form.category.data).first() if not category: category = Category(name=form.category.data) db.session.add(category) post.category = category db.session.add(post) db.session.commit() #with app.app_context(): flask_whooshalchemyplus.index_one_model(Post) flash('新的文章已提交') return redirect(url_for('.post', id=post.id)) return render_template('edit_post.html', post_commit_button=True, form=form)
def blog_create(): if request.method == 'GET': return render_template('blog/blog_create.html') elif request.method == 'POST': title_name = request.form.get('title') markdown_str = request.form.get('text') classify_id = request.form.get('classify_id') classify = db.session.query(Classify).filter(Classify.id == classify_id).first() tags = request.form.get('tag').split() temp_article = Article() if tags: for tag in tags: cur_tag = db.session.query(Tag).filter(Tag.tag_name == tag).first() if cur_tag: temp_article.tag.append(cur_tag) else: new_tag = Tag() new_tag.tag_name = tag temp_article.tag.append(new_tag) temp_article.author = 'liuzhiyu' temp_article.content = markdown_str if classify is not None: temp_article.classify_id = classify_id else: pass temp_article.title = title_name db.session.add(temp_article) db.session.commit() flask_whooshalchemyplus.index_one_model(Article) return jsonify({'status': 'success'})
def index(): """ 设置一个key_prefix来作为标记,然后,在内容更新的函数里面调用cache.delete('index')来删除缓存来保证用户访问到的内容是最新的 新文章对象的 author 属性值为表达式 current_user._get_current_object() 。变量current_user 由 Flask-Login 提供, 和所有上下文变量一样,也是通过线程内的代理对象实现。这个对象的表现类似用户对象,但实际上却是一个轻度包装,包含真正的用户对象。 数据库需要真正的用户对象,因此要调用 _get_current_object() 方法。 渲染的页数从请求的查询字符串( request.args )中获取如果没有明确指定则默认渲染第一页参数 type=int 保证参数无法转换成整数时,返回默认值。 为了显示某页中的记录,要把 all() 换成 Flask-SQLAlchemy 提供的 paginate() 方法。页数是 paginate() 方法的第一个参数 也是唯一必需的参数。可选参数 per_page 用来指定每页显示的记录数量;如果没有指定,则默认显示 20 个记录。另一个可选参数为 error_out 当其设为 True 时(默认值),如果请求的页数超出了范围,则会返回 404 错误;如果设为 False ,页数超出范围时会返回一个空列表。 为了能够很便利地配置每页显示的记录数量,参数 per_page 的值从程序的环境变量 FLASKY_POSTS_PER_PAGE 中读取。这样修改之后, 首页中的文章列表只会显示有限数量的文章。若想查看第 2 页中的文章,要在浏览器地址栏中的 URL 后加上查询字符串 ?page=2。 :return: """ page = request.args.get('page', 1, type=int) show_followed = False query = Post.query if current_user.is_authenticated: show_followed = bool(request.cookies.get('show_followed', '')) if show_followed: query = current_user.followed_posts pagination = query.outerjoin(Post.answers).order_by( Post.timestamp.desc()).paginate( page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False) posts = pagination.items flask_whooshalchemyplus.index_one_model(Post) return render_template('index4.html', posts=posts, show_followed=show_followed, pagination=pagination)
def new_post(): post = Post.from_json(request.json) post.author = g.current_user db.session.add(post) db.session.commit() index_one_model(Post) return jsonify(post.to_json()), 201, { 'Location': url_for('api.get_post', id=post.id) }
def edit(id): post = Post.query.get_or_404(id) if current_user != post.author and not current_user.can(Permission.ADMIN): abort(403) form = PostEditForm() # 处理文章头图 if request.method == 'POST' and 'image' in request.files: try: filename = post_img.save(request.files['image']) except UploadNotAllowed: pass else: # 如果文章已经有头图了,就删除原先头图文件 if post.image is not None: post_img_path = os.path.join( basedir, 'app', post.image[1:]) # 第一个字符‘/’会使得join 不能正确拼接路径,需要去掉 if os.path.exists(post_img_path): os.remove(post_img_path) post.image = url_for("static", filename='img/upload/post_img/' + filename) # 处理二级表单 if request.method == 'POST' and not form.submit.data: data = request.get_json() name = data['name'] category = Category.query.filter_by(name=name).first() sub_categories = { category.id: category.name for category in Category.query.filter_by( parent_id=category.id).all() } return jsonify(sub_categories) if form.validate_on_submit(): post.title = form.title.data # 如果没有输入一级分类,就设置成默认分类(未分类) if not form.category.data: post.category = Category.query.filter_by(default=True).first() # 如果输入了一级分类和二级分类,就设置成二级分类 elif form.sub_category.data: post.category = Category.query.get(form.sub_category.data) # 如果只输入了一级分类, 就设置成一级分类 else: post.category = Category.query.get(form.category.data) post.summary = form.summary.data post.body = form.body.data db.session.add(post) db.session.commit() flask_whooshalchemyplus.index_one_model(Post) # 修改文章后 创建搜索索引 flash('博客已修改成功') return redirect(url_for('.post', id=post.id)) form.title.data = post.title form.category.data = post.category_id form.summary.data = post.summary form.body.data = post.body return render_template("blog/edit_post.html", form=form, post=post)
def question(): if request.method == 'GET': user_id = session.get('user_id') user = User.query.filter(User.id == user_id).first() return render_template('question.html', user=user) else: title = request.form.get('title') content = request.form.get('content') type = request.form.get('type') # if type: # return type # else: # return u'no type' if type == '1': kind = 1 elif type == '2': kind = 2 elif type == '3': kind = 3 elif type == '4': kind = 4 elif type == '5': kind = 5 elif type == '6': kind = 6 elif type == '7': kind = 7 else: kind = 8 question = Question(title=title, content=content, report_reasons_and_times='A@0|B@0|C@0|D@0', report_total=0, type=kind) user_id = session.get('user_id') user = User.query.filter(User.id == user_id).first() user.number_of_post = user.number_of_post + 1 user.point = user.point + 20 if user.point >= 50 and user.point < 100: user.grade = 2 elif user.point >= 100 and user.point < 200: user.grade = 3 elif user.point >= 200 and user.point < 500: user.grade = 4 else: user.grade = 5 question.author = user # question.author_id = user_id flask_whooshalchemyplus.index_one_model(Question) db.session.add(question) db.session.commit() return redirect(url_for('index'))
def edit_post(id): post = Post.query.get_or_404(id) if current_user != post.author and not current_user.can(Permission.ADMIN): abort(403) form = PostForm() if form.validate_on_submit(): post.title = form.title.data #old_tags = post.tags remove_tags = [] tag_str_list = form.tags.data.split(',') for tag in post.tags: if tag.name not in tag_str_list: post.tags.remove(tag) remove_tags.append(tag) for tag_str in tag_str_list: tag = Tag.query.filter_by(name=tag_str).first() if not tag: # new post tag tag = Tag(name=tag_str) db.session.add(tag) if not tag in post.tags: post.tags.append(tag) for tag in remove_tags: if tag.posts.count() == 0: print 'delete tag: %s because there is not any post use this tag' % tag.name db.session.delete(tag) if form.category.data != post.category.name: old_category = post.category category = Category.query.filter_by( name=form.category.data).first() if not category: category = Category(name=form.category.data) db.session.add(category) post.category = category #print old_category.name, old_category.posts.count() if old_category.posts.count() == 0: print 'delete category: %s because there is not any post in this category' % old_category.name db.session.delete(old_category) #post.tags.data = form.tags.data post.content = form.content.data db.session.add(post) db.session.commit() flask_whooshalchemyplus.index_one_model(Post) flash('文章修改成功') return redirect(url_for('.post', id=id)) form.title.data = post.title form.tags.data = ','.join(tag.name for tag in post.tags) form.category.data = post.category.name form.content.data = post.content return render_template('edit_post.html', post_id=id, post_commit_button=True, form=form)
def index(): print("index called") # for i in (Post.query.outerjoin(Post.answers).order_by(Post.timestamp.desc()).order_by(Answer.agreements_num.asc()).all()): # for a in i.answers: # print(a.body) # # form = PostForm() # page = request.args.get('page', 1, type=int) # pagination = Post.query.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config['FLASK_POSTS_PER_PAGE'],error_out=False) # posts = pagination.items # return render_template('index.html', form=form, posts=posts,pagination=pagination) # form = PostForm() # if current_user.can(Permission.WRITE_ARTICLES) and \ # form.validate_on_submit(): # post = Post(body=form.body.data,author=current_user._get_current_object()) # db.session.add(post) # return redirect(url_for('.index')) # posts = Post.query.order_by(Post.timestamp.desc()).all() # return render_template('index.html', form=form, posts=posts) form = PostForm() if current_user.can(Permission.WRITE_ARTICLES) and \ form.validate_on_submit(): #新文章对象的 author 属性值为表达式 current_user._get_current_object() 。变量current_user 由 Flask-Login 提供,和所有上下文变量一样,也是通过线程内的代理对象实现。这个对象的表现类似用户对象,但实际上却是一个轻度包装,包含真正的用户对象。数据库需要真正的用户对象,因此要调用 _get_current_object() 方法。 post = Post(body=form.body.data, author=current_user._get_current_object()) db.session.add(post) return redirect(url_for('.index')) #渲染的页数从请求的查询字符串( request.args )中获取,如果没有明确指定,则默认渲染第一页。参数 type=int 保证参数无法转换成整数时,返回默认值。 page = request.args.get('page', 1, type=int) show_followed = False if current_user.is_authenticated: show_followed = bool(request.cookies.get('show_followed', '')) if show_followed: query = current_user.followed_posts else: query = Post.query #为了显示某页中的记录,要把 all() 换成 Flask-SQLAlchemy 提供的 paginate() 方法。页数是 paginate() 方法的第一个参数,也是唯一必需的参数。可选参数 per_page 用来指定每页显示的记录数量;如果没有指定,则默认显示 20 个记录。另一个可选参数为 error_out ,当其设为 True 时(默认值),如果请求的页数超出了范围,则会返回 404 错误;如果设为 False ,页数超出范围时会返回一个空列表。为了能够很便利地配置每页显示的记录数量,参数 per_page 的值从程序的环境变量 FLASKY_POSTS_PER_PAGE 中读取。这样修改之后,首页中的文章列表只会显示有限数量的文章。若想查看第 2 页中的文章,要在浏览器地址栏中的 URL 后加上查询字符串 ?page=2。 pagination = query.outerjoin(Post.answers).order_by( Post.timestamp.desc()).paginate( page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False) posts = pagination.items import flask_whooshalchemyplus flask_whooshalchemyplus.index_one_model(Post) return render_template('index4.html', form=form, posts=posts, show_followed=show_followed, pagination=pagination)
def addarea(): form = AddAreaForm(request.form) if form.validate(): name = form.name.data area = Area(name=name) db.session.add(area) import flask_whooshalchemyplus flask_whooshalchemyplus.index_one_model(Area) db.session.commit() return restful.success() else: return restful.args_error(form.get_error())
def new_post(): if not current_user.can(Permission.ADMIN): abort(403) post = Post() form = PostForm() # 处理文章头图 if request.method == 'POST' and 'image' in request.files: try: filename = post_img.save(request.files['image']) except UploadNotAllowed: pass else: post.image = url_for("static", filename='img/upload/post_img/' + filename) # 处理二级表单 if request.method == 'POST' and not form.submit.data: data = request.get_json() name = data['name'] category = Category.query.filter_by(name=name).first() sub_categories = { category.id: category.name for category in Category.query.filter_by( parent_id=category.id).all() } return jsonify(sub_categories) if form.validate_on_submit(): post.author_id = current_user.id post.title = form.title.data # 如果没有输入一级分类,就设置成默认分类(未分类) if not form.category.data: post.category = Category.query.filter_by(default=True).first() # 如果输入了一级分类和二级分类,就设置成二级分类 elif form.sub_category.data: post.category = Category.query.get(form.sub_category.data) # 如果只输入了一级分类, 就设置成一级分类 else: post.category = Category.query.get(form.category.data) post.summary = form.summary.data post.body = form.body.data db.session.add(post) db.session.commit() flask_whooshalchemyplus.index_one_model(Post) # 提交文章后 创建搜索索引 flash('博客发表') return redirect(url_for('.post', id=post.id)) return render_template("blog/new_post.html", form=form)
def post(self): form = RegisterForm(request.form) if form.validate(): telephone = form.telephone.data username = form.username.data password = form.password1.data # 检验用户名 usertest = FrontUser.query.filter_by(username=username).first() if usertest: return restful.args_error(message="该用户名已被占用!") user = FrontUser(telephone = telephone, username = username, password = password) db.session.add(user) db.session.commit() import flask_whooshalchemyplus flask_whooshalchemyplus.index_one_model(FrontUser) return restful.success() else: return restful.args_error(message = form.get_error())
def edit_post(id): post = Post.query.get_or_404(id) if g.current_user != post.author and not g.current_user.can( Permission.ADMIN): return forbidden('Insufficient permission') post.title = request.json.get('title', post.title) post.summary = request.json.get('summary', post.summary) post.body = request.json.get('body', post.body) category = Category.query.filter_by( name=request.json.get('category')).first() # 如果没有设置分类,则设置为默认分类 if category is None: category_id = Category.query.filter_by(default=True).first().id else: category_id = Category.query.filter_by( name=request.json.get('category')).first().id post.category_id = category_id db.session.add(post) db.session.commit() index_one_model(Post) return jsonify(post.to_json())
def post(self): form = PostForm(request.form) if form.validate(): theme = form.theme.data content = form.content.data area_id = form.area_id.data # 根据版块id找到对应的版块 area = Area.query.filter_by(id = area_id).first() if not area: return restful.args_error("请输入已存在的版块!") if g.front_user.locked: return restful.args_error("此账号已被封禁,若误封请联系管理员邮箱[email protected]") post = Post(theme = theme, content = content) area.number = area.number + 1 post.area = area post.author = g.front_user db.session.add(post) import flask_whooshalchemyplus flask_whooshalchemyplus.index_one_model(Post) db.session.commit() return restful.success() else: return restful.args_error(message = form.get_error())
def index(): g.tags = Tag.query.all() page = request.args.get('page', 1, type=int) show_followed = False if current_user.is_authenticated: show_followed = bool(request.cookies.get('show_followed', '')) if show_followed: query = current_user.followed_posts else: query = Post.query # 为了显示某页中的记录,要把 all() 换成 Flask-SQLAlchemy 提供的 paginate() 方法。页数是 paginate() 方法的第一个参数,也是唯一必需的参数。可选参数 per_page 用来指定每页显示的记录数量;如果没有指定,则默认显示 20 个记录。另一个可选参数为 error_out ,当其设为 True 时(默认值),如果请求的页数超出了范围,则会返回 404 错误;如果设为 False ,页数超出范围时会返回一个空列表。为了能够很便利地配置每页显示的记录数量,参数 per_page 的值从程序的环境变量 FLASKY_POSTS_PER_PAGE 中读取。这样修改之后,首页中的文章列表只会显示有限数量的文章。若想查看第 2 页中的文章,要在浏览器地址栏中的 URL 后加上查询字符串 ?page=2。 pagination = query.order_by(Post.timestamp.desc()).paginate( page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False) posts = pagination.items import flask_whooshalchemyplus flask_whooshalchemyplus.index_one_model(Post) return render_template('index.html', posts=posts, show_followed=show_followed, pagination=pagination)
def search_results(query): flask_whooshalchemyplus.index_one_model(News) results = News.query.whoosh_search(query).all() return render_template('search/search.html', query=query, results=results)