Exemplo n.º 1
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(_l('Successfully write a post!'))
        return redirect(
            url_for('main.index')
        )  # 标准写法,需要重定向,而不是通过render_template返回index页面,可以减少浏览器刷新,否则刷新浏览器就会提示重新提交表单
    page = request.args.get('page', 1, type=int)
    posts = current_user.followed_posts().paginate(
        page, current_app.config['POST_PER_PAGE'],
        False)  # 查询当前用户关注的人以及自己的post .paginate(1,20,False)分页查询
    # 超过页码返回empty-False 否则返回404-True
    next_url = url_for(
        'main.index', page=posts.next_num
    ) if posts.has_next else None  # Pagination对象其他有用方法:has_next、has_prev、next_num、prev_num
    prev_url = url_for(
        'main.index', page=posts.prev_num
    ) if posts.has_prev else None  # url_for可以任意添加关键字参数,不在路径中Flask会自动变成query参数
    return render_template('index.html',
                           title='Home',
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url)
Exemplo n.º 2
0
def dashboard():
    form = PostForm()

    if form.validate_on_submit():
        # for automatic language translation... to be implemented
        language = guess_language(form.post.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ''
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash(_('Your post is now live!'), 'info')
        return redirect(url_for('main.dashboard'))

    # implement pagination in the dasboard page
    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('main.dashboard',
                       page=posts.next_num) if posts.has_next else None
    prev_url = url_for('main.dashboard',
                       page=posts.prev_num) if posts.has_prev else None

    return render_template('dashboard.html',
                           title=_('Dashboard'),
                           form=form,
                           posts=posts.items,
                           next_url=next_url,
                           prev_url=prev_url)
Exemplo n.º 3
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])
Exemplo n.º 4
0
def create_post(payload):
    try:
        post = Post(
            title=payload['title'],
            body=payload['body'],
            author=payload['user']
        )
        db.session.add(post)
        db.session.commit()
        db.session.remove()
        return {'status': 'success'}
    except IntegrityError as e:
        return {'status': 'fail', 'message': e}
Exemplo n.º 5
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')
Exemplo n.º 6
0
def search():
    if not g.search_form.validate():
        return redirect(url_for('main.explore'))
    page = request.args.get('page', 1, type=int)
    posts, total = Post.search(g.search_form.q.data, page,
                               current_app.config['POSTS_PER_PAGE'])
    next_url = url_for('main.search', q=g.search_form.q.data, page=page + 1) \
        if total['value'] > page * current_app.config['POSTS_PER_PAGE'] else None
    prev_url = url_for('main.search', q=g.search_form.q.data, page=page -
                       1) if page > 1 else None
    return render_template('search.html',
                           title=_('Search'),
                           posts=posts,
                           next_url=next_url,
                           prev_url=prev_url)
Exemplo n.º 7
0
import json
import random
import time
from blog_app.models import Post
# from django.contrib.auth.models import User

with open('posts.json') as f:
    posts_json = json.load(f)

for post in posts_json:
    post = Post(title=post['title'], content=post['content'], author_id="1")
    post.save()
Exemplo n.º 8
0
from base import Session, engine, Base

from blog_app.models import User, Post

Base.metadata.create_all(engine)

session = Session()

admin_user = User('admin', '*****@*****.**', hash('default'))

first_post = Post(body='My First Post Body',
                  user_id=1,
                  title='My first Post title')

session.add(admin_user)
session.add(first_post)

session.commit()
session.close()
Exemplo n.º 9
0
def create_blogposts(number_of_objects):
    fake = Faker()

    for i in range(number_of_objects):

        number_of_symbols = random.randint(3000, 7000)

        sentences_list = fake.text(number_of_symbols).split('\n')
        sentences_list_len = len(sentences_list)

        index = 0
        min_linebreak_index = 9
        max_linebreak_index = 14
        while index < sentences_list_len - max_linebreak_index - 1:
            linebreak_index = random.randint(min_linebreak_index, max_linebreak_index)
            linebreak_index += random.randint(-2, 2)

            sentences_list.insert(index + linebreak_index, '\n\n')

            index += linebreak_index

            if index > sentences_list_len:
                break

        text = ''.join(sentences_list)

        with open('scripts/taglines', 'r') as reader:
            list_of_tags = reader.read().split('\n')

        number_of_tags = random.randint(0, 10)

        random.shuffle(list_of_tags)
        tags = random.sample(list_of_tags, number_of_tags)

        title = fake.sentence(nb_words=7)

        User = get_user_model()

        users = User.objects.all()

        while True:
            user = random.choice(users)
            if user.is_staff:
                continue
            break

        slug = slugify('{}-{}-{}'.format(
            title,
            user.username,
            datetime.datetime.now().strftime('%Y-%m-%d'))
        )
        while Post.objects.filter(slug=slug).exists():
            slug = '{}-{}'.format(slug, get_random_string(length=2))

        post = Post()
        post.title = title
        post.content = text
        post.author = user
        post.status = random.randint(0, 1)
        post.slug = slug
        post.save()

        list_of_tags = []
        for tag in tags:
            list_of_tags.append(Tag.objects.get_or_create(tagline=tag)[0])

        post.tags.add(*list_of_tags)