コード例 #1
0
    def put(self, pid):
        comment = PostModel.find_one_by(id=pid, user_id=current_user.id)
        form = PostForm(meta=dict(csrf=False))
        if comment:
            if form.validate():
                _form = form.form
                # 图片字段不存在时候,NoneType类型无法更新,所以先删除
                del _form['image']

                image = request.files.get('image')
                if image:
                    filename = hash_filename(image.filename)
                    if not uploader.file_allowed(image, filename):
                        raise UploadNotAllowed('file type not allow')
                    path = uploader.save(storage=image,
                                         folder=str(comment.id),
                                         name=filename)
                    print('path ->', path)
                    # 获得对应到文件夹路径
                    url = uploader.url(path)
                    _form['image'] = url

                comment.update(commit=False, **_form)
                db.session.add(comment)
                db.session.commit()
                return dict(code=200, msg='success', data=comment.asdict())
            else:
                return dict(code=400, msg='form validate failure', data=None)
        else:
            return dict(code=404, msg='not found', data=None)
コード例 #2
0
def index():
    form = PostForm(request.form)
    if form.validate():
        time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
        post = Post(body=form.post.data, title=form.title.data, timestamp=time)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('index'))
    posts = Post.query.all()
    return render_template("index.html",
                           posts=posts, form=form)
コード例 #3
0
def posts():
    post = PostForm()
    if request.method == 'POST' and post.validate():
        title = post.title.data
        content = post.content.data
        user_id = current_user.id
        print('\n', title, content)
        post = Post(title, content, user_id)

        # db.session.add(post,posts)
        db.session.add(post)
        db.session.commit()
        return redirect(url_for('posts'))
    return render_template('posts.html', post=post)
コード例 #4
0
    def post(self, user):
        # grab the form
        form = PostForm(self.request.params)

        # check if the person exists in the db or not
        try:
            user = Key("User", lower(user)).get()
        except:
            user = None

        # shouldn't be None if we got this far
        # but check anyway
        if user is None:
            self.invalidate_sig()
            self.redirect('/user/login')
            return

        # validate form
        if not form.validate():
            self.r(form)
            return

        # validate csrf
        if not self.validate_csrf(form.csrf_token.data):
            form.csrf_token.data = self.generate_csrf()
            self.r(form, flashes=flash('Please submit the form again.'))
            return

        t = form.title.data

        try:
            # let's create the post
            post = Post(
                title=t,
                author=user.username,
                author_lower=lower(user.username),
                subject=form.subject.data,
                content=form.content.data
            )
            post.put()
            # maybe they want to create another post?
            self.r(PostForm(data={'csrf_token': self.generate_csrf()}),
                   flashes=flash('Your new post can be viewed <a href="/post/view?key=%s">here</a>.' % post.key.urlsafe(), 'success'))
            return
        except Exception as e:
            # give them another chance
            form.csrf_token.data = self.generate_csrf()
            self.r(form)
            return
コード例 #5
0
def post_update(id):
    post = Post.query.get_or_404(id)
    form = PostForm(obj=post)
    if request.method == 'POST' and form.validate():
        post.title = form.title.data
        post.body = form.body.data
        db.session.add(post)
        db.session.commit()
        flash("Successfully updated post")
        return redirect(url_for("post_detail", id=post.id))
    return render_template(
        "post_update.html",
        post=post,
        form=form,
    )
コード例 #6
0
def post_create():

    form = PostForm()
    if request.method == 'POST' and form.validate():
        new_post = Post(title=form.title.data,
                        body=form.body.data,
                        author=current_user)
        db.session.add(new_post)
        db.session.commit()
        flash('Post successfully created!')
        return redirect(url_for('posts_list'))

    return render_template(
        'post_create.html',
        form=form,
    )
コード例 #7
0
ファイル: views.py プロジェクト: maksad/fast_monkeys
def add_post():
	form = PostForm(request.form)
	if request.method == 'POST' and form.validate():
		existing_post = Post.query.filter_by(title=form.title.data).first()
		if existing_post:
			form.title.errors.append('Post with such title already exists')
		else:
			post = Post(form.title.data, 
				form.content.data, current_user.id, form.tags.data)
			db.session.add(post)
			db.session.commit()
			flash('Successfully added post')
			return redirect(url_for('show_post', post_id=post.id))

	return render_template('add_post.html', 
		form=form)
