Example #1
0
def create_post():
    """Create new post."""
    if is_admin():
        current_app.logger.info("An admin started creating a new post")
        form = CreatePostForm()
        if form.validate_on_submit():
            post = Post(
                title=form.title.data,
                body=form.body.data,
                private=form.private.data,
                author=current_user,
            )
            current_app.logger.info("New post created")
            db.session.add(post)
            db.session.commit()
            current_app.logger.info(f"Post {post.id} pushed to database")
            current_app.logger.info(
                f"Post {post.id} has been created by user {current_user.id}")
            flash("Post created.")
            return redirect(url_for("index.index"))
        return render_template("blog/create_post.html", form=form, post=None)
    else:
        current_app.logger.warning(
            f"User {current_user.id} attempted creating a post, but was bounced back"
        )
        abort(500)
Example #2
0
	def test_string_representation(self):
		expected = "This is a title"
		p1 = Post(title=expected)
		actual = str(p1)
		print('Expected: ', expected)
		print('Result: ', actual)
		self.assertEqual(expected, actual)
Example #3
0
    def test_delete_category(self):
        category = Category(name='Tech')
        post = Post(title='test', category=category)
        db.session.add(category)
        db.session.add(post)
        db.session.commit()

        response = self.client.get(url_for('admin.delete_category',
                                           category_id=1),
                                   follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertNotIn('Category deleted.', data)
        self.assertIn('405 Method Not Allowed', data)

        response = self.client.post(url_for('admin.delete_category',
                                            category_id=1),
                                    follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn('You can not delete the default category.', data)
        self.assertNotIn('Category deleted.', data)
        self.assertIn('Default', data)

        response = self.client.post(url_for('admin.delete_category',
                                            category_id=2),
                                    follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn('Category deleted.', data)
        self.assertIn('Default', data)
        self.assertNotIn('Tech', data)
Example #4
0
def new_post():
    form = PostForm()

    if form.validate_on_submit():
        title = form.title.data
        subtitle = form.subtitle.data
        theme = request.files.getlist('image')[0].filename
        body = form.body.data
        category = Category.query.get(form.category.data)
        topic = Topic.query.get(form.topic.data)
        post = Post(title=title,
                    subtitle=subtitle,
                    theme=theme,
                    body=body,
                    category=category,
                    topic=topic)
        # same with:
        # category_id = form.category.data
        # post = Post(title=title, body=body, category_id=category_id)
        db.session.add(post)
        db.session.commit()

        img_list = request.files.getlist('image')
        img_path = current_app.root_path + '/static/img/' + str(topic.name)
        if img_list[0].filename:

            for f in img_list:
                filename = f.filename
                f.save(os.path.join(img_path, filename))

        flash('Post created.', 'success')
        return redirect(url_for('blog.show_post', post_id=post.id))

    return render_template('admin/new_post.html', form=form)
Example #5
0
    def test_new_category(self):
        response = self.client.get(url_for('admin.new_category'))
        data = response.get_data(as_text=True)
        self.assertIn('New Category', data)

        response = self.client.post(url_for('admin.new_category'),
                                    data=dict(name='Tech'),
                                    follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn('Category created.', data)
        self.assertIn('Tech', data)

        response = self.client.post(url_for('admin.new_category'),
                                    data=dict(name='Tech'),
                                    follow_redirects=True)
        data = response.get_data(as_text=True)
        self.assertIn('Name already in use.', data)

        category = Category.query.get(1)
        post = Post(title='Post Title', category=category)
        db.session.add(post)
        db.session.commit()
        response = self.client.get(url_for('blog.show_category',
                                           category_id=1))
        data = response.get_data(as_text=True)
        self.assertIn('Post Title', data)
Example #6
0
def new_post():
    form = UploadForm()
    if form.validate_on_submit():
        file = form.post.data
        content = file.read().decode('utf-8')
        yaml_config = yaml.load(content.split("---")[1].replace('\t', ' '))
        title = yaml_config.get('title')
        body = markdown.markdown(''.join(content.split("---")[2:]),
                                 extensions=['markdown.extensions.extra', 'markdown.extensions.codehilite',
                                             'markdown.extensions.tables', 'markdown.extensions.toc'])

        category_name = yaml_config.get('category')[0]
        category_exist = Category.query.filter_by(name=category_name).first()
        if category_exist:
            category = Category.query.get(category_exist.id)
        else:
            category = Category(name=category_name)
            db.session.add(category)
            db.session.commit()
        post = Post(title=title, body=body, category=category)
        db.session.add(post)
        db.session.commit()
        flash('Post created.', 'success')
        return redirect(url_for('blog.show_post', post_id=post.id))
    return render_template('admin/new_post.html', form=form)
Example #7
0
def fake_posts(count=50):
    for i in range(count):
        post = Post(title=fake.sentence(),
                    body=fake.text(2000),
                    category=Category.query.get(
                        random.randint(1, Category.query.count())))
        db.session.add(post)
    db.session.commit()
Example #8
0
def fake_posts(count=50):                   # 生成虚拟文章
    for i in range(count):
        post=Post(title=fake.sentence(),
                  body=fake.text(2000),
                  category=Category.query.get(random.randint(1,Category.query.count())),
                  timestamp=fake.date_time_this_year()
                  )
        db.session.add(post)
    db.session.commit()
Example #9
0
 def setUp(self):
     self.now = datetime.datetime.utcnow().replace(tzinfo=utc)
     self.timedelta = datetime.timedelta(15)
     author = User.objects.get(pk=1)
     for count in range(1, 11):
         post = Post(title=f"Post {count} Title", text="foo", author=author)
         if count < 6:
             pubdate = self.now - self.timedelta * count
             post.published_date = pubdate
         post.save()
Example #10
0
 def setUp(self):
     self.now = datetime.datetime.utcnow().replace(tzinfo=utc)
     self.timedelta = datetime.timedelta(15)
     author = User.objects.get(pk=1)
     for count in range(1, 11):
         post = Post(title="Post %d Title" % count,
                     text="foo",
                     author=author,
                     published_date=self.now)
         post.save()
Example #11
0
    def setUp(self):
        super(AdminTestCase, self).setUp()
        self.login()

        category = Category(name='Default')
        post = Post(title='Hello', category=category, body='Blah...')
        comment = Comment(body='A comment', post=post, from_admin=True)
        link = Link(name='GitHub', url='https://github.com/greyli')
        db.session.add_all([category, post, comment, link])
        db.session.commit()
Example #12
0
    def setUp(self) -> None:
        super().setUp()
        self.login()

        category = Category(name="Default")
        post = Post(title="Hello", category=category, body="Blah...")
        comment = Comment(body="A comment", post=post, from_admin=True)
        link = Link(name="GitHub", url="https://github.com/greyli")
        db.session.add_all([category, post, comment, link])
        db.session.commit()
Example #13
0
def fake_posts(count=50):
    for i in range(count):
        post = Post(
            title=fake.word(),
            body=fake.text(),
            timestamp=fake.date_time_this_year(),
            category=Category.query.get(random.randint(1, Category.query.count())),
            can_comment=random.randint(0, 1) > 0,
        )
        db.session.add(post)
    db.session.commit()
Example #14
0
def create_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data.capitalize(),
                    body=form.body.data,
                    user_id=current_user.id,
                    tags=gettags(form.tags.data))
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('posts.index'))
    return render_template('post/create-post.html', form=form)
Example #15
0
 def setUp(self):
     self.now = datetime.datetime.utcnow().replace(tzinfo=utc)
     self.timedelta = datetime.timedelta(15)
     author = User.objects.get(pk=1)
     for count in range(1, 11):
         post = Post(title='Post %d Title' % count, text='foo', author=author)
         if count < 6:
             #publish the first five posts
             pubdate = self.now - self.timedelta * count
             post.published_date = pubdate
         post.save()
Example #16
0
 def setUp(self):
     self.now = datetime.datetime.utcnow().replace(tzinfo=utc)
     self.timedelta = datetime.timedelta(15)
     author = User.objects.get(pk=1)
     genre1 = Genre(genre="poetry")
     genre1.save()
     for count in range(1, 11):
         post = Post(title="Post %d Title" % count,
                     text="foo",
                     author=author,
                     genre=genre1)
         post.save()
Example #17
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        title = form.title.data
        body = form.body.data
        category = Category.query.get(form.category.data)
        post = Post(title=title, body=body, category=category)
        db.session.add(post)
        db.session.commit()
        flash("post created", "success")
        return redirect(url_for("blog.show_post", post_id=post.id))
    return render_template("admin/new_post.html", form=form)
Example #18
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        title = form.title.data
        category = Category.query.get(form.category.data)
        body = form.body.data
        post = Post(title=title, category=category, body=body)
        db.session.add(post)
        db.session.commit()
        flash('文章已创建', 'success')
        return redirect(url_for('blog.show_post', post_id=post.id))
    return render_template('admin/new_post.html', form=form)
Example #19
0
def fake_posts(count=50):
    """生成虚拟文章"""
    for i in range(count):
        post = Post(
            title=fake.sentence(),
            body=fake.text(2000),
            timestamp=fake.date_time_this_year(),
            # 每一篇文章指定一个随机分类,主键值为1到所有分类数量之间的随机值
            category=Category.query.get(
                random.randint(1, Category.query.count())))
        db.session.add(post)
    db.session.commit()
Example #20
0
def create_post():
    """Create new post."""
    form = CreatePostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    body=form.body.data,
                    private=form.private.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Post created.')
        return redirect(url_for('index.index'))
    return render_template('blog/create_post.html', form=form, post=None)
Example #21
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('main.home'))
    return render_template('create_post.html',
                           title='New Post',
                           form=form,
                           legend='New Post')
Example #22
0
def fake_posts(count=50):
    tags_count = Tag.query.count()

    for i in range(count):
        tags_indexs = random.sample(range(1, tags_count+1), 2)
        post = Post(
            title=fake.sentence(),
            body=fake.text(2000),
            category=Category.query.get(random.randint(1, Category.query.count())),
            tags=[Tag.query.get(tags_indexs[0]),Tag.query.get(tags_indexs[1])],
            timestamp=fake.date_time_this_decade()
        )
        db.session.add(post)
    db.session.commit()
Example #23
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        title = form.title.data
        body = form.body.data
        private = form.private.data
        # category = Category.query.get(form.category.data)
        categories = [Category.query.get(i) for i in form.categories.data]
        post = Post(title=title, body=body, private=private, categories=categories)
        db.session.add(post)
        db.session.commit()
        flash("Post created.", "success")
        return redirect(url_for("blog.show_post", post_id=post.id))
    return render_template("admin/new_post.html", form=form)
Example #24
0
 def setUp(self):
     self.now = datetime.datetime.utcnow().replace(tzinfo=utc)
     self.timedelta = datetime.timedelta(15)
     author = User.objects.get(pk=1)
     for count in range(1, 11):
         title = "Post %d Title" % count
         # print("NEXT TITLE:", title)
         post = Post(title="Post %d Title" % count,
             text="foo",
             author=author)
         if count < 6:
             # print("setting published date") # create 5 records with a published date
             pubdate = self.now - self.timedelta * count
             post.published_date = pubdate 
         post.save()
Example #25
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        title = form.title.data
        body = form.body.data
        category = Category.query.get(form.category.data)
        post = Post(title=title, body=body, category=category, read=1)
        # same with:
        # category_id = form.category.data
        # post = Post(title=title, body=body, category_id=category_id)
        db.session.add(post)
        db.session.commit()
        flash('Post created.', 'success')
        return redirect(url_for('blog.show_post', post_id=post.id))
    return render_template('admin/new_post.html', form=form)
Example #26
0
def create():
    form = CreateForm()
    if form.validate_on_submit():
        title = form.title.data
        body = form.body.data

        post = Post(title=title,
                    body=body,
                    author_id=g.user.id,
                    timestamp=time.strftime("%Y-%m-%d %H:%M:%S",
                                            time.localtime()))
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('blog.index'))
    return render_template('create.html', form=form)
