|
| 1 | +import re |
| 2 | +from datetime import datetime, timezone |
| 3 | + |
| 4 | +import boto3 |
| 5 | +from django.conf import settings |
| 6 | +from django.core.management.base import BaseCommand |
| 7 | +from rest_framework.request import Request |
| 8 | +from rest_framework.test import APIRequestFactory |
| 9 | +from rest_framework_xml.renderers import XMLRenderer |
| 10 | + |
| 11 | +from api.serializers import ErpSerializer |
| 12 | +from erp.models import Erp |
| 13 | + |
| 14 | +CHUNK_SIZE = 1000 |
| 15 | + |
| 16 | +ACTIVITIES = [ |
| 17 | + 255, |
| 18 | + 184, |
| 19 | + 4, |
| 20 | + 6, |
| 21 | + 1, |
| 22 | + 293, |
| 23 | + 279, |
| 24 | + 14, |
| 25 | + 257, |
| 26 | + 406, |
| 27 | + 223, |
| 28 | + 22, |
| 29 | + 243, |
| 30 | + 247, |
| 31 | + 27, |
| 32 | + 29, |
| 33 | + 253, |
| 34 | + 33, |
| 35 | + 34, |
| 36 | + 305, |
| 37 | + 38, |
| 38 | + 203, |
| 39 | + 40, |
| 40 | + 339, |
| 41 | + 41, |
| 42 | + 42, |
| 43 | + 43, |
| 44 | + 141, |
| 45 | + 298, |
| 46 | + 50, |
| 47 | + 51, |
| 48 | + 285, |
| 49 | + 450, |
| 50 | + 297, |
| 51 | + 63, |
| 52 | + 64, |
| 53 | + 375, |
| 54 | + 307, |
| 55 | + 206, |
| 56 | + 79, |
| 57 | + 62, |
| 58 | + 407, |
| 59 | + 405, |
| 60 | + 224, |
| 61 | + 85, |
| 62 | + 86, |
| 63 | + 84, |
| 64 | + 415, |
| 65 | + 95, |
| 66 | + 252, |
| 67 | + 100, |
| 68 | + 103, |
| 69 | + 109, |
| 70 | + 236, |
| 71 | + 112, |
| 72 | + 211, |
| 73 | + 411, |
| 74 | + 113, |
| 75 | + 385, |
| 76 | + 117, |
| 77 | + 209, |
| 78 | + 380, |
| 79 | + 292, |
| 80 | + 125, |
| 81 | + 432, |
| 82 | + 417, |
| 83 | + 231, |
| 84 | + 294, |
| 85 | + 310, |
| 86 | + 135, |
| 87 | + 362, |
| 88 | + 137, |
| 89 | + 145, |
| 90 | + 147, |
| 91 | + 269, |
| 92 | + 148, |
| 93 | + 152, |
| 94 | + 153, |
| 95 | + 258, |
| 96 | + 445, |
| 97 | + 413, |
| 98 | + 163, |
| 99 | + 165, |
| 100 | + 295, |
| 101 | + 171, |
| 102 | + 172, |
| 103 | + 177, |
| 104 | + 396, |
| 105 | + 220, |
| 106 | + 173, |
| 107 | + 174, |
| 108 | + 175, |
| 109 | + 176, |
| 110 | + 178, |
| 111 | + 168, |
| 112 | + 182, |
| 113 | + 183, |
| 114 | + 185, |
| 115 | + 381, |
| 116 | + 194, |
| 117 | + 371, |
| 118 | + 196, |
| 119 | + 276, |
| 120 | + 392, |
| 121 | + 414, |
| 122 | + 429, |
| 123 | +] |
| 124 | + |
| 125 | + |
| 126 | +class Command(BaseCommand): |
| 127 | + help = "Export ERP in XML format to S3" |
| 128 | + |
| 129 | + def handle(self, *args, **options): |
| 130 | + now = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") |
| 131 | + |
| 132 | + server_name = settings.SITE_HOST |
| 133 | + factory = APIRequestFactory(SERVER_NAME=server_name) |
| 134 | + fake_request = Request(factory.get("/")) |
| 135 | + |
| 136 | + qs = ( |
| 137 | + Erp.objects.published() |
| 138 | + .select_related("user", "accessibilite", "activite") |
| 139 | + .filter(activite__id__in=ACTIVITIES) |
| 140 | + .order_by("id") |
| 141 | + ) |
| 142 | + total = qs.count() |
| 143 | + self.stdout.write(f"{total} ERPs to export...") |
| 144 | + |
| 145 | + bucket_name = settings.S3_EXPORT_BUCKET_NAME |
| 146 | + file_name = f"export_{now}_full.xml" |
| 147 | + |
| 148 | + s3 = boto3.client( |
| 149 | + "s3", |
| 150 | + endpoint_url=settings.S3_EXPORT_BUCKET_ENDPOINT_URL, |
| 151 | + ) |
| 152 | + |
| 153 | + # Initialize the multipart upload |
| 154 | + mpu = s3.create_multipart_upload(Bucket=bucket_name, Key=file_name, ContentType="application/xml") |
| 155 | + upload_id = mpu["UploadId"] |
| 156 | + parts = [] |
| 157 | + part_number = 1 |
| 158 | + buffer = b'<?xml version="1.0" encoding="utf-8"?>\n<root>' |
| 159 | + renderer = XMLRenderer() |
| 160 | + |
| 161 | + try: |
| 162 | + for offset in range(0, total, CHUNK_SIZE): |
| 163 | + batch = qs[offset : offset + CHUNK_SIZE] |
| 164 | + self.stdout.write(f"Serialize {offset}-{offset + CHUNK_SIZE}/{total}...") |
| 165 | + |
| 166 | + data = ErpSerializer(batch, many=True, context={"request": fake_request}).data |
| 167 | + xml_str = renderer.render(data, accepted_media_type="application/xml", renderer_context={}) |
| 168 | + if isinstance(xml_str, str): |
| 169 | + xml_str = xml_str.encode("utf-8") |
| 170 | + |
| 171 | + # using ErpSerializer is serializing into <root> tag, so we need to remove it, to append it to our buffer |
| 172 | + inner = re.search(rb"<root>(.*)</root>", xml_str, re.DOTALL) |
| 173 | + if inner: |
| 174 | + buffer += inner.group(1) |
| 175 | + |
| 176 | + # S3 multipart requires parts >= 5MB (except the last one) |
| 177 | + if len(buffer) >= 5 * 1024 * 1024: |
| 178 | + self.stdout.write(f"Upload part {part_number} ({offset}-{offset + CHUNK_SIZE}/{total})...") |
| 179 | + response = s3.upload_part( |
| 180 | + Bucket=bucket_name, |
| 181 | + Key=file_name, |
| 182 | + PartNumber=part_number, |
| 183 | + UploadId=upload_id, |
| 184 | + Body=buffer, |
| 185 | + ) |
| 186 | + parts.append({"PartNumber": part_number, "ETag": response["ETag"]}) |
| 187 | + part_number += 1 |
| 188 | + buffer = b"" |
| 189 | + |
| 190 | + # Remaining part |
| 191 | + buffer += "</root>".encode("utf-8") |
| 192 | + response = s3.upload_part( |
| 193 | + Bucket=bucket_name, |
| 194 | + Key=file_name, |
| 195 | + PartNumber=part_number, |
| 196 | + UploadId=upload_id, |
| 197 | + Body=buffer, |
| 198 | + ) |
| 199 | + parts.append({"PartNumber": part_number, "ETag": response["ETag"]}) |
| 200 | + |
| 201 | + s3.complete_multipart_upload( |
| 202 | + Bucket=bucket_name, |
| 203 | + Key=file_name, |
| 204 | + UploadId=upload_id, |
| 205 | + MultipartUpload={"Parts": parts}, |
| 206 | + ) |
| 207 | + |
| 208 | + except Exception as e: |
| 209 | + s3.abort_multipart_upload(Bucket=bucket_name, Key=file_name, UploadId=upload_id) |
| 210 | + raise e |
| 211 | + |
| 212 | + file_url = s3.generate_presigned_url( |
| 213 | + "get_object", |
| 214 | + Params={"Bucket": bucket_name, "Key": file_name}, |
| 215 | + ExpiresIn=604800, |
| 216 | + ) |
| 217 | + |
| 218 | + self.stdout.write(self.style.SUCCESS(f"Export terminated, link available during 7 days: {file_url}")) |
0 commit comments