Ejemplo n.º 1
0
def populate_default_data(db, app):
    db.app = app
    db.create_all()

    user = User()
    user.username = "******"
    user.set_password("jim")
    db.session.add(user)
    db.session.commit()

    tag_one = Tag(title="Python")
    tag_two = Tag(title="Flask")
    tag_three = Tag(title="SQLAlchemy")
    tag_four = Tag(title="Jinja")
    tag_list = [tag_one, tag_two, tag_three, tag_four]
    s = "Example text"

    for i in range(100):
        new_post = Post(title="Post " + str(i))
        new_post.user = user
        new_post.publish_date = datetime.datetime.now()
        new_post.text = s
        new_post.tags = random.sample(tag_list, random.randint(1, 3))
        db.session.add(new_post)

    db.session.commit()
Ejemplo n.º 2
0
def new(type):
    form = PostForm()
    if form.validate_on_submit():
        new_post = Post(form.title.data)
        new_post.text = form.text.data
        new_post.cover = form.cover.data
        new_post.publish_date = datetime.now()
        new_post.update_date = new_post.publish_date
        new_post.user_id = current_user.id
        new_post.type = type
        new_post.summary = form.summary.data
        new_post.video = form.video.data
        tagStrList = form.tags.data.split(',')
        for tagStr in tagStrList:
            tagStr = tagStr.strip()
            tag = Tag.query.filter_by(title=tagStr).first()
            if not tag:
                tag = Tag(tagStr)
            new_post.tags.append(tag)

        for photo_url in form.photos.data:
            if photo_url != '':
                photo = Photo(photo_url)
                new_post.photos.append(photo)

        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('blog.post', post_id=new_post.id))
    form.type.data = type
    return render_template("edit_{}.html".format(type), form=form, type=type)
Ejemplo n.º 3
0
	def post(self,post_id=None):
		if post_id:
			abort(405)
		else:
			args = post_post_parser.parse_args(strict=True)

			user = User.verify_auth_token(args['token'])
			if not user:
				abort(401)

			new_post = Post(args['title'])
			new_post.user = user
			new_post.publish_date=datetime.datetime.now()
			new_post.text = args['text']
			if args['tags']:
				for item in args['tags']:
					tag = Tag.query.filter_by(
						title=item
					).first()

					if tag:
						new_post.tags.append(tag)
					else:
						new_tag = Tag(item)
						new_post.tags.append(new_tag)


			db.session.add(new_post)
			db.session.commit()

			return new_post.id,201
Ejemplo n.º 4
0
    def post(self, post_id=None):
        if post_id:
            abort(400)
        else:
            args = post_post_parser.parse_args(strict=True)

            user = User.verify_auth_token(args['token'])
            if not user:
                abort(401)

            new_post = Post(args['title'])
            new_post.user = user
            new_post.date = datetime.datetime.now()
            new_post.text = args['text']

            if args['tags']:
                for item in args['tags']:
                    tag = Tag.query.filter_by(title=item).first()

                    # Add the tag if it exists. If not, make a new tag
                    if tag:
                        new_post.tags.append(tag)
                    else:
                        new_tag = Tag(item)
                        new_post.tags.append(new_tag)

            db.session.add(new_post)
            db.session.commit()
            return new_post.id, 201