Example #27
0
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        #save it into database
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user)
        db.session.add(post)
        db.session.commit()
        #end
        flash('your post has been creatd', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html',
                           title='Post',
                           form=form,
                           legend='Post')
Example #28
0
def fake_posts(count=50):
    for i in range(count):
        post = Post(
            title=fake.sentence(),
            body=fake.text(2000),
            # category=Category.query.get(random.randint(1, Category.query.count())),
            timestamp=fake.date_time_this_year(),
        )
        post.categories.extend(
            set(
                random.choices(
                    Category.query.all(),
                    k=random.randint(1,
                                     Category.query.count() // 3),
                )))
        db.session.add(post)
    db.session.commit()
Example #29
0
    def setUp(self):
        super(BlogTestCase, self).setUp()
        self.login()

        category = Category(name='Default')
        topic = Topic(name="test")
        post = Post(title='Hello Post',
                    category=category,
                    topic=topic,
                    body='Blah...')
        comment = Comment(body='A comment',
                          post=post,
                          from_admin=True,
                          reviewed=True)
        link = Link(name='GitHub', url='https://github.com/syntomic')

        db.session.add_all([category, post, comment, link])
        db.session.commit()
Example #30
0
def add_post():
    title = request.json.get('title')
    body = request.json.get('body')
    html = request.json.get('html')
    timestamp = datetime.fromtimestamp(request.json.get('timestamp') / 1000)
    category_id = request.json.get('category_id')
    post = Post(title=title,
                body=body,
                timestamp=timestamp,
                category_id=category_id,
                html=html)
    db.session.add(post)
    db.session.commit()
    return jsonify(title=title,
                   body=body,
                   post_id=post.id,
                   category_id=category_id,
                   timestamp=timestamp,
                   html=html)