Отправьте Zip в качестве ответа в рамках Django Rest [дубликат]Python

Программы на Python
Anonymous
Отправьте Zip в качестве ответа в рамках Django Rest [дубликат]

Сообщение Anonymous »

Я создаю штрих-коды в API-формате как в формате PNG, так и в формате PDF, а затем пытаюсь сжать их и отправить в ответ в виде zip-файла, для этого я делаю это:

Код: Выделить всё

class DownloadBarcodeImageAPIViewV2(APIView):
# permission_classes = (permissions.IsAuthenticated,)

def convert_image_to_pdf(self, image_path):
image = Image.open(image_path)
pdf_path = os.path.splitext(image_path)[0] + '.pdf'
image.convert('RGB').save(pdf_path)
return pdf_path

def get(self, request):
obj_relative_url = self.request.user.company.branding_logo.document
obj_url = obj_relative_url.url
po_id = request.GET['po']

company = request.user.company.pk
barcodes = CompanyBarcodes.objects.filter(
po_id=po_id,
company=company,
).prefetch_related('company', 'product', 'grn_id', 'asn_id', 'itemGroup')

items = []

for i in barcodes:
items.append({'bar': i.barcode, 'name': str(i.product.name) + " - " + str(i.product.sku)})

zip_buffer = io.BytesIO()  # Create a BytesIO buffer to hold the zip file

with zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED, False) as zipf:
for item in items:
EAN = barcode.get_barcode_class('code128')
d = {'module_width': 0.15,
'module_height': 2.0,
'quiet_zone': 0.5,
'text_distance': 1.5,
'font_size': 3,
'text_line_distance': 3,
'dpi': 900}
w = ImageWriter(d)
ean = EAN(item['bar'], writer=ImageWriter())
a = ean.save("{} - {}".format(item['name'], item['bar']), options=d)
pdf_path = self.convert_image_to_pdf(a)
zipf.write(pdf_path, os.path.basename(pdf_path))  # Add PDF to the zip file

zip_buffer.seek(0)  # Move the cursor to the beginning of the buffer
zip_data = base64.b64encode(zip_buffer.getvalue()).decode()  # Encode the zip buffer as base64

return HttpResponse(zip_data, content_type='application/zip')  # Return the zip file in the response
и файл загружается успешно, но когда я пытаюсь открыть файл, он говорит, что его невозможно открыть, поскольку это недействительный архив. Какие изменения я могу внести?

Подробнее здесь: https://stackoverflow.com/questions/782 ... -framework

Вернуться в «Python»