Validators now accept file content as string

This commit is contained in:
Yarninator 2024-08-05 13:48:47 +02:00
parent bd685cfa72
commit 22a1227ee2
4 changed files with 10 additions and 30 deletions

View file

@ -1,7 +1,7 @@
import re import re
from PIL import Image from PIL import Image
def is_valid_image(file_name): def is_valid_image(file_name: str = None, file_content: str = None):
try: try:
with Image.open(file_name) as img: with Image.open(file_name) as img:
img.verify() img.verify()
@ -10,13 +10,16 @@ def is_valid_image(file_name):
return False return False
def is_valid_svg(file_name): def is_valid_svg(file_name: str = None, file_content: str = None):
SVG_R = r'(?:<\?xml\b[^>]*>[^<]*)?(?:<!--.*?-->[^<]*)*(?:<svg|<!DOCTYPE svg)\b' SVG_R = r'(?:<\?xml\b[^>]*>[^<]*)?(?:<!--.*?-->[^<]*)*(?:<svg|<!DOCTYPE svg)\b'
SVG_RE = re.compile(SVG_R, re.DOTALL) SVG_RE = re.compile(SVG_R, re.DOTALL)
if file_name != None:
file_object = open(file_name, 'r') file_object = open(file_name, 'r')
file_contents = file_object.read() file_contents = file_object.read()
else:
file_contents = file_content
is_svg = SVG_RE.match(file_contents) is not None is_svg = SVG_RE.match(file_contents) is not None

View file

@ -5,7 +5,7 @@ import os
from src.classes import product_classes from src.classes import product_classes
from src.config import definitions from src.config import definitions
from validators import image_validator from shop_validators import image_validator
from src import data_connection from src import data_connection
app = FastAPI() app = FastAPI()
@ -39,6 +39,6 @@ def get_single_product(barcode: int):
def get_icon(icon_filename: str): def get_icon(icon_filename: str):
full_filepath = os.path.join(definitions.ICONS_PATH, icon_filename) + ".svg" full_filepath = os.path.join(definitions.ICONS_PATH, icon_filename) + ".svg"
assert os.path.exists(full_filepath), f"File {full_filepath} not found" assert os.path.exists(full_filepath), f"File {full_filepath} not found"
assert image_validator.is_valid_svg(full_filepath), f"File {full_filepath} is not a valid image" assert image_validator.is_valid_svg(file_name=full_filepath), f"File {full_filepath} is not a valid image"
return full_filepath return full_filepath

View file

View file

@ -1,23 +0,0 @@
import re
from PIL import Image
def is_valid_image(file_name):
try:
with Image.open(file_name) as img:
img.verify()
return True
except (IOError, SyntaxError):
return False
def is_valid_svg(file_name):
SVG_R = r'(?:<\?xml\b[^>]*>[^<]*)?(?:<!--.*?-->[^<]*)*(?:<svg|<!DOCTYPE svg)\b'
SVG_RE = re.compile(SVG_R, re.DOTALL)
file_object = open(file_name, 'r')
file_contents = file_object.read()
is_svg = SVG_RE.match(file_contents) is not None
return is_svg