Ejemplo n.º 5
0
def create_users_posts():
    session = Session()
    user = User(username='******', password='******')
    session.add(user)
    session.flush(session)

    print("Создаем посты от имени пользователя: ", user)
    print('------создаем посты-----')
    post1 = Post(user_id=user.id, title='Обзор фильма "Во все тяжкие"',
                 text='Здесь находится большой текст-описание обзора фильма "Во все тяжкие"', timestamp=datetime.now())
    post2 = Post(user_id=user.id, title='Обзор фильма "Гладиатор"',
                 text='Здесь находится большой текст-описание обзора фильма "Гладиатор"', timestamp=datetime.now())
    post3 = Post(user_id=user.id, title='Обзор фильма "Терминатор"',
                 text='Здесь находится большой текст-описание обзора фильма "Терминатор"', timestamp=datetime.now())
    post4 = Post(user_id=user.id, title='Обзор фильма "Мишки Гамми"',
                 text='Здесь находится большой текст-описание обзора фильма "Мишки Гамми"', timestamp=datetime.now())
    post5 = Post(user_id=user.id, title='Обзор фильма "Кремниевая долина"',
                 text='Здесь находится большой текст-описание обзора фильма "Кремниевая долина"', timestamp=datetime.now())
    session.add(post1)
    session.add(post2)
    session.add(post3)
    session.add(post4)
    session.add(post5)
    create_start_tags()
    session.commit()
    session.close()
Ejemplo n.º 6
0
    def post(self):
        data = reqparse.RequestParser()
        data.add_argument('title', type=str, required=True)
        data.add_argument('text', type=str, required=True)
        args = data.parse_args()

        post = Post(args['title'])
        post.text = args['text']
        db.session.add(post)
        db.session.commit()
Ejemplo n.º 7
0
def insert_data():
    # 不需要在这里创建库,应该使用数据库升级命令`db upgrade`来创建库
    # db.create_all()

    # 注意调用顺序
    Role.generate_fake()
    User.generate_fake()
    Tag.generate_fake()
    Post.generate_fake()
    Comment.generate_fake(1000)
Ejemplo n.º 8
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        new_post = Post(form.title.data)
        new_post.text = form.text.data
        new_post.publish_date = datetime.datetime.now()

        db.session.add(new_post)
        db.session.commit()
    return render_template('new.html', form=form)
Ejemplo n.º 9
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        new_post = Post(form.title.data)
        new_post.text = form.text.data
        new_post.publish_date = datetime.datetime.now()
        new_post.user = User.query.filter_by(
            username=current_user.username).one()
        db.session.add(new_post)
        db.session.commit()
    return render_template('new.html', form=form)
Ejemplo n.º 10
0
def new_post():
    form=PostForm()

    if form.validate_on_submit():
        new_post = Post(form.title.data)
        new_post.text = form.text.data
        new_post.publish_date = datetime.datetime.now()

        db.session.add(new_post)
        db.session.commit()

    return render_template('new.html', form=form)
Ejemplo n.º 11
0
def add(request):  #broker
    if request.method == 'POST':
        resp = request.body.decode('UTF-8')
        data = json.loads(resp)
        lista = Adapters.objects.filter(ativo=1).values("rid")
        if data["to"] == 1:
            isRecomendation = False
            for i in lista:
                if i["rid"] in (
                        data["id"]).split(" "):  #clique de recomendacao
                    isRecomendation = True
                    adapter = i["rid"]
                    break
            post_data = Post(data["ip"], data["idUser"], data["idClick"],
                             data["classe"], data["texto"], data["current"],
                             data["href"], data["timestamp"],
                             data["dateTimestamp"], data["dateR"])
            post_data.save()  #salva o clique na tabela ClickStream
            if isRecomendation:  #salva na tabela recomendações acessadas caso o clique proveio de uma recomendação
                post_data = RecomendacaoAcessada(adapter,
                                                 data["idClick"],
                                                 date=data["dateR"])
                post_data.save()
            return HttpResponse(status=204)
        else:  #gerar recomendacao
            dados = Post.objects.get(idClick=data["idClick"])
            for i in lista:
                if i["rid"] == data["iden"]:
                    recomendador = i["rid"] + '.' + i[
                        "rid"]  #nome do recomendador (ou funcao)
                    try:
                        recomendador = eval(
                            recomendador)  # executa python dentro da execução
                    except:
                        module = __import__("webapp.algorithms." + i["rid"],
                                            fromlist=i["rid"])
                        recomendador = getattr(module, i["rid"])
                    finally:
                        function_output = recomendador(
                            request,
                            dados)  #saida deverá ser um vetor de links
                        for each_link in function_output:
                            post_data = RecomendacaoGerada(  #salva as recomendações sugeridas
                                i["rid"], data["idClick"], each_link,
                                data["dateR"])
                            post_data.save()
                        return JsonResponse({i["rid"]: function_output})
            return HttpResponse(status=204)
    else:
        return HttpResponse(status=204)
