Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- '''API to using CRUD operations on images in React frontend.'''
- from flask import Blueprint, request, jsonify, abort
- from flask_jwt_extended import jwt_required, get_jwt_identity
- from app.models import User, Image
- from app import db
- from werkzeug.utils import secure_filename
- import os
- import uuid
- from datetime import datetime
- images = Blueprint('images', __name__, url_prefix='/api/v1/images')
- '''Create empty folder on server for images.'''
- if not os.path.exists('app/static/images'):
- os.makedirs('app/static/images')
- @images.route('/', methods=['GET'])
- @jwt_required
- def get_images():
- '''Get all images from database.'''
- images = Image.query.all()
- return jsonify([image.serialize() for image in images]), 200
- @images.route('/<int:image_id>', methods=['GET'])
- @jwt_required
- def get_image(image_id):
- '''Get image by id from database.'''
- image = Image.query.get(image_id)
- if not image:
- abort(404)
- return jsonify(image.serialize()), 200
- @images.route('/', methods=['POST'])
- @jwt_required
- def create_image():
- '''create image in database and upload to server using upload method
- in models.image.'''
- data = request.get_json()
- if not data:
- abort(400)
- image = Image(
- name=data.get('name'),
- mimetype=data.get('mimetype'),
- user_id=get_jwt_identity()
- )
- '''using upload method in models.image.'''
- image.name = image.upload(request.files['image'])
- db.session.add(image)
- db.session.commit()
- return jsonify(image.serialize()), 201
- @images.route('/<int:image_id>', methods=['PUT'])
- @jwt_required
- def update_image(image_id):
- '''Update image in database.'''
- data = request.get_json()
- if not data:
- abort(400)
- image = Image.query.get(image_id)
- if not image:
- abort(404)
- if image.user_id != get_jwt_identity():
- abort(403)
- image.name = data.get('name', image.name)
- image.mimetype = data.get('mimetype', image.mimetype)
- image.updated_at = datetime.utcnow()
- db.session.commit()
- return jsonify(image.serialize()), 200
- @images.route('/<int:image_id>', methods=['DELETE'])
- @jwt_required
- def delete_image(image_id):
- '''Delete image from database and server.'''
- image = Image.query.get(image_id)
- if not image:
- abort(404)
- if image.user_id != get_jwt_identity():
- abort(403)
- '''Delete image from server.'''
- os.remove(os.path.join('app/static/images', image.name))
- '''Delete image from database.'''
- db.session.delete(image)
- db.session.commit()
- return jsonify(image.serialize()), 200
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement