[pricelist][picture] delete picture, if not found

This commit is contained in:
Tim Gröger 2021-03-28 12:47:02 +02:00
parent 6fce88c120
commit 2ae8bc7e0c
4 changed files with 37 additions and 30 deletions

View File

@ -6,12 +6,13 @@ from http.client import NO_CONTENT
from flaschengeist.plugins import Plugin from flaschengeist.plugins import Plugin
from flaschengeist.utils.decorators import login_required from flaschengeist.utils.decorators import login_required
from werkzeug.exceptions import BadRequest, Forbidden from werkzeug.exceptions import BadRequest, Forbidden
from flaschengeist.config import config
from . import models from . import models
from . import pricelist_controller, permissions from . import pricelist_controller, permissions
from ...controller import userController from ...controller import userController
from ...models.session import Session from ...models.session import Session
from ...utils.HTTP import no_content, created from ...utils.HTTP import no_content
pricelist_bp = Blueprint("pricelist", __name__, url_prefix="/pricelist") pricelist_bp = Blueprint("pricelist", __name__, url_prefix="/pricelist")
@ -221,14 +222,6 @@ def get_columns(userid, current_session: Session):
@pricelist_bp.route("/drinks/<int:identifier>/picture", methods=["POST", "GET", "DELETE"]) @pricelist_bp.route("/drinks/<int:identifier>/picture", methods=["POST", "GET", "DELETE"])
def set_picture(identifier): def set_picture(identifier):
if request.method == "GET":
try:
size = request.args.get("size")
response = pricelist_controller.get_drink_picture(identifier, size)
return response.make_conditional(request)
except FileNotFoundError:
return no_content()
if request.method == "DELETE": if request.method == "DELETE":
pricelist_controller.delete_drink_picture(identifier) pricelist_controller.delete_drink_picture(identifier)
return no_content() return no_content()
@ -238,8 +231,14 @@ def set_picture(identifier):
picture = models._Picture() picture = models._Picture()
picture.mimetype = file.content_type picture.mimetype = file.content_type
picture.binary = bytearray(file.stream.read()) picture.binary = bytearray(file.stream.read())
pricelist_controller.save_drink_picture(identifier, picture) return jsonify(pricelist_controller.save_drink_picture(identifier, picture))
else: else:
raise BadRequest raise BadRequest
return created() @pricelist_bp.route("/picture/<identifier>", methods=["GET"])
def _get_picture(identifier):
if request.method == "GET":
size = request.args.get("size")
path = config["pricelist"]["path"]
response = pricelist_controller.get_drink_picture(identifier, size)
return response.make_conditional(request)

View File

@ -137,7 +137,7 @@ class Drink(db.Model, ModelSerializeMixin):
cost_price_pro_volume: Optional[float] = db.Column(db.Numeric(precision=5, scale=3, asdecimal=False)) cost_price_pro_volume: Optional[float] = db.Column(db.Numeric(precision=5, scale=3, asdecimal=False))
cost_price_package_netto: Optional[float] = db.Column(db.Numeric(precision=5, scale=3, asdecimal=False)) cost_price_package_netto: Optional[float] = db.Column(db.Numeric(precision=5, scale=3, asdecimal=False))
uuid = db.Column(db.String(36)) uuid: str = db.Column(db.String(36))
_type_id = db.Column("type_id", db.Integer, db.ForeignKey("drink_type.id")) _type_id = db.Column("type_id", db.Integer, db.ForeignKey("drink_type.id"))

View File

@ -6,7 +6,7 @@ from flaschengeist.config import config
from flaschengeist.database import db from flaschengeist.database import db
from .models import Drink, DrinkPrice, Ingredient, Tag, DrinkType, DrinkPriceVolume, DrinkIngredient, ExtraIngredient from .models import Drink, DrinkPrice, Ingredient, Tag, DrinkType, DrinkPriceVolume, DrinkIngredient, ExtraIngredient
from flaschengeist.utils.picture import save_picture, get_picture, delete_picture, get_no_image from flaschengeist.utils.picture import save_picture, get_picture, delete_picture
from uuid import uuid4 from uuid import uuid4
@ -373,19 +373,32 @@ def delete_extra_ingredient(identifier):
def save_drink_picture(identifier, file): def save_drink_picture(identifier, file):
drink = get_drink(identifier) drink = get_drink(identifier)
if not drink.uuid: old_uuid = None
if drink.uuid:
old_uuid = drink.uuid
drink.uuid = str(uuid4()) drink.uuid = str(uuid4())
db.session.commit() db.session.commit()
path = config["pricelist"]["path"] path = config["pricelist"]["path"]
save_picture(file, f"{path}/{drink.uuid}") save_picture(file, f"{path}/{drink.uuid}")
if old_uuid:
delete_picture(f"{path}/{old_uuid}")
return drink
def get_drink_picture(identifier, size=None): def get_drink_picture(identifier, size=None):
drink = get_drink(identifier)
if not drink.uuid:
return get_no_image()
path = config["pricelist"]["path"] path = config["pricelist"]["path"]
return get_picture(f"{path}/{drink.uuid}") drink = None
if isinstance(identifier, int):
drink = get_drink(identifier)
if isinstance(identifier, str):
drink = Drink.query.filter(Drink.uuid==identifier).one_or_none()
try:
if drink:
return get_picture(f"{path}/{drink.uuid}", size)
except FileNotFoundError:
drink.uuid = None
db.session.commit()
raise FileNotFoundError
def delete_drink_picture(identifier): def delete_drink_picture(identifier):
drink = get_drink(identifier) drink = get_drink(identifier)

View File

@ -25,14 +25,6 @@ def save_picture(picture, path):
work_image.thumbnail(thumbnail_size) work_image.thumbnail(thumbnail_size)
work_image.save(f"{filename}-{thumbnail_size[0]}.png", "PNG") work_image.save(f"{filename}-{thumbnail_size[0]}.png", "PNG")
def get_no_image():
path = os.path.dirname(__file__)
with open(f"{path}/no-image.png", "rb") as file:
image = file.read()
response = Response(image, mimetype="image/png")
response.add_etag()
return response
def get_picture(path, size=None): def get_picture(path, size=None):
try: try:
if size: if size:
@ -51,10 +43,13 @@ def get_picture(path, size=None):
response.add_etag() response.add_etag()
return response return response
except: except:
get_no_image() raise FileNotFoundError
def delete_picture(path): def delete_picture(path):
try:
shutil.rmtree(path) shutil.rmtree(path)
except FileNotFoundError:
pass