Ejemplo n.º 12
0
def new_post():
    form = PostForm()

    if form.validate_on_submit():
        new_post = Post(form.title.data)
        new_post.text = form.text.data
        new_post.publish_date = datetime.datetime.now()
        new_post.user = User.query.filter_by(
            username=current_user.username
        ).one()

        db.session.add(new_post)
        db.session.commit()

    return render_template('new.html', form=form)
Ejemplo n.º 13
0
def new_post():
    form = PostForm()

    if not current_user:
        return redirect(url_for('main.login'))

    if form.validate_on_submit():
        new_post = Post(form.title.data)
        new_post.text = form.text.data
        new_post.publish_date = datetime.datetime.now()

        db.session.add(new_post)
        db.session.commit()

    return render_template('new.html', form=form)
Ejemplo n.º 14
0
def add_post():
    if not g.current_user:
        flash('发表新想法前请先登录!', category='error')
        return redirect(url_for('main.login'))
    form = PostForm()
    if form.validate_on_submit():
        new_post = Post(form.title.data, form.content.data)
        new_post.publish_date = datetime.datetime.now()
        new_post.user = g.current_user
        new_post.category = PostCategory(form.category.data)

        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('.get_post', post_id=new_post.id))

    return render_template('add.html', form=form)
Ejemplo n.º 15
0
    def post(self):

        args = self.parser.parse_args()
        # 校验参数必须填写
        if args.title is None or args.post_type is None or args.category is None\
                or args.summary is None or args.content is None:
            abort(400)

        # 文章类型,文章,视频,企业内推
        post_type = args.post_type

        # 校验用户身份 admin用户允许新增文章
        if args.token is None:
            abort(403)
        user = User.verify_auth_token(args.token)
        if user is None:
            abort(403)
        if user.username != '*****@*****.**':
            abort(403)

        new_post = Post(user.id, user.nickname, post_type, args.title,
                        args.image, args.category, args.tags, args.summary,
                        args.content)
        db.session.add(new_post)
        db.session.commit()
Ejemplo n.º 16
0
def index():
    form = PostForm()
    if form.validate_on_submit():
        language = guess_language(form.post.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ''
        post = Post(body=form.post.data,
                    author=current_user,
                    language=language)
        db.session.add(post)
        db.session.commit()
        flash(_('Your post is now live!'))
        return redirect(url_for('index'))
    #分页
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('index',
                       page=posts.next_num if posts.has_next else None)
    prev_url = url_for('index',
                       page=posts.prev_num if posts.has_prev else None)
    return render_template('index.html',
                           title=_('Home'),
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url)
Ejemplo n.º 17
0
def setup_db():
    db.create_all()

    # role_list = (('admin', 'admin'), ('default', 'default'))
    # Role.create_roles(role_list)
    # tag_list = [Tag.create(tag) for tag in ('Python', 'Flask', 'SQLAlchemy', 'Jinja')]
    # default_role = Role.create_role('default', 'default')
    # s = 'Body text'
    admin_role = Role.create_role('admin', 'admin')

    User.create(username='******',
                email='*****@*****.**',
                password='******',
                roles=admin_role)

    Post.generate_fake_posts()
Ejemplo n.º 18
0
def search():
    if not g.search_form.validate():
        return redirect(url_for('main.explore'))

    page = request.args.get('gage', 1, type=int)
    search_results, total = Post.search(g.search_form.q.data, page,
                                        current_app.config['POSTS_PER_PAGE'])
    posts = search_results.paginate(page, current_app.config['POSTS_PER_PAGE'],
                                    False)

    next_url = url_for('main.search',
                       page=posts.next_num) if posts.has_next else None
    prev_url = url_for('main.search',
                       page=posts.prev_num) if posts.has_prev else None

    displayPagination = search_results.count(
    ) > current_app.config['POSTS_PER_PAGE']
    print(displayPagination)

    return render_template('search.html',
                           title='Search Results',
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url,
                           display=displayPagination)
Ejemplo n.º 19
0
    def setUp(self):
        db.app = test_app
        db.create_all()
        user = User()
        user.username = self.username
        user.set_password(self.password)
        db.session.add(user)

        comment = Comment()
        comment.name = self.comment_name
        comment.text = self.comment_text

        tag = Tag()
        tag.title = self.tag_title

        post = Post()
        post.title = self.post_title
        post.text = self.post_text
        post.publish_date = self.post_publish_date

        # add relationships to other tables
        post.user = user
        post.tags = [tag]
        post.comments = [comment]

        db.session.add(user)
        db.session.add(comment)
        db.session.add(tag)
        db.session.add(post)
        db.session.commit()
Ejemplo n.º 20
0
    def test_follow_posts(self):
        # create four users
        mohamed = User(username='******', email='*****@*****.**')
        wamda = User(username='******', email='*****@*****.**')
        ragda = User(username='******', email='*****@*****.**')
        abdeen = User(username='******', email='*****@*****.**')
        db.session.add_all([mohamed, wamda, ragda, abdeen])

        # create four posts
        now = datetime.utcnow()
        p1 = Post(title="Mohamed post's title",
                  content="post from mohamed",
                  author=mohamed,
                  date_posted=now + timedelta(seconds=1))
        p2 = Post(title="Wamda post's title",
                  content="post from wamda",
                  author=wamda,
                  date_posted=now + timedelta(seconds=4))
        p3 = Post(title="Ragda post's title",
                  content="post from ragda",
                  author=ragda,
                  date_posted=now + timedelta(seconds=3))
        p4 = Post(title="Abdeen post's title",
                  content="post from abdeen",
                  author=abdeen,
                  date_posted=now + timedelta(seconds=2))
        db.session.add_all([p1, p2, p3, p4])
        db.session.commit()

        # setup the followers
        mohamed.follow(wamda)  # mohamed follows wamda
        mohamed.follow(abdeen)  # mohamed follows abdeen
        wamda.follow(ragda)  # wamda follows ragda
        ragda.follow(abdeen)  # ragda follows abdeen
        db.session.commit()

        # check the followed posts of each user
        f1 = mohamed.followed_posts().all()
        f2 = wamda.followed_posts().all()
        f3 = ragda.followed_posts().all()
        f4 = abdeen.followed_posts().all()
        self.assertEqual(f1, [p2, p4])
        self.assertEqual(f2, [p3])
        self.assertEqual(f3, [p4])
        self.assertEqual(f4, [])
Ejemplo n.º 21
0
def new_post():
    form = PostForm()

    if form.validate_on_submit():
        new_post = Post()
        new_post.title = form.title.data
        new_post.text = form.text.data
        new_post.publish_date = datetime.datetime.now()

        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('blog.post', post_id=new_post.id))

    recent, top_tags = sidebar_data()
    return render_template('new.html',
            form=form,
            recent=recent,
            top_tags=top_tags)
Ejemplo n.º 22
0
def new_post():
    # 此处验证用login_required装饰器代替
    '''
    if not g.current_user:
        return redirect(url_for('main.login'))
    '''
    form = PostForm()

    if form.validate_on_submit():
        new_post = Post(form.title.data)
        new_post.text = form.text.data
        new_post.publish_date = datetime.datetime.now()
        new_post.user = current_user

        db.session.add(new_post)
        db.session.commit()
        return redirect(url_for('.post', post_id=new_post.id))
    return render_template('new.html', form=form)
