def add_comment(slug): if request.method == 'POST': content = request.json['content'] # id of parent comment parent_id = request.json['parent_id'] if parent_id: comment = Comment(content_html=content, author=current_user._get_current_object(), parent=Comment.query.get(parent_id), post=Post.query.filter_by(slug=slug).first()) else: comment = Comment(content_html=content, author=current_user._get_current_object(), post=Post.query.filter_by(slug=slug).first()) db.session.add(comment) db.session.commit() if parent_id: receive_id = Comment.query.get(parent_id).author.id else: receive_id = Post.query.filter_by(slug=slug).first().author.id notify = Notification(sender_id=current_user.id, receive_id=receive_id, target=comment.id, target_type='comment', action='comment') db.session.add(notify) return jsonify(comment_id=comment.id, timestamp=comment.date_created)
def ajax(target_attr, target, link, page, per_page, template_pagination, last_viewed_comment=None, extra_data=None): if not target.bl.has_comments_access(current_user._get_current_object()): abort(403) maxdepth = None if request.args.get('fulltree') == '1' else calc_maxdepth(current_user) comments_count, paged, comments_tree_list = target.bl.paginate_comments(page, per_page, maxdepth, last_viewed_comment=last_viewed_comment) if not comments_tree_list and paged.number != 1: abort(404) comment_ids = [x[0].id for x in comments_tree_list] if current_user.is_authenticated: comment_votes_cache = target.bl.select_comment_votes(current_user._get_current_object(), comment_ids) else: comment_votes_cache = {i: 0 for i in comment_ids} data = dict(extra_data or {}) data.update({ target_attr: target, 'comments_tree_list': comments_tree_list, 'last_viewed_comment': last_viewed_comment, 'page_obj': paged, 'comment_votes_cache': comment_votes_cache, }) return jsonify({ 'success': True, 'link': link, 'comments_count': comments_count, 'comments_tree': render_template('includes/comments_tree.html', **data), 'pagination': render_template(template_pagination, **data), })
def change_email_request(): '''auth.change_email_request()''' form = ChangeEmailForm() if form.validate_on_submit(): if current_user.verify_password(form.password.data): new_email = form.email.data.strip().lower() token = current_user.generate_email_change_token(new_email) send_email( recipient=new_email, subject='确认您的邮箱账户', template='auth/mail/change_email', user=current_user._get_current_object(), token=token ) flash('一封确认邮件已经发送至您的邮箱', category='info') add_user_log( user=current_user._get_current_object(), event='请求修改邮箱为:{}'.format(new_email), category='auth' ) return redirect(url_for('auth.change_email_request')) flash('无效的用户名或密码', category='error') return redirect(url_for('auth.change_email_request')) return minify(render_template( 'auth/change_email.html', form=form ))
def show(target_attr, comment): # В эту вьюху направляет ссылка из метода get_permalink user = current_user._get_current_object() target = getattr(comment, target_attr) if not comment.bl.has_comments_access(target, user): abort(403) return redirect(comment.bl.get_paged_link(current_user._get_current_object()))
def mind(): form = Postform() page = request.args.get('page', 1, type=int) pagination = Post.query.filter_by(author=current_user._get_current_object()).order_by(Post.timestamp.desc()).paginate(page, per_page=5, error_out=True) posts = pagination.items if current_user.scan(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('main.mind')) return render_template('main/mind.html', form=form, posts=posts, pagination=pagination)
def ajax_tree(target_attr, comment, target=None, last_viewed_comment=None, extra_data=None): if not target: target = getattr(comment, target_attr) if not target.bl.has_comments_access(current_user._get_current_object()): abort(403) # Проще получить все комментарии и потом выбрать оттуда нужные comments_tree_list = target.bl.get_comments_tree_list( maxdepth=None, root_id=comment.root_id, last_viewed_comment=last_viewed_comment, ) # Ищем начало нужной ветки start = None for i, x in enumerate(comments_tree_list): if x[0].local_id == comment.local_id: start = i break if start is None: abort(404) tree = None # Ищем конец ветки for i, x in enumerate(comments_tree_list[start + 1:], start + 1): if x[0].tree_depth == comment.tree_depth + 1: assert x[0].parent.id == comment.id # debug if x[0].tree_depth <= comment.tree_depth: tree = comments_tree_list[start + 1:i] break # Если ветка оказалось концом комментариев if tree is None: tree = comments_tree_list[start + 1:] comment_ids = [x[0].id for x in tree] if current_user.is_authenticated: comment_votes_cache = target.bl.select_comment_votes(current_user._get_current_object(), comment_ids) else: comment_votes_cache = {i: 0 for i in comment_ids} data = dict(extra_data or {}) data.update({ target_attr: target, 'comments_tree_list': tree, 'last_viewed_comment': last_viewed_comment, 'comment_votes_cache': comment_votes_cache, }) return jsonify({ 'success': True, 'tree_for': comment.local_id, 'comments_tree': render_template('includes/comments_tree.html', **data), })
def question(id): form = AnswerForm() question = Post.query.get_or_404(id) if question.title is None: abort(404) if form.validate_on_submit(): post = Post(body=form.content.data,author=current_user._get_current_object()) db.session.add(post) db.session.commit() post.add_to_question(question) Timeline.push_to_follower(action=ACTION.ANSWER,user=current_user._get_current_object(),post=post) return redirect(url_for('.question',id=id)) return render_template('question.html',question=question,form=form)
def request_loan(): if not current_user.is_borrower: abort(403) elif not current_user.is_approved: abort(404) elif current_user.is_owing: flash('You cannot request a new loan if your still due!') return redirect(url_for('loans.view')) elif current_user.has_requested_loan: flash('You cannot request a new loan if your last loan hasnt been approved!') return redirect(url_for('loans.view')) else: form = LoanApplicationForm() if form.validate_on_submit(): loan = Loan(loan_amt=form.loan_amt.data, user=current_user._get_current_object()) if loan.loan_amt > loan.user.max_credit_amt: flash('You can only borrow to a maximum of %s' % loan.user.max_credit_amt) return redirect(url_for('loans.request_loan')) loans.is_requested = True loan.user.has_requested_loan = True db.session.add(loan) db.session.commit() flash( 'Success.Your Loan Application has been submitted.View it below.') return redirect(url_for('loans.view')) return render_template('loans/request_loan.html', form=form, title="New Loan")
def show(story_id, local_id): local = get_local_thread(story_id, current_user._get_current_object()) comment = StoryLocalComment.get(local=local, local_id=local_id) if not comment or (comment.deleted and not current_user.is_staff): abort(404) return common_comment.show('local', comment)
def index(): """ 首页 :return: 首页模版 """ 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或者关注用户的posts show_followed = False if current_user.is_authenticated: show_followed = bool(request.cookies.get('show_followed', '')) # show-followed以字典形式存储在cookies中 if show_followed: query = current_user.followed_posts else: query = Post.query page = request.args.get('page', 1, type=int) pagination = query.order_by(Post.timestamp.desc()).paginate( page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False) posts = pagination.items return render_template('index.html', posts=posts, form=form, show_followed=show_followed, pagination=pagination, current_time=datetime.utcnow(), user_agent=request.headers.get('User-Agent'))
def write(): write_article_form = WriteArticleForm(prefix='write') if write_article_form.validate_on_submit(): # --------以下功能是增加文章的分类 cty = Category.query.filter_by(name=write_article_form.category.data.strip()).first() if not cty and write_article_form.category.data.strip() != '': cty = Category(name=write_article_form.category.data.strip()) db.session.add(cty) # --------增文章分类------结束 # --------以下功能是将文章信息插入数据库 a = Article(title=write_article_form.title.data.strip(), body=write_article_form.body.data, cty=cty, author=current_user._get_current_object()) db.session.add(a) # --------以下功能是 Markdown 转换 html a.markdown_to_html(write_article_form.body.data) # -------- Markdown 转换 html ----结束 # --------以下功能是将文章标识插入数据库 for tg in tag_split(tags=write_article_form.tags.data): t = Tag.query.filter_by(name=tg.strip()).first() if not t: t = Tag(name=tg.strip()) db.session.add(t) a.tag(tag=t) # --------将文章标识插入数据库---结束 return redirect(url_for('admin.article_settings')) directory = Finder(path=current_app.config['IMAGES_FOLDER']) return render_template('admin/write.html', writeArticleForm=write_article_form, directory=directory)
def post(id): """ 文章固定链接,用于分享 :param id: :return: """ post = Post.query.get_or_404(id) # 获取路径中id的post文章 form = CommentForm() # 评论表单 if form.validate_on_submit(): # 如果评论表单中输入了评论可以提交 comment = Comment(body=form.body.data, post=post, author=current_user._get_current_object()) # 真的的User对象 db.session.add(comment) flash('评论已发布') return redirect(url_for('.post', id=post.id, page=-1)) # 重新回到此路由,并刷新评论 page = request.args.get('page', 1, type=int) if page == -1: # 当page是-1时 计算评论的总量和总页数,得到真正要显示的页数 page = (post.comments.count() - 1) // current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1 pagination = post.comments.order_by(Comment.timestamp.asc()).paginate( # 设置评论分页数据 page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'], error_out=False) comments = pagination.items return render_template('post.html', posts=[post], form=form, comments=comments, pagination=pagination)
def index(): 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')) show_followed = False User.is_authenticated 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 # 分页处理 page = request.args.get('page', 1, type=int) pagination = query.order_by(Post.timestamp.desc()).paginate( page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False) posts= pagination.items cfgtag=current_app.config['SQLALCHEMY_DATABASE_URI'] return render_template('index.html', form=form, posts=posts, show_followed=show_followed, pagination=pagination, cfgtag=cfgtag)
def update(pk): category = Category.get(id=pk) if not category: abort(404) form = CategoryForm(data={ 'name': category.name, 'description': category.description, 'color': category.color, }) saved = False if form.validate_on_submit(): try: category.bl.update(current_user._get_current_object(), form.data) except ValidationError as exc: form.set_errors(exc.errors) else: saved = True return render_template( 'admin/categories/work.html', page_title=category.name, category=category, form=form, edit=True, saved=saved, )
def index(): form = PostForm() if form.validate_on_submit(): 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('main.index')) 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 pagination = query.order_by(Post.timestamp.desc()).paginate(page, per_page=current_app.config['POSTS_PER_PAGE'], error_out=False) posts = pagination.items res = { 'form': form, 'pagination': pagination, 'posts': posts, 'show_followed': show_followed, } return render_template('index.html', **res)
def index(): """ :summary: 首页,包含一个发表post的表单 :return: """ form = PostForm() if form.validate_on_submit(): post = Post( body=form.body.data, author=current_user._get_current_object() ) db.session.add(post) db.session.commit() # 创建一个文件夹来存储文章对应的图片 os.system('mkdir %s/app/static/img/posts/%s' % (basedir, post.id)) return redirect(url_for('main.index')) # 为了显示某页中的记录, 要把 all() 换成 Flask-SQLAlchemy 提供的 paginate() 方法。 # 页数是 paginate() 方法的第一个参数,也是唯一必需的参数。可选参数 per_page 用来指定每页显示的记录数量; # 如果没有指定,则默认显示 20 个记录。 # 另一个可选参数为 error_out,当其设为 True 时(默认值),如果请求的页数超出了范围,则会返回 404 错误; # 如果设为 False,页数超出范围时会返回一个空列表。 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 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('main/index.html', form=form, posts=posts, show_followed=show_followed, pagination=pagination)
def add_question(): """添加新问题并推送主页动态 """ form = AddQuestionForm() if form.validate_on_submit(): user = current_user._get_current_object() prev_question = Question.query.order_by(Question.id.desc()).first() if prev_question is None: question = Question(user=user, title=form.title.data, content=form.content.data) db.session.add(question) db.session.commit() else: id_plus = randint(1, 4) question_id = prev_question.id + id_plus question = Question(id=question_id, user=user, title=form.title.data, content=form.content.data) db.session.add(question) db.session.commit() user.follow_question(question) feed = Feed(user_id=user.id, action='ask_question', question_id=question.id) db.session.add(feed) return redirect(url_for('main.question_page', id=question.id))
def check_user_status(question, answers): """确认当前用户与问题及回答的关系 @question, 当前浏览的问题 @answers, 该问题下已有的所有回答 @status['follow'], 是否已关注当前问题 @status[answer_id], 赞同/反对/两者都不 某个回答 """ status = {} user = current_user._get_current_object() if current_user.is_active: f = user.user_on_question.filter_by(question_id=question.id).first() if f is None: status['follow'] = False elif not f.follow: status['follow'] = False else: status['follow'] = True for answer in answers: u_on_a = UserOnAnswer.query.filter(db.and_( UserOnAnswer.user_id == user.id, UserOnAnswer.answer_id == answer.id)).first() if u_on_a is None: status[answer.id] = 0 elif u_on_a.vote == 1: status[answer.id] = 1 elif u_on_a.vote == -1: status[answer.id] = -1 else: status[answer.id] = 0 return (status, user)
def post(id): post = Post.query.get_or_404(id) form = CommentForm() if form.validate_on_submit(): comment = Comment( body=form.body.data, post=post, author=current_user._get_current_object() ) db.session.add(comment) flash('Your comment has been published.') return redirect(url_for('main.post', id=post.id, page=-1)) page = request.args.get('page', 1, type=int) if page == -1: page = (post.comments.count() - 1) // \ current_app.config['APP_COMMENTS_PER_PAGE'] + 1 pagination = post.comments.order_by(Comment.timestamp.asc()).paginate( page, per_page=current_app.config['APP_COMMENTS_PER_PAGE'], error_out=False ) comments = pagination.items return render_template( 'post.html', posts=[post], form=form, comments=comments, pagination=pagination, )
def view(story_id, comments_page): user = current_user._get_current_object() local = get_local_thread(story_id, user) story = local.story per_page = user.comments_per_page or current_app.config['COMMENTS_COUNT']['page'] maxdepth = None if request.args.get('fulltree') == '1' else calc_maxdepth(user) last_viewed_comment = story.bl.last_viewed_local_comment_by(user) comments_count, paged, comments_tree_list = local.bl.paginate_comments(comments_page, per_page, maxdepth, last_viewed_comment=last_viewed_comment) if not comments_tree_list and paged.number != 1: abort(404) if comments_page < 0 or comments_page == paged.num_pages: story.bl.viewed_localcomments(user) data = { 'story': story, 'local': local, 'comments_tree_list': comments_tree_list, 'comments_count': comments_count, 'last_viewed_comment': last_viewed_comment, 'page_title': 'Обсуждение', 'comment_form': CommentForm(), 'page_obj': paged, 'sub_comments': story.bl.get_local_comments_subscription(user), } return render_template('story_localcomments.html', **data)
def update(pk): logopic = Logopic.get(id=pk) if not logopic: abort(404) form = LogopicForm(data={ 'visible': logopic.visible, 'description': logopic.description, 'original_link': logopic.original_link, 'original_link_label': logopic.original_link_label, }) saved = False if form.validate_on_submit(): try: logopic.bl.update(current_user._get_current_object(), form.data) except ValidationError as exc: form.set_errors(exc.errors) else: saved = True return render_template( 'admin/logopics/work.html', page_title=gettext('Header picture'), logopic=logopic, form=form, edit=True, saved=saved, )
def add(): if request.args.get('notebook'): notebook = Notebook.query.filter_by( id=int(request.args.get('notebook'))).first() form = NoteForm(notebook=notebook.id) else: form = NoteForm() form.notebook.choices = [ (n.id, n.title) for n in Notebook.query.filter_by( author_id=current_user.id).all()] if form.validate_on_submit(): note = Note( title=form.title.data, body=form.body.data, notebook_id=form.notebook.data, author=current_user._get_current_object()) db.session.add(note) db.session.commit() tags = [] if not len(form.tags.data) == 0: for tag in form.tags.data.split(','): tags.append(tag.replace(" ", "")) note.str_tags = (tags) db.session.commit() return redirect(url_for('main.notebook', id=note.notebook_id)) return render_template('app/add.html', form=form)
def restore(target_attr, comment, template, template_ajax=None, template_ajax_modal=False): user = current_user._get_current_object() target = getattr(comment, target_attr) if not comment.bl.can_restore_by(user): abort(403) extra_ajax = g.is_ajax and request.form.get('extra_ajax') == '1' if request.method == 'POST': comment.bl.restore(user) if extra_ajax: return build_comment_response(comment, target_attr, target) else: return redirect(comment.bl.get_paged_link(user)) data = { 'page_title': gettext('Confirm restore comment'), target_attr: target, 'comment': comment, 'comment_restore': True, 'robots_noindex': True, } if g.is_ajax and template_ajax: html = render_template(template_ajax, **data) return jsonify({'page_content': {'modal': html} if template_ajax_modal else {'content': html}}) return render_template(template, **data)
def update(pk): character = Character.get(id=pk) if not character: abort(404) form = CharacterForm(data={ 'name': character.name, 'description': character.description, 'group': character.group.id if character.group else CharacterGroup.select().first().id, }) saved = False if form.validate_on_submit(): try: character.bl.update(current_user._get_current_object(), form.data) except ValidationError as exc: form.set_errors(exc.errors) else: saved = True return render_template( 'admin/characters/work.html', page_title=character.name, character=character, form=form, edit=True, saved=saved, )
def change_password(): """View function which handles a change password request.""" form_class = _security.change_password_form if request.is_json: form = form_class(MultiDict(request.get_json())) else: form = form_class() if form.validate_on_submit(): after_this_request(_commit) change_user_password(current_user._get_current_object(), form.new_password.data) if not request.is_json: do_flash(*get_message('PASSWORD_CHANGE')) return redirect(get_url(_security.post_change_view) or get_url(_security.post_login_view)) if request.is_json: form.user = current_user return _render_json(form) return _security.render_template( config_value('CHANGE_PASSWORD_TEMPLATE'), change_password_form=form, **_ctx('change_password') )
def new_post(slug=None): form = PostForm() if slug: post = Post.query.filter_by(slug=slug).first() if post.author_id != current_user.id: abort(404) if form.validate_on_submit(): post.content_html = request.form['editorValue'] post.topic = Topic.query.filter_by(title=form.topic.data).first() post.title = form.title.data db.session.add(post) flash(u'文章已修改') return redirect(url_for('main.index')) form.title.default = post.title form.topic.default = post.topic form.process() return render_template('new_post.html', form=form, post=post) else: if form.validate_on_submit(): content = request.form['editorValue'] topic = Topic.query.filter_by(title=form.topic.data).first() author = current_user._get_current_object() title = form.title.data post = Post(content_html=content, topic=topic, author=author, title=title) post.slug = post.slugify() db.session.add(post) db.session.commit() flash(u'文章已发布') return redirect(url_for('main.index')) return render_template('new_post.html', form=form)
def tag_index(tag_name, page): iname = normalize_tag(tag_name) if not iname: abort(404) tag = Tag.get(iname=iname) if tag and tag.is_alias_for is not None: if tag.is_alias_for.is_alias_for: raise RuntimeError('Tag alias {} refers to another alias {}!'.format(tag.id, tag.is_alias_for.id)) tag = tag.is_alias_for if not tag or tag.is_blacklisted: abort(404) if tag.iname != tag_name: return redirect(url_for('tags.tag_index', tag_name=tag.iname, page=page)) objects = Story.bl.select_by_tag(tag, user=current_user._get_current_object()) objects = objects.prefetch(Story.characters, Story.contributors, StoryContributor.user, Story.tags, StoryTag.tag, Tag.category) objects = objects.order_by(Story.first_published_at.desc(), Story.id.desc()) page_obj = Paginator(page, objects.count(), per_page=current_app.config['STORIES_COUNT']['stream']) objects = page_obj.slice_or_404(objects) return render_template( 'tags/tag_index.html', page_title=tag.name, tag=tag, aliases=[x.name for x in Tag.bl.get_aliases_for([tag])[tag.id]], category=tag.category, stories=objects, page_obj=page_obj, **cached_lists([x.id for x in objects]) )
def site_token(site_id): synchronize(site_id) next = url_for('.sign_in_success', site_id=site_id, _external=True) response = { 'sign_in': url_for('.widget', mode='select', next=next, _external=True), 'sign_out': url_for('.sign_out', _external=True), } user = current_user._get_current_object() if not user.is_authenticated: response['status_code'] = 401 return jsonify(response) if not user.email_verified: gitkit_account = gitkit.get_account_by_id(user.id) user.email_verified = gitkit_account['email_verified'] db.session.commit() response['account'] = { 'email': user.email, 'email_verified': user.email_verified, 'name': user.name, } for roles in user.roles: if roles.site_id == site_id: response['account']['roles'] = roles.roles break if not user.email_verified or 'roles' not in response['account']: response['status_code'] = 403 return jsonify(response) response['status_code'] = 200 response['access_token'] = token_serializer.dumps(user.id) return jsonify(response)
def upload(): error = '' url = '' callback = request.args.get("CKEditorFuncNum") if not isinstance(current_user._get_current_object(), User) or not current_user.can_upload(): error = '对不起你没有权限,请联系管理员' elif request.method == 'POST' and 'upload' in request.files: f = request.files['upload'] time_format = str(time.strftime("%Y-%m-%d-%H%M%S", time.localtime())) file_name = 'img'+time_format+'.jpg' file_name = secure_filename(file_name) f.save(os.path.join(application.static_folder+'/images', file_name)) else: error = 'post error' if not error: url = url_for('static', filename='images/'+file_name) res = """ <script type="text/javascript"> window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s'); </script> """ % (callback, url, error) response = make_response(res) response.headers["Content-Type"] = "text/html" return response
def query(path=None): """ Query endpoint for general queries via the web interface. Calls on the DOAJ.queryService for action :param path: :return: """ pathparts = request.path.strip('/').split('/') if len(pathparts) < 2: abort(400) domain = pathparts[0] index_type = pathparts[1] q = None # if this is a POST, read the contents out of the body if request.method == "POST": q = request.json # if there is a source param, load the json from it elif 'source' in request.values: q = json.loads(urllib2.unquote(request.values['source'])) try: account = None if current_user is not None and not current_user.is_anonymous: account = current_user._get_current_object() queryService = DOAJ.queryService() res = queryService.search(domain, index_type, q, account, request.values) except exceptions.AuthoriseException as e: abort(403) except exceptions.NoSuchObjectException as e: abort(404) resp = make_response(json.dumps(res)) resp.mimetype = "application/json" return resp
def new_pitches(): form = PitchForm() if form.validate_on_submit(): title = form.title.data description = form.description.data owners = form.owners.data cohort = form.cohort.data technologies = form.technologies.data new_pitch = Pitch(title=title, description=description, owners=owners, technologies=technologies, cohort=cohort, user_p=current_user._get_current_object().id) new_pitch.save_pitch() pitches = Pitch.query.order_by(Pitch.pitched_p.desc()).all() return render_template('pitches.html', pitches=pitches) title = 'New Pitch' return render_template('new_pitch.html', title=title, pitch_form=form)
def new_order(): form = OrderForm() choices = [] categories = Category.query.all() for category in categories: choices.append((category.name, category.name)) form.category.choices = choices if form.validate_on_submit(): category = Category.query.filter_by(name=form.category.data).first() print(category) name = form.name.data detail = form.detail.data budget = form.budget.data order = Order(name=name, detail=detail, budget=budget) order.belong_to_category = category order.belong_to_user = current_user._get_current_object() order.belong_to_status = OrderStatus.query.get(1) db.session.add(order) db.session.commit() return redirect(url_for('auth.user_profile', id=current_user.id)) return render_template('main/new_order.html', form=form)
def home(page): per_page = 10 form = PostForm() if current_user.is_authenticated and form.validate_on_submit(): post = Post(body=form.body.data) post.author = current_user._get_current_object() db.session.add(post) db.session.commit() return redirect(url_for('main.home', page=1)) posts = Post.query.order_by(Post.timestamp.desc()).all() pages = (len(posts) - 1) // per_page + 1 start = (page - 1) * per_page end = start + per_page posts = posts[start:end] return render_template('HomePage.html', form=form, posts=posts, current_time=datetime.utcnow(), pages=pages)
def index(): form = PostForm() # 发布文章按钮点击之后 if current_user.can( Permission.WRITE_ARITICLES) and form.validate_on_submit(): post = Post( body=form.body.data, author=current_user._get_current_object() ) # Post需要的是真正的user对象,current_user是对user的轻度包装,所以需要通过_get_current_object获取真正的对象 db.session.add(post) return redirect(url_for('.index')) # 判断展示哪些文章 from 12.4 show_followed = False if current_user.is_authenticated: # 从cookie里取show_followed字段。request.cookies这是一个字典 show_followed = bool(request.cookies.get('show_followed', '')) print('show_followed result = ' + 'show followed' if show_followed else 'show all' + 'request = ' + str(request)) if show_followed: query = current_user.followed_posts else: query = Post.query # posts = Post.query.order_by(Post.timestmp.desc()).all() page = request.args.get( 'page', 1, type=int) # 从请求的查询字符串中获取渲染的页数,没有指定则显示第1页,type=int保证参数无法转换成整数时,返回默认值 # paginate: SQLAlchemy的分页控件,返回值是一个Pagination类对象,用于在模板中生成分页链接 # 进一步理解下分页,其实它类似于一个SQLAlchemy的过滤器... pagination = query.order_by(Post.timestmp.desc()).paginate( page, per_page=current_app.config['FLASKY_POSTS_PER_PAGE'], error_out=False) posts = pagination.items return render_template('index_with_posts.html', form=form, posts=posts, pagination=pagination)
def change_email_request(): """Respond to existing user's request to change their email.""" form = ChangeEmailForm() if form.validate_on_submit(): if current_user.verify_password(form.password.data): new_email = form.email.data token = current_user.generate_email_change_token(new_email) change_email_link = url_for('account.change_email', token=token, _external=True) status = send_email(recipient=new_email, subject='Confirm Your New Email', template='account/email/change_email', user=current_user._get_current_object(), change_email_link=change_email_link) flash('A confirmation link has been sent to {}.'.format(new_email), 'warning') return redirect(url_for('main.index')) else: flash('Invalid email or password.', 'form-error') return render_template('account/manage.html', form=form)
def index(): 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')) show_followed = False if current_user.is_authenticated: show_followed = bool(request.cookies.get('show_followed', '')) page = request.args.get('page', 1, type=int) 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['FLASKY_PER_PAGE'], error_out=False) posts = pagination.items return render_template('index.html', posts=posts, form=form, pagination=pagination, show_followed=show_followed)
def new_blog(): subscribers = Subscriber.query.all() blog = Blog.query.first() form = BlogForm() if form.validate_on_submit(): title = form.title.data blog = form.blog.data user_id = current_user new_blog_object = Blog(blog=blog, user_id=current_user._get_current_object().id, title=title) new_blog_object.save_blog() for subscriber in subscribers: mail_message("New Blog", "email/new_post_alert", subscriber.email, new_blog_object=new_blog_object) return redirect(url_for('main.index')) return render_template('new_blog.html', form=form)
def course_delete(CourseNum): if isinstance(current_user._get_current_object(), Manager): # 先删除选课信息 course_select_tables = Course_select_table.query.filter_by( CourseNum=CourseNum).all() for course_select_table in course_select_tables: db.session.delete(course_select_table) db.session.commit() flash('删除学生选课信息成功!') # 再删除课程与老师的对应表 course_teachers = Course_Teacher.query.filter_by( CourseNum=CourseNum).all() for course_teacher in course_teachers: db.session.delete(course_teacher) db.session.commit() flash('删除教师开设课程成功!') # 最后删除课程 course = Course.query.filter_by(CourseNum=CourseNum).first() db.session.delete(course) db.session.commit() flash('删除课程成功!') return redirect(url_for('course_manage'))
def post(id): post = Post.query.get_or_404(id) form = CommentForm() if form.validate_on_submit(): comment = Comment(body=form.body.data, post=post, author=current_user._get_current_object()) db.session.add(comment) db.session.commit() flash('your comment has been published') return redirect(url_for('.post', id=post.id, page=-1)) page = request.args.get('page', 1, type=int) if page == -1: page = (post.comments.count()-1) // \ current_app.config['MICRO_COMMENTS_PER_PAGE'] + 1 pagination = post.comments.order_by(Comment.timestamp.asc()).paginate( page, per_page=current_app.config['MICRO_COMMENTS_PER_PAGE'], error_out=False ) comments = pagination.items return render_template('post.html', posts=[post], form=form, comments=comments, pagination=pagination)
def form(): if request.method == 'GET': return render_template('form.html', users=User.objects) elif request.method == 'POST': try: mytask = Task() mytask.name = request.form['name'] print mytask.name mytask.user = current_user._get_current_object() print mytask.user mytask.assignee = User.objects.get(id=request.form['assignee']) print mytask.assignee mytask.date = datetime.strptime(request.form['date'], "%Y-%m-%d") print mytask.date mytask.save() except Exception as e: print e flash('Oops, try again !', 'danger') return redirect(url_for('form')) else: flash("Nouvelle tache ajoutee", 'success') return redirect(url_for('list'))
def change_profile(): if current_user._get_current_object().__class__.__name__ == 'Courier': form = ChangeForm() if request.method == "POST": if form.validate_on_submit(): if check_times(int(form.start_hour.data), int(form.finish_hour.data)): session = db_session.create_session() session.query(Courier).filter(Courier.id == current_user.id).update({ "courier_type": form.type.data, "regions": [form.region.data], "working_hours": [ f"{str(form.start_hour.data).rjust(2, '0')}:00-{str(form.finish_hour.data).rjust(2, '0')}:00"]}) session.query(User).filter(User.id_from_type_table == current_user.id, User.type == 'courier').update( {"hashed_password": set_password(form.password.data)}) session.commit() return redirect('/profile') return render_template('change_profile.html', user=current_user, form=form, time_message='Такое время недопустимо.') return render_template('change_profile.html', user=current_user, form=form, time_message='') elif request.method == "GET": return render_template('change_profile.html', user=current_user, form=form, time_message='') return render_template('no_access.html', user=current_user)
def index(): # next line of code causing warning though form inherits from FlaskForm: # FlaskWTFDeprecationWarning: "flask_wtf.Form" has been renamed to "FlaskForm" and will be removed in 1.0. 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')) 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 page = request.args.get('page', 1, type=int) pagination = query.order_by(Post.timestamp.desc()).paginate( page, per_page=current_app.config['SONGBOOK_POSTS_PER_PAGE'], error_out=False) posts = pagination.items return render_template('index.html', form=form, posts=posts, pagination=pagination, show_followed=show_followed)
def hired(id): post = Post.query.get_or_404(id) apps = Application.query.filter_by(post_id=id, approved=True) tasks = Task.query.filter_by(post_id=id, done=False) form1 = CommentForm(prefix="form1") form2 = TaskForm(prefix="form2") if form1.validate_on_submit(): comment = Comment(body=form.body.data, post=post, author=current_user._get_current_object()) db.session.add(comment) flash('Your comment has been published.') return redirect(url_for('.post', id=post.id, page=-1)) if form2.validate_on_submit(): for app in apps: task = Task(description=form2.body.data, post_id=id, worker_id=app.applicant_id) db.session.add(task) flash('Your task has been sent out.') return redirect(url_for('.hired', id=post.id, page=-1)) page = request.args.get('page', 1, type=int) if page == -1: page = (post.comments.count() - 1) // \ current_app.config['FLASKY_COMMENTS_PER_PAGE'] + 1 pagination = post.comments.order_by(Comment.timestamp.asc()).paginate( page, per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'], error_out=False) comments = pagination.items return render_template('workers.html', post=post, posts=[post], comments=comments, form=form1, form2=form2, pagination=pagination, tasks=tasks, apps=apps)
def the_post(id): form = CommentForm() the_post = Post.query.get_or_404(id) if form.validate_on_submit(): comment = Comment(body=form.body.data, author=current_user._get_current_object(), post=the_post) db.session.add(comment) db.session.commit() return redirect(url_for('post.the_post', id=the_post.id, page=-1)) current_page = request.args.get('page', 1, type=int) if current_page == -1: current_page = (the_post.comments.count() - 1) // 5 + 1 pagination = the_post.comments.order_by(Comment.timestamp.asc()).paginate( current_page, per_page=5, error_out=False) comments = pagination.items return render_template('the_post.html', post=the_post, form=form, pagination=pagination, comments=comments)
def index(): form = CommentForm() page = request.args.get('page', 1, type=int) posts = current_user.followed_posts().paginate( page, current_app.config['POSTS_PER_PAGE'], False) next_url = url_for('posts.index', page=posts.next_num) \ if posts.has_next else None prev_url = url_for('posts.index', page=posts.prev_num) \ if posts.has_prev else None if form.validate_on_submit(): comment = Comment(body=form.body.data, post=post, author=current_user._get_current_object()) db.session.add(comment) db.session.commit() return render_template('posts/index.html', title='Followed Posts', posts=posts.items, form=form, next_url=next_url, prev_url=prev_url)
def handleUrl(content, slug: str, update: bool = False): res = None if not slug and not update: keyLength = app.config['URL_KEY_GENERATOR'].get('keyLength', 7) slug = urlKeyGenerator.createKey(keyLength) while not store.slugAvailable(slug): slug = urlKeyGenerator.createKey(keyLength) if update: res = store.get(slug, True) res.update_content(content) else: res = store.set( Document(slug, True, content, owner=current_user._get_current_object()), True) if (not res): app.logger.info('error adding url') return jsonify({'message': 'Error adding url.'}), 500 else: app.logger.info('added url %s', slug) return jsonify({'key': slug, 'isUrl': True})
def index(): form = PostsForm() u = current_user._get_current_object() if form.validate_on_submit(): if current_user.is_authenticated: p = Posts(content=form.content.data, timestamp=datetime.now(), user=u) db.session.add(p) db.session.commit() 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, rrid=0).order_by( Posts.timestamp.desc()).paginate(page, per_page=3, error_out=True) posts = pagination.items return render_template('main/index.html', form=form, posts=posts, pagination=pagination)
def joined(channel): new_channel = Channel.query.filter_by(name=channel).first() if new_channel is None: return emit('flash', [{'message': 'The channel you have tried to reach does not exist.', 'category': 'danger'}]) join_room(channel) previous_channel = current_user.channel_id and current_user.current_channel.name if current_user.channel_id is None or current_user.current_channel.name != channel: current_user.current_channel = new_channel db.session.add(current_user._get_current_object()) db.session.commit() if previous_channel is not None and previous_channel != channel: emit('load members', {'members': Channel.query.filter_by( name=previous_channel).first().get_all_channel_members(offset=0), 'isReload': True}, room=previous_channel) emit('load channel information', current_user.current_channel.to_json()) emit('load members', {'members': current_user.current_channel.get_all_channel_members(offset=0), 'isReload': True}, room=current_user.current_channel.name) emit('load messages', {'messages': current_user.current_channel.get_all_channel_messages(offset=0), 'fromSendMessage': False, 'fromScrollEvent': False})
def index(): user_agent = request.headers.get('user_agent') if current_user.is_authenticated: form = PostForm() if form.validate_on_submit(): post = Post(cont=form.body.data, author_id=current_user._get_current_object()) db.session.add(post) return redirect(url_for('.index')) else: form = NameForm() if form.validate_on_submit(): old_name = session.get('name') if old_name is not None and old_name != form.name.data: flash('你改名啦~') session['name'] = form.name.data return redirect(url_for('main.index')) return render_template('index.html', name=session.get('name'), form=form, user_agent=user_agent, current_time=datetime.utcnow())
def blog1(): form = PostForm() if form.validate_on_submit(): if current_user.is_authenticated: # 获取当前登录的用户 u = current_user._get_current_object() p = Posts(title=form.title.data, content=form.content.data, user=u) db.session.add(p) db.session.commit() return redirect(url_for('users.blog1')) else: flash("请先登录") print(form.errors) return redirect(url_for('users.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 return render_template('user/blog1.html', form=form, posts=posts, pagination=pagination)
def command(port): form = CommandForm() id = Posts.query.filter_by(content=port).first().id if form.validate_on_submit(): if current_user.is_authenticated: u = current_user._get_current_object() p = Posts(content=form.content.data, user=u, rid=id) db.session.add(p) return redirect(url_for('main.command', port=port)) else: flash('登录后才能评论') return redirect('user.login') page = request.args.get('page', 1, type=int) pagination = Posts.query.filter_by(rid=id).order_by( Posts.timestamp.desc()).paginate(page, per_page=3, error_out=False) posts = pagination.items return render_template('main/command.html', form=form, posts=posts, pagination=pagination, port=port)
def add_post(): """add post to db""" data = request.get_json() try: post = post_schema(data) except MultipleInvalid as e: return make_error_resp(2001, str(e)) current_app.logger.debug("save post with categories: {}".format( post.get('categories'))) status, obj = save_model_from_json(Post, post) current_app.logger.debug("post status: {}".format(status)) if status: obj.content = format_markdown(obj.markdown) obj.published_at = datetime.now() obj.created_at = datetime.now() obj.author = current_user._get_current_object() current_app.logger.info("save post with len: {}".format( len(obj.content))) obj.save() return normal_resp({'post': obj.to_json()}) else: return make_error_resp(2001, {})
def index(): form = PostsForm() if form.validate_on_submit(): #判断是否登录python 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=5, error_out=False) posts = pagination.items return render_template('main/index.html', form=form, posts=posts, pagination=pagination)
def index(): form = EditPostForm() if request.method=="POST": post=Post( body=request.form.get('body'), author=current_user._get_current_object() ) db.session.add(post) return redirect(url_for('main.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 page=request.args.get('page',default=1,type=int) pagination=query.order_by(Post.timestamp.desc()).paginate( page,current_app.config['FLASKY_POSTS_PER_PAGE'],error_out=False ) posts=pagination.items return render_template('index.html',form=form,posts=posts,pagination=pagination,show_followed=show_followed)
def comment(id): form = CommentForm() pitch = Pitch.query.get(id) user = User.query.all() comments = Comment.query.filter_by(pitches_id=id).all() if form.validate_on_submit(): comment = form.comment.data user_id = current_user._get_current_object().id new_comment = Comment(comment=comment, user_id=user_id, pitches_id=pitch.id) new_comment.save_comment() new_comments = [new_comment] print(new_comments) return redirect(url_for('.index')) return render_template('comment.html', form=form, comments=comments, user=user)
def add(): user = current_user._get_current_object() rating = Rating.select().order_by(Rating.id.desc()).first() form = StoryForm(data={ 'status': 0, 'original': 1, 'rating': rating.id if rating else 1 }) data = { 'page_title': gettext('New story'), 'form': form, 'story_add': True, 'saved': False, 'not_saved': False, } if form.validate_on_submit(): formdata = dict(form.data) if formdata['status'] == 0: formdata['status'] = 'unfinished' elif formdata['status'] == 1: formdata['status'] = 'finished' elif formdata['status'] == 2: formdata['status'] = 'freezed' formdata['tags'] = [x.strip() for x in formdata['tags'].split(',')] formdata['tags'] = [x for x in formdata['tags'] if x] try: story = Story.bl.create([user], formdata) except ValidationError as exc: form.set_errors(exc.errors) data['not_saved'] = True else: return redirect(url_for('story.edit', pk=story.id)) return render_template('story_work.html', **data)
def edit_profile(): form = EditProfileForm(user=current_user) if request.method == 'POST': if form.validate_on_submit(): changes = False if current_user.email != form.email.data: token=current_user.generate_email_change_token(form.email.data) send_email(form.email.data, "Confirm Email Change","main/email/confirm",user=current_user,new_email=form.email.data,token=token) flash('A confirmation has been sent to your chosen new email account.') if current_user.last_name != form.last_name.data: current_user.last_name = form.last_name.data changes=True if current_user.first_name != form.first_name.data: current_user.first_name = form.first_name.data changes=True if current_user.about_me != form.about_me.data: current_user.about_me = form.about_me.data changes=True if changes==True: db.session.add(current_user._get_current_object()) db.session.commit() flash('Your changes have been saved.') else: flash('No edits were made.') return redirect(url_for('main.profile',id=current_user.id)) else: if form.cancel.data: flash('No edits were made to your account.') return redirect(url_for('main.profile',id=current_user.id)) else: for error in form.errors: flash(form.errors[error][0]) return render_template('main/edit_user.html.j2',user=current_user,form=form) form.email.data = current_user.email form.last_name.data = current_user.last_name form.first_name.data = current_user.first_name form.about_me.data = current_user.about_me return render_template('main/edit_user.html.j2',user=current_user,form=form)
def index(): name = None user = current_user._get_current_object() old_name = session.get('name') page = request.args.get('page', 1, type=int) show_followed = False show_followed = bool(request.cookies.get('show_followed', '')) if old_name != None and old_name != user.username: flash('Looks like you\'ve changed your name') print(user) if not user: session['known'] = False # send_mail(form.email.data, 'New User', 'mail/new_user', user=user) else: session['known'] = True session['name'] = user.username if not show_followed: query = Post.query else: query = current_user.followed_posts # posts = user.posts.order_by(Post.timestamp).all() pagination = query.order_by(Post.timestamp.desc()).paginate( page, per_page=int(current_app.config['FLASKY_POSTS_PER_PAGE']), error_out=False) posts = pagination.items return render_template('index.html', posts=posts, name=session.get('name'), known=session.get('known', False), current_time=datetime.utcnow(), pagination=pagination, show_followed=show_followed)
def index(): form = PostForm() if current_user.can(Permission.WRITE) and form.validate_on_submit(): # 保存图片 name1 = "" name2 = "" name3 = "" file1 = request.files['img1'] # 获取图片 file2 = request.files['img2'] file3 = request.files['img3'] name1 = str(int(round(time.time() * 1000))) + "1_" + file1.filename # 格式化文件名 file1.save(os.path.join(current_app.config['UPLOAD_FOLDER'], name1)) # 保存图片 name2 = str(int(round(time.time() * 1000))) + "2_" + file2.filename file2.save(os.path.join(current_app.config['UPLOAD_FOLDER'], name2)) name3 = str(int(round(time.time() * 1000))) + "3_" + file3.filename file3.save(os.path.join(current_app.config['UPLOAD_FOLDER'], name3)) post = Post(body=form.body.data, author=current_user._get_current_object(), img1_url=name1, img2_url=name2, img3_url=name3) db.session.add(post) db.session.commit() return redirect(url_for('.index')) 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 pagination = query.order_by(Post.timestamp.desc()).paginate( # 按时间戳排序 page, per_page=current_app.config['FLASKY_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 index(): users = User.query.order_by(User.score.desc()).limit(7) # all open series open_series = Series.query.filter(Series.open == True).all() closed_series = Series.query.filter(Series.open == False).all() if current_user.is_authenticated: usr = current_user._get_current_object() form = CommentForm() if form.validate_on_submit(): comment = Comment() comment.body = form.body.data comment.user = usr db.session.add(comment) msg = u'Dodat komentar.' flash(msg) return redirect(url_for('main.index')) comments = Comment.query.all() else: form = None comments = None return render_template('index.html', comments=comments, series=open_series, closed_series=closed_series, users=users, form=form)