コード例 #8
0
def create_post():
    form = PostForm()
    if request.method == 'POST' and form.validate():
        new_post_author = form.author.data
        new_post_body = form.body.data

        new_post = {
            'author': new_post_author,
            'body': new_post_body,
        }
        posts.append(new_post)
        flash('Post successfully created!')
        return redirect(url_for('home'))

    return render_template(
        'create.html',
        form=form,
    )
コード例 #9
0
def post_update(post_id):
    post = Post.query.get_or_404(post_id)
    update_form = PostForm()
    if post.author.id != current_user.id:
        flash("You cannot update another user's post", 'danger')
        return redirect(url_for('myposts'))
    if request.method == 'POST' and update_form.validate():
        post_title = update_form.title.data
        content = update_form.content.data

        post.title = post_title
        post.content = content

        db.session.commit()
        flash("Your post has been updated.", 'info')
        return redirect(url_for('post_detail', post_id=post.id))

    return render_template('post_update.html', form=update_form, post=post)
コード例 #10
0
def requestpost():
    title = "Virtual Tour Mates | CREATE POST"
    post = PostForm()
    if request.method == 'POST' and post.validate():
        post_title = post.title.data
        content = post.content.data
        user_id = current_user.id
        
        new_post = Post(post_title, content, user_id)
        
        db.session.add(new_post)
        
        db.session.commit()
        
        flash("You have successfully created a post!", 'success')
        
        return redirect(url_for('requestpost'))
    return render_template('request_post.html', post=post, title=title)
コード例 #11
0
def post_update(post_id):
    post = Post.query.get_or_404(post_id)
    update_form = PostForm()

    if request.method == 'POST' and update_form.validate():
        title = update_form.title.data
        content = update_form.content.data
        user_id = current_user.id
        print(title, content, user_id)

        # Update will get added to the DB
        post.title = title
        post.content = content
        post.user_id = user_id

        db.session.commit()
        return redirect(url_for('post_update', post_id=post.id))
    return render_template('post_update.html', update_form=update_form)
コード例 #12
0
ファイル: routes.py プロジェクト: CristinaGradinaru/flaskDay1
def createposts():
    post = PostForm()
    title = 'Kekembas Blog | Create Post'
    if request.method =='POST' and post.validate():
        post_title = post.title.data
        content = post.content.data
        user_id = current_user.id
        # print(post_title, content)
        # create new post instance
        new_post = Post(post_title, content, user_id)
        # add new post instance to database
        db.session.add(new_post)
        # commit
        db.session.commit()
        # flash a message
        flash("You have blabla", "success")
        # redirect back to create post
        return redirect(url_for('createposts'))
    return render_template('create_post.html', post=post, title=title)
コード例 #13
0
ファイル: routes.py プロジェクト: FateFormedd/kekambas_flask
def createpost():
    title = "Kekambas Blog | CREATE POST"
    post = PostForm()
    if request.method == 'POST' and post.validate():
        post_title = post.title.data
        content = post.content.data
        user_id = current_user.id
        # print(post_title, content)
        # Create new Post instance
        new_post = Post(post_title, content, user_id)
        # Add new post instance to database
        db.session.add(new_post)
        # Commit
        db.session.commit()
        # flash a message
        flash("You have successfully created a post!", 'success')
        # redirect back to create post
        return redirect(url_for('createpost'))
    return render_template('create_post.html', post=post, title=title)
コード例 #14
0
    def post(self):
        form = PostForm(meta=dict(csrf=False))
        if form.validate():
            path = ''
            try:
                _form = form.form
                del _form['image']  # 文件对象不能直接放数据库,类型不一致
                m = PostModel.new(**_form,
                                  user_id=current_user.id,
                                  commit=False)

                # 先flush到数据库,获得ID,下面好根据ID存储文件,但是不提交事务,方便回退
                db.session.add(m)
                db.session.flush()

                image = request.files.get('image')
                if image:
                    filename = hash_filename(image.filename)
                    if not uploader.file_allowed(image, filename):
                        raise UploadNotAllowed('file type not allow')
                    path = uploader.save(storage=image,
                                         folder=str(m.id),
                                         name=filename)
                    # 获得对应到文件夹路径
                    url = uploader.url(path)
                    m.image = 'http://198.13.50.56' + url

                # 提交
                db.session.commit()

                return dict(code=200, msg='success', data=m.asdict())
            except Exception as e:
                _logger.exception(e)
                db.session.rollback()
                # 删除无用附件
                if path:
                    os.remove(pathlib.Path(uploader.config.destination) / path)
                return dict(code=500, msg=str(e), data=None)
        else:
            return form.errors
コード例 #15
0
ファイル: routes.py プロジェクト: henryho8012/flask
def index():
    form = PostForm(request.form)
    if form.validate():
        post = Post(body=form.post.data, author=current_user)
        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)
コード例 #16
0
ファイル: views.py プロジェクト: maksad/fast_monkeys
def edit_post(post_id):
	post = Post.query.get_or_404(post_id)
	if request.method == 'POST':
		form = PostForm(request.form)
		if form.validate():
			existing_post = Post.query.filter_by(title=form.title.data).first()
			if existing_post and existing_post.id != post.id:
				form.title.errors.append('Post with such title already exists')
			else:
				# form.populate_obj(post)
				post.title = form.title.data
				post.content = form.content.data
				print form.tags.data
				post.strings_2_tags(form.tags.data)
				post.short_content = post.content[:400]
				db.session.commit()
				flash('Successfully saved')
				return redirect(url_for('show_post', post_id=post.id))
	else:
		form = PostForm(obj=post)

	form.tags.data = ', '.join([str(t) for t in post.tags]) # list comprehension
	return render_template('edit_post.html', 
		form=form, post=post)
コード例 #17
0
ファイル: routes.py プロジェクト: javier-lopez/microblogging
def index(page=1):
    if current_user.is_authenticated:
        user = User.objects(email=current_user.email).first()
        posts = user.posts_from_following_users().paginate(
            page=page, per_page=items_per_page)
        # posts = user.posts_from_following_users()
    else:
        # app.logger.debug('index => user => None')
        user = None
        posts = Post.objects.paginate(page=page, per_page=items_per_page)

    form = PostForm()
    if request.method == 'POST' and form.validate():
        user = User.objects(email=current_user.email).first()
        post = Post(author=user, body=form.post.data).save()
        #force the browser to issue another request after the form submission
        #avoid untended duplicated posts on refresh actions
        return redirect(url_for('index'))

    return render_template("index.html.j2",
                           title='Inicio',
                           user=user,
                           posts=posts,
                           form=form)
コード例 #18
0
ファイル: blueprint.py プロジェクト: AlertRED/Flask-microblog
def create_post():
    form = PostForm(request.form)
    form.tags.choices = [(tag.id, tag.name) for tag in Tag.get()]
    if request.method == 'POST':
        if form.validate():
            title, body, timestamp = form['title'].data, form[
                'body'].data, form['timestamp'].data
            tags = [Tag.get_first(id=int(tag_id)) for tag_id in form.tags.data]
            try:
                Post.create(title=title,
                            body=body,
                            timestamp=timestamp,
                            tags=tags)
            except Exception as e:
                flash(str(e), 'alert')
            else:
                flash('Пост успешно выложен', 'success')
                return redirect(url_for('index'))
        else:
            flash('Не все поля заполнены', 'alert')
    return render_template('edit_post.html',
                           form=form,
                           title='Создание поста',
                           button='Создать')
コード例 #19
0
def index():
    form = PostForm()
    # tranForm = TransactionForm()
    if form.submit.data and form.validate():
        post = Post(body=form.post.data, author=current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your Post is now LIVE!')
        return redirect(url_for('index'))

    # if tranForm.submitTran.data and tranForm.validate():
    #     transaction = Transaction(
    #             author = current_user,
    #             amount = tranForm.amount.data,
    #             note = tranForm.note.data,
    #             type = tranForm.type.data)
    #     db.session.add(transaction)
    #     db.session.commit()
    #     flash('Recent Record Saved as, Transaction Amount {}, Type {}, date{} recorded'.format(tranForm.amount.data, tranForm.type.data, tranForm.date.data))
    #     return redirect(url_for('index'))
    user = {'username': '******'}
    # transactions = current_user.followed_transactions().all()
    posts = current_user.followed_posts().all()
    return render_template('index.html', title='Home Page', posts=posts, form=form)
コード例 #20
0
ファイル: test_tests.py プロジェクト: maksad/fast_monkeys
	def submit_post(self, tags):
		form = PostForm(title='test title', 
			content='test content', tags=tags)
		if form.validate():
			return form.tags.data