Ejemplo n.º 23
0
    def process_submission(self, post):
        print('Post Recieved')

        try:
            from webapp.models import Post, Review
        except django.core.exceptions.AppRegistryNotReady:
            return False

        if "[review]" in post.title.lower():
            try:
                p_exists = Post.objects.get(id=post.id)
                print('Post in Database')
                return False
            except Post.DoesNotExist:
                pass

            p = Post(user=post.author.name,
                     date=post.created,
                     link=post.url,
                     id=post.id,
                     title=post.title)
            p.save()

            print(post.title + ' is not in the database, adding')
            split_selftext = post.selftext.split('\n')
            index, review_start_index, review_end_index = 0, -1, -1

            while (index < len(split_selftext)):
                if (review_start_index == review_end_index
                        and "|" in split_selftext[index]):
                    review_start_index = index
                elif (review_start_index != review_end_index
                      and "|" in split_selftext[index]):
                    review_end_index = index
                index += 1

            if (review_start_index == -1 or review_end_index == -1):
                return []

            r_list = parse.parse_review(
                split_selftext[review_start_index:review_end_index + 1], p)
            for r in r_list:
                r.save()
Ejemplo n.º 24
0
def scrape_post(post):
    if "[review]" in post.title.lower():
        print("Run Scraper")
        try:
            p_exists = Post.objects.get(id=post.id)
            return
        except Post.DoesNotExist:
            pass

        p = Post(user=post.author.name,
                 date=parse.parse_date(post.created),
                 link=post.url,
                 id=post.id,
                 title=post.title)
        p.save()

        pprint(('Post: ' + str(p)))
        split_selftext = post.selftext.split('\n')
        index, review_start_index, review_end_index = 0, -1, -1

        while (index < len(split_selftext)):
            if (review_start_index == review_end_index
                    and "|" in split_selftext[index]):
                review_start_index = index
            elif (review_start_index != review_end_index
                  and "|" in split_selftext[index]):
                review_end_index = index
            index += 1

        if (review_start_index == -1 or review_end_index == -1):
            return []

        r_list = parse.parse_review(
            split_selftext[review_start_index:review_end_index + 1], p)
        for r in r_list:
            p.review_set.create(user=r.user,
                                date=post.created,
                                itemName=r.itemName,
                                itemLink=r.itemLink,
                                itemReview=r.itemReview,
                                itemSize=r.itemSize,
                                itemPic=r.itemPic)
Ejemplo n.º 25
0
def new_post():
    form = PostForm()
    print("new_post")
    if form.validate_on_submit():
        new_post = Post()
        new_post.title = form.title.data
        new_post.text = form.text.data
        new_post.publish_date = datetime.datetime.now()
        user = User.objects(id=current_user.id).first()
        new_post.user = user
        new_post.save()

    return render_template('new.html', form=form)
Ejemplo n.º 26
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post has been created!', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html', title='New Post', form=form)
Ejemplo n.º 27
0
def post_article():
    params = request.get_json()
    print params
    post = Post(
        title=params['title'],
        text=params['text'],
        publish_able=params['publishable'],
        tag_id=params['tagId'])
    post.user_id = g.userId
    erps = copy.deepcopy(error_response)

    db.session.add(post)
    try:
        db.session.commit()
    except BaseException:
        erps['error'] = '新建错误'
        return json.dumps(erps)

    erps['success'] = True
    return json.dumps(erps)
