fix: uploading barcode pdf files instead of images

This commit is contained in:
2024-11-06 15:35:28 +04:00
parent 4f9d55d2c6
commit fced9b8101
4 changed files with 36 additions and 22 deletions

View File

@@ -30,21 +30,9 @@ class BarcodeImagesUploader(BaseImagesUploader):
file_location.unlink() file_location.unlink()
async def upload(self, upload_file: UploadFile) -> str: async def upload(self, upload_file: UploadFile) -> str:
# Create temp file in filesystem filename = str(uuid4()) + '.' + upload_file.filename.split('.')[-1]
temp_filename = str(uuid4()) + '.' + upload_file.filename.split('.')[-1] file_location = self.storage_path / filename
temp_file_location = self.storage_path / temp_filename with open(file_location, 'wb') as buffer:
with open(temp_file_location, 'wb') as buffer:
await copyfileobj(upload_file.file, buffer) await copyfileobj(upload_file.file, buffer)
# Generate PDF file and save it return filename
res_filename = str(uuid4()) + '.pdf'
res_file_location = f"{self.storage_path}/{res_filename}"
temp_file_url = f"{self.relative_path}/{temp_filename}"
pdf_gen = PDFGenerator()
pdf_gen.generate_barcode_image(temp_file_url, res_file_location)
# Remove temp file
self.delete(temp_filename)
return res_filename

View File

@@ -189,8 +189,3 @@ class PDFGenerator:
pdf_maker.add_pdfs(file) pdf_maker.add_pdfs(file)
return pdf_maker.get_bytes() return pdf_maker.get_bytes()
def generate_barcode_image(self, barcode_image_url: str, path_to_save_pdf: str):
c = canvas.Canvas(path_to_save_pdf, pagesize=(self.page_width, self.page_height))
c.drawImage(barcode_image_url, 0, 0, width=self.page_width, height=self.page_height)
c.save()

View File

@@ -1,7 +1,11 @@
from io import BytesIO from io import BytesIO
from typing import BinaryIO
from fpdf import FPDF from fpdf import FPDF
import pdfrw import pdfrw
from pdfrw import PdfReader
from pdfrw.objects.pdfdict import PdfDict
class PdfMaker: class PdfMaker:
def __init__(self, size: tuple): def __init__(self, size: tuple):
@@ -36,3 +40,29 @@ class PdfMaker:
self.writer.write(result_io) self.writer.write(result_io)
result_io.seek(0) result_io.seek(0)
return result_io return result_io
@staticmethod
def check_is_correct_aspects_ratio(file: BinaryIO):
pdf = PdfReader(file)
allowed_aspects_ratio = 1.45
page: PdfDict
try:
page: PdfDict = pdf.getPage(0)
except IndexError:
raise Exception("Ошибка. В документе нет страниц.")
try:
pdf.getPage(1)
raise Exception("Ошибка. В документе должна быть только одна страница.")
except IndexError:
pass
media_box = page.MediaBox
width = float(media_box[2]) - float(media_box[0])
height = float(media_box[3]) - float(media_box[1])
aspect_ratio = width / height
if abs(aspect_ratio - allowed_aspects_ratio) > 0.01:
raise Exception("Ошибка. Страница документа должна быть размером 58х40.")
file.seek(0)

View File

@@ -7,6 +7,7 @@ from sqlalchemy.orm import selectinload, Query
import utils.barcodes import utils.barcodes
from backend import config from backend import config
from barcodes.images_uploader import BarcodeImagesUploader from barcodes.images_uploader import BarcodeImagesUploader
from barcodes.pdf.pdf_maker import PdfMaker
from external.s3_uploader.uploader import S3Uploader from external.s3_uploader.uploader import S3Uploader
from models.product import Product, ProductImage, ProductBarcodeImage from models.product import Product, ProductImage, ProductBarcodeImage
from schemas.base import PaginationSchema from schemas.base import PaginationSchema
@@ -277,6 +278,7 @@ class ProductService(BaseService):
async def upload_barcode_image(self, product_id: int, upload_file: UploadFile) -> ProductUploadBarcodeImageResponse: async def upload_barcode_image(self, product_id: int, upload_file: UploadFile) -> ProductUploadBarcodeImageResponse:
try: try:
PdfMaker.check_is_correct_aspects_ratio(upload_file.file)
await self.get_model_by_id(product_id) await self.get_model_by_id(product_id)
uploader = BarcodeImagesUploader() uploader = BarcodeImagesUploader()
@@ -296,7 +298,6 @@ class ProductService(BaseService):
barcode_image_url=barcode_image_url, barcode_image_url=barcode_image_url,
) )
except Exception as e: except Exception as e:
print(e)
return ProductUploadBarcodeImageResponse(ok=False, message=str(e)) return ProductUploadBarcodeImageResponse(ok=False, message=str(e))
async def delete_barcode_image(self, product_id: int) -> ProductDeleteBarcodeImageResponse: async def delete_barcode_image(self, product_id: int) -> ProductDeleteBarcodeImageResponse: