コード例 #1
0
def save():
    v = Validator(request.form)
    v.fields('id').integer(nullable=True)
    v.field('title').required()
    v.field('text').required()
    v.field('category_id').integer(nullable=True)
    user = auth.service.get_user()
    if not user.is_authorized():
        abort(403)
    if v.is_valid():
        data = v.valid_data

        news = News.get(data.id)

        if news:
            news.title = data.title
            news.text = data.text
        else:
            news = News()
            news.title = data.title
            news.text = data.text
            news.author = user

        category = NewsCategory.get(data.category_id)
        news.category = category

        tags = data.list('tag')
        existing_tags = {tag.name: tag for tag in NewsTag.get_tags(tags)}
        tags = {tag: NewsTag(name=tag) for tag in tags}
        tags.update(existing_tags)

        news.tags = list(tags.values())

        is_new = True if user.id is not None else False
        db.session.add(news)
        db.session.commit()

        if is_new:
            send_news_notification.delay(news.id, news.title)

        return jsonify({'status': 'ok',
                        'news': news.as_dict()})

    return jsonify({'status': 'fail',
                    'errors': v.errors})
コード例 #2
0
def list_all_by_tag(id):
    tag = NewsTag.get(id)
    news = News.all_by_tag(tag) if tag else []
    return render_template('news/all.html', **{'tag': tag, 'news': news})