Ejemplo n.º 28
0
    def test_follow_posts(self):
        # create four users
        u1 = User(username='******', email='*****@*****.**')
        u2 = User(username='******', email='*****@*****.**')
        u3 = User(username='******', email='*****@*****.**')
        u4 = User(username='******', email='*****@*****.**')
        db.session.add_all([u1, u2, u3, u4])

        # create four posts
        now = datetime.utcnow()
        p1 = Post(body="post from john",
                  author=u1,
                  timestamp=now + timedelta(seconds=1))
        p2 = Post(body="post from susan",
                  author=u2,
                  timestamp=now + timedelta(seconds=4))
        p3 = Post(body="post from mary",
                  author=u3,
                  timestamp=now + timedelta(seconds=3))
        p4 = Post(body="post from david",
                  author=u4,
                  timestamp=now + timedelta(seconds=2))
        db.session.add_all([p1, p2, p3, p4])
        db.session.commit()

        # setup the followers
        u1.follow(u2)  # john follows susan
        u1.follow(u4)  # john follows david
        u2.follow(u3)  # susan follows mary
        u3.follow(u4)  # mary follows david
        db.session.commit()

        # check the followed posts of each user
        f1 = u1.followed_posts().all()
        f2 = u2.followed_posts().all()
        f3 = u3.followed_posts().all()
        f4 = u4.followed_posts().all()
        self.assertEqual(f1, [p2, p4, p1])
        self.assertEqual(f2, [p2, p3])
        self.assertEqual(f3, [p3, p4])
        self.assertEqual(f4, [p4])
Ejemplo n.º 29
0
def adding(data,time,room):
    print('adding',time)
    if len(Post.query.filter_by(room=room).all())>100:
        print("\ndeleting####\n",len(Post.query.filter_by(room=room).all()))
        val=Post.query.filter_by(room=room).first()
        print(val)
        db.session.delete(val)
        db.session.commit()
    val = Post(date_posted=time,content=str(data),room=room)
    # print(">>>>>",val)
    db.session.add(val)
    db.session.commit()
Ejemplo n.º 30
0
def editormd():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(text=form.text.data,
                    title=form.title.data,
                    subtitle=form.subtitle.data,
                    user=current_user._get_current_object(),
                    publish_date=datetime.now())
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('main.index'))
    return render_template('post/editormd.html',
                           form=form,
                           backgroundpic='/static/img/post-bg.jpg')
Ejemplo n.º 31
0
def setup_db():
    db.create_all()

    admin_role = Role()
    admin_role.name = "admin"
    admin_role.description = "admin"
    db.session.add(admin_role)

    default_role = Role()
    default_role.name = "default"
    default_role.description = "default"
    db.session.add(default_role)

    admin = User()
    admin.username = "******"
    admin.set_password("password")
    admin.roles.append(admin_role)
    admin.roles.append(default_role)
    db.session.add(admin)

    tag_one = Tag('Python')
    tag_two = Tag('Flask')
    tag_three = Tag('SQLAlechemy')
    tag_four = Tag('Jinja')
    tag_list = [tag_one, tag_two, tag_three, tag_four]

    s = "Body text"

    for i in xrange(100):
        new_post = Post("Post " + str(i))
        new_post.user = admin
        new_post.publish_date = datetime.datetime.now()
        new_post.text = s
        new_post.tags = random.sample(tag_list, random.randint(1, 3))
        db.session.add(new_post)

    db.session.commit()
Ejemplo n.º 32
0
    def post(self, post_id=None):
        if post_id:
            abort(400)
        else:
            args = post_post_parser.parse_args(strict=True)
            username = args['username']
            password = args['password']
            user = User.query.filter_by(username=username).first()

            if not user:
                abort(401)

            if not user.check_password(password):
                abort(401)

            new_post = Post()
            new_post.user_id = user.id
            new_post.title = args['title']
            new_post.publish_date = datetime.datetime.now()
            new_post.text = args['text']

            if args['tags']:
                for t_title in args['tags']:
                    tag = Tag.query.filter_by(title=t_title).first()

                    # Add the tag if it exists. If not make a new tag.
                    if tag:
                        new_post.tags.append(tag)
                    else:
                        new_tag = Tag()
                        new_tag.title = t_title
                        new_post.tags.append(new_tag)

            db.session.add(new_post)
            db.session.commit()
            return new_post.id, 201
Ejemplo n.º 33
0
def setup_db():
    db.create_all()

    # 创建管理员角色
    admin_role = Role('admin')
    admin_role.description = 'admin'
    db.session.add(admin_role)
    # 创建默认角色
    default_role = Role('default')
    default_role.description = 'default'
    db.session.add(default_role)

    # 创建管理员用户信息
    admin = User('admin')
    admin.set_password('password')
    admin.roles.append(admin_role)
    admin.roles.append(default_role)
    db.session.add(admin)

    tag_one = Tag('Python')
    tag_two = Tag('Flask')
    tag_three = Tag('SQLAlchemy')
    tag_four = Tag('Jinja')
    tag_list = [tag_one, tag_two, tag_three, tag_four]

    s = 'Body text'

    for i in range(100):
        new_post = Post('Post %s' % i, s)
        new_post.user = admin
        new_post.publish_date = datetime.datetime.now()
        new_post.tags = random.sample(tag_list, random.randint(1, 3))

        db.session.add(new_post)

    db.session.commit()
Ejemplo n.º 34
0
    def post(self, post_id=None):
        if post_id:  # 为啥要设置这条件?
            abort(400)
        else:
            args = post_post_parser.parse_args(strict=True)  # ?
            user = User.verify_auth_token(args['token'])
            if not user:
                abort(401)
            new_post = Post(args['title'], args['text'])  # 新建post对象
            new_post.date = datetime.datetime.now()
            new_post.author = user

            if args['tags']:
                for item in args['tags']:
                    tag = Tag.query.filter_by(title=item).first()
                    if tag:  # 如果数据库已经存在该tag,那就直接添加到新post中
                        new_post.tags.append(tag)
                    else:  # 不然要新建了再添加
                        new_tag = Tag(item)
                        new_post.tags.append(new_tag)

        db.session.add(new_post)
        db.session.commit()
        return new_post.id, 201
Ejemplo n.º 35
0
def create_article():
    if request.method == 'POST':
        title = request.form['title']
        header = request.form['header']
        text = request.form['text']
        post_creation_date = datetime.datetime.utcnow()
        post = Post(title=title,
                    header=header,
                    text=text,
                    post_creation_date=post_creation_date)
        try:
            db.session.add(post)
            db.session.commit()
            return redirect(url_for('.edit_articles'))
        except:
            return 'Error'
    else:
        return render_template('/admin/create-articles.html')
Ejemplo n.º 36
0
def post(post_id):
    form = CommentForm()
    post = Post.objects(id=post_id).get_or_404()
    if form.validate_on_submit():
        new_comment = Comment()
        new_comment.name = form.name.data
        new_comment.text = form.text.data
        new_comment.date = datetime.datetime.now()
        post.comments.append(new_comment)
        post.save()
    tags = post.tags
    comments = post.comments

    return with_sidebar_render('post.html',
                               post=post,
                               tags=tags,
                               comments=comments,
                               form=form)
Ejemplo n.º 37
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    post_image_file=form.picture_file.data,
                    author=current_user)
        if form.picture_file.data:
            post_image_file = save_picture_post(form.picture_file.data)
            current_user.image_file = post_image_file
        db.session.add(post)
        db.session.commit()
        flash('Your post has been created', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html',
                           title='New Post',
                           form=form,
                           legend='New Post')
Ejemplo n.º 38
0
def edit_post(id):
    post = Post.objects(id=id).get_or_404()
    permission = Permission(UserNeed(post.user.id))

    if (permission.can() or admin_permission.can()):
        form = PostForm()

        if form.validate_on_submit():
            post.title = form.title.data
            post.text = form.text.data
            post.publish_date = datetime.datetime.now()

            post.save()

            return redirect(url_for('.post', post_id=post.id))

        form.text.data = post.text
        return render_template('edit.html', form=form, post=post)
    abort(403)