示例#1
0
def post_by_id(post_id):
    post = Post.query.get(post_id)
    if request.method == "GET":
        return post.to_dict()
    elif request.method == "PUT":
        form = CreatePost()
        if form.validate_on_submit():
            form.populate_obj(post)
            db.session.commit()

            if "images" in request.files:
                images = request.files.getlist("images")
                for image in images:
                    if allowed_file(image.filename):
                        image.filename = get_unique_filename(image.filename)
                        image_url = upload_file_to_s3(image, Config.S3_BUCKET)
                        image = PostsImage(post_id=post.id,
                                           image_url=image_url)
                        db.session.add(image)
                db.session.commit()
            return post.to_dict()
        return {"errors": validation_errors_to_error_messages(form.errors)}
    elif request.method == "DELETE":
        post.title = "[DELETED]"
        post.body = "[DELETED]"
        posts_images = PostsImage.query.filter(
            PostsImage.post_id == post_id).all()
        for image in posts_images:
            db.session.delete(image)
        db.session.commit()

        return post.to_dict()
    return post.to_dict()
示例#2
0
def create_post():
    form = CreatePost()
    if form.validate_on_submit():
        post = Post()
        form.populate_obj(post)
        db.session.add(post)
        db.session.commit()

        if "images" in request.files:
            images = request.files.getlist("images")
            for image in images:
                if allowed_file(image.filename):
                    image.filename = get_unique_filename(image.filename)
                    image_url = upload_file_to_s3(image, Config.S3_BUCKET)
                    image = PostsImage(post_id=post.id, image_url=image_url)
                    db.session.add(image)
            db.session.commit()
        return post.to_dict()
    return {"errors": validation_errors_to_error_messages(form.errors)}