|
5 | 5 | from xml.etree.ElementTree import Element, ElementTree
|
6 | 6 |
|
7 | 7 | from django.core.files.base import ContentFile
|
8 |
| -from django.core.files.uploadedfile import InMemoryUploadedFile |
9 | 8 | from django.utils import timezone
|
10 | 9 |
|
11 | 10 | from donations.models.byof import OwnFormsUpload, OwnFormsStatusChoices
|
@@ -138,13 +137,35 @@ def generate_xml_from_external_data(own_upload: OwnFormsUpload) -> Dict[str, Uni
|
138 | 137 | return {"error": None, "data": xml_element_tree}
|
139 | 138 |
|
140 | 139 |
|
141 |
| -def parse_file_data(file: InMemoryUploadedFile) -> List[DonorModel]: |
| 140 | +def decode_readfile(input_file): |
| 141 | + # TODO: Try to optimize/simplify this |
| 142 | + readfile = input_file.read() |
| 143 | + |
| 144 | + try: |
| 145 | + # Try to decode the file as utf-8 |
| 146 | + # Deepcopy the readfile to avoid modifying the original bytes |
| 147 | + read_file = readfile.decode("utf-8") |
| 148 | + except UnicodeDecodeError: |
| 149 | + # If utf-8 fails, try cp1252 — common for Windows |
| 150 | + try: |
| 151 | + input_file.seek(0) |
| 152 | + readfile = input_file.read() |
| 153 | + read_file = readfile.decode("cp1252") |
| 154 | + except UnicodeDecodeError: |
| 155 | + raise ValueError(_("The file is not in a valid format.")) |
| 156 | + |
| 157 | + return read_file |
| 158 | + |
| 159 | + |
| 160 | +def parse_file_data(file) -> List[DonorModel]: |
142 | 161 | """
|
143 | 162 | Transform the CSV file to raw data.
|
144 | 163 | :param file: The CSV file path
|
145 | 164 | :return: A list of dictionaries containing the information of donors
|
146 | 165 | """
|
147 |
| - read_file = file.read().decode("utf-8") |
| 166 | + |
| 167 | + read_file = decode_readfile(file) |
| 168 | + |
148 | 169 | reader = csv.DictReader(io.StringIO(read_file))
|
149 | 170 |
|
150 | 171 | header_check = _check_csv_header(reader)
|
|
0 commit comments