|
2 | 2 | import hashlib |
3 | 3 | import json |
4 | 4 | import logging |
| 5 | +import re |
5 | 6 | import os |
6 | 7 | from collections.abc import Mapping |
7 | 8 | from datetime import datetime |
@@ -52,6 +53,31 @@ def generate_pseudo_random_guid(cadena): |
52 | 53 | return UUID(hash_object.hexdigest()) |
53 | 54 |
|
54 | 55 |
|
| 56 | +def sanitize_filename(filename: str, replacement: str = "") -> str: |
| 57 | + """ |
| 58 | + Removes or replaces characters that are invalid in filenames. |
| 59 | +
|
| 60 | + Args: |
| 61 | + filename (str): The input string. |
| 62 | + replacement (str): What to put instead of invalid characters (default "_"). |
| 63 | +
|
| 64 | + Returns: |
| 65 | + str: A safe filename. |
| 66 | + """ |
| 67 | + # Characters forbidden in Windows filenames: \ / : * ? " < > | |
| 68 | + invalid_chars = r'[\\/:*?"<>|]+' |
| 69 | + |
| 70 | + # Replace invalid characters |
| 71 | + safe = re.sub(invalid_chars, replacement, filename) |
| 72 | + |
| 73 | + # Optionally, remove other special characters (keeping alphanumeric, space, _, -, .) |
| 74 | + safe = re.sub(r'[^a-zA-Z0-9 _.\-]', replacement, safe) |
| 75 | + |
| 76 | + # # Remove leading/trailing whitespace and dots (Windows restriction) |
| 77 | + # safe = safe.strip(" .") |
| 78 | + |
| 79 | + return safe |
| 80 | + |
55 | 81 | class MyCFDI(SatCFDI): |
56 | 82 | local_db = None |
57 | 83 | base_dir = None # type: str |
@@ -131,7 +157,7 @@ def filename(self): |
131 | 157 | match self.tag: |
132 | 158 | case '{http://www.sat.gob.mx/cfd/3}Comprobante' | '{http://www.sat.gob.mx/cfd/4}Comprobante': |
133 | 159 | path = "{3:%Y}/{3:%Y-%m}/facturas/{4}_{0}_[{1}]_{2}".format( |
134 | | - self.name, |
| 160 | + sanitize_filename(self.name), |
135 | 161 | code_str(self["TipoDeComprobante"]), |
136 | 162 | self.uuid, |
137 | 163 | self["Fecha"], |
|
0 commit comments