meli-python-sdk 1.0.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- meli_python_sdk-1.0.0a1.dist-info/METADATA +449 -0
- meli_python_sdk-1.0.0a1.dist-info/RECORD +18 -0
- meli_python_sdk-1.0.0a1.dist-info/WHEEL +5 -0
- meli_python_sdk-1.0.0a1.dist-info/licenses/LICENSE +21 -0
- meli_python_sdk-1.0.0a1.dist-info/top_level.txt +1 -0
- meli_sdk/__init__.py +43 -0
- meli_sdk/_version.py +1 -0
- meli_sdk/actions.py +85 -0
- meli_sdk/bills.py +123 -0
- meli_sdk/client.py +523 -0
- meli_sdk/exceptions.py +34 -0
- meli_sdk/items.py +257 -0
- meli_sdk/metrics.py +77 -0
- meli_sdk/orders.py +222 -0
- meli_sdk/py.typed +0 -0
- meli_sdk/session.py +92 -0
- meli_sdk/shipments.py +26 -0
- meli_sdk/storage.py +119 -0
meli_sdk/bills.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import os
|
|
3
|
+
from typing import Union
|
|
4
|
+
|
|
5
|
+
from .actions import Actions
|
|
6
|
+
from .exceptions import MeliAPIError
|
|
7
|
+
|
|
8
|
+
DEFAULT_FILENAME = "factura.pdf"
|
|
9
|
+
PDF_MAGIC = b"%PDF-"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Bills:
|
|
13
|
+
"""Clase moderna para interactuar con los recursos de Facturación y Documentos Fiscales
|
|
14
|
+
(Composición)."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, client) -> None:
|
|
17
|
+
self.client = client
|
|
18
|
+
|
|
19
|
+
def get_billing_info(self, order_id: Union[int, str]) -> dict:
|
|
20
|
+
"""Obtiene la información de facturación vinculada a una orden."""
|
|
21
|
+
return self.client.request("GET", f"/orders/{order_id}/billing_info")
|
|
22
|
+
|
|
23
|
+
def has_fiscal_document(self, pack_id: Union[int, str]) -> bool:
|
|
24
|
+
"""Comprueba si un paquete de órdenes tiene un documento fiscal adjunto."""
|
|
25
|
+
try:
|
|
26
|
+
response = self.client.request("GET", f"/packs/{pack_id}/fiscal_documents")
|
|
27
|
+
except MeliAPIError as e:
|
|
28
|
+
if e.status_code == 404:
|
|
29
|
+
return False
|
|
30
|
+
raise
|
|
31
|
+
|
|
32
|
+
documents = response.get("fiscal_documents") if isinstance(response, dict) else None
|
|
33
|
+
return isinstance(documents, list) and bool(documents)
|
|
34
|
+
|
|
35
|
+
def upload_fiscal_document(
|
|
36
|
+
self,
|
|
37
|
+
pack_id: Union[int, str],
|
|
38
|
+
document,
|
|
39
|
+
*,
|
|
40
|
+
filename: str = None,
|
|
41
|
+
) -> dict:
|
|
42
|
+
"""Sube un documento fiscal (factura PDF) para un paquete.
|
|
43
|
+
|
|
44
|
+
``document`` puede ser una ruta, ``bytes``/``bytearray`` o un objeto de archivo binario.
|
|
45
|
+
"""
|
|
46
|
+
filename, fileobj, owns_file = self._prepare_fiscal_document(document, filename)
|
|
47
|
+
try:
|
|
48
|
+
files = {"fiscal_document": (filename, fileobj, "application/pdf")}
|
|
49
|
+
return self.client.request(
|
|
50
|
+
"POST", f"/packs/{pack_id}/fiscal_documents", files=files
|
|
51
|
+
)
|
|
52
|
+
finally:
|
|
53
|
+
if owns_file:
|
|
54
|
+
fileobj.close()
|
|
55
|
+
|
|
56
|
+
def _prepare_fiscal_document(self, document, filename):
|
|
57
|
+
"""Return (filename, file object, owns_file) after validating the PDF."""
|
|
58
|
+
if isinstance(document, (str, os.PathLike)):
|
|
59
|
+
fileobj = open(document, "rb")
|
|
60
|
+
try:
|
|
61
|
+
self._check_pdf(fileobj)
|
|
62
|
+
except Exception:
|
|
63
|
+
fileobj.close()
|
|
64
|
+
raise
|
|
65
|
+
default_name = os.path.basename(os.fspath(document))
|
|
66
|
+
return filename or default_name, fileobj, True
|
|
67
|
+
|
|
68
|
+
if isinstance(document, (bytes, bytearray)):
|
|
69
|
+
if not document:
|
|
70
|
+
raise ValueError("fiscal document is empty")
|
|
71
|
+
if bytes(document[:5]) != PDF_MAGIC:
|
|
72
|
+
raise ValueError("fiscal document must be a PDF")
|
|
73
|
+
return filename or DEFAULT_FILENAME, io.BytesIO(bytes(document)), True
|
|
74
|
+
|
|
75
|
+
if hasattr(document, "read"):
|
|
76
|
+
self._check_pdf_file_object(document)
|
|
77
|
+
name = getattr(document, "name", "")
|
|
78
|
+
default_name = os.path.basename(name) if isinstance(name, str) and name else ""
|
|
79
|
+
return filename or default_name or DEFAULT_FILENAME, document, False
|
|
80
|
+
|
|
81
|
+
raise TypeError("document must be a path, bytes or a binary file object")
|
|
82
|
+
|
|
83
|
+
@staticmethod
|
|
84
|
+
def _check_pdf(fileobj) -> None:
|
|
85
|
+
"""Validate the PDF signature of a seekable file and rewind it."""
|
|
86
|
+
header = fileobj.read(5)
|
|
87
|
+
if not header:
|
|
88
|
+
raise ValueError("fiscal document is empty")
|
|
89
|
+
if header != PDF_MAGIC:
|
|
90
|
+
raise ValueError("fiscal document must be a PDF")
|
|
91
|
+
fileobj.seek(0)
|
|
92
|
+
|
|
93
|
+
@staticmethod
|
|
94
|
+
def _check_pdf_file_object(document) -> None:
|
|
95
|
+
"""Validate the PDF signature of a caller file object when it is seekable."""
|
|
96
|
+
seek = getattr(document, "seek", None)
|
|
97
|
+
seekable = getattr(document, "seekable", None)
|
|
98
|
+
if seek is None or (callable(seekable) and not seekable()):
|
|
99
|
+
return
|
|
100
|
+
|
|
101
|
+
header = document.read(5)
|
|
102
|
+
document.seek(0)
|
|
103
|
+
if not header:
|
|
104
|
+
raise ValueError("fiscal document is empty")
|
|
105
|
+
if header != PDF_MAGIC:
|
|
106
|
+
raise ValueError("fiscal document must be a PDF")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# --- Capa de Compatibilidad Clásica (Legacy) ---
|
|
110
|
+
class Bill(Actions):
|
|
111
|
+
"""Clase legacy Bill compatible con la estructura original."""
|
|
112
|
+
|
|
113
|
+
def __init__(self, session) -> None:
|
|
114
|
+
self.session = session
|
|
115
|
+
|
|
116
|
+
def info(self, id: Union[int, str]) -> dict:
|
|
117
|
+
return Bills(self.session.client).get_billing_info(id)
|
|
118
|
+
|
|
119
|
+
def documents(self, pack_id: Union[int, str]) -> bool:
|
|
120
|
+
return Bills(self.session.client).has_fiscal_document(pack_id)
|
|
121
|
+
|
|
122
|
+
def upload(self, id: Union[int, str], url_file: str) -> dict:
|
|
123
|
+
return Bills(self.session.client).upload_fiscal_document(id, url_file)
|
meli_sdk/client.py
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import math
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from email.utils import parsedate_to_datetime
|
|
7
|
+
from urllib.parse import urlencode, urlsplit
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
from ._version import __version__
|
|
12
|
+
from .exceptions import MeliAPIError, MeliConnectionError, MeliTokenExpiredError
|
|
13
|
+
from .storage import TokenStorage
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger("meli_sdk")
|
|
16
|
+
|
|
17
|
+
RETRYABLE_STATUSES = frozenset({500, 502, 503, 504})
|
|
18
|
+
IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE"})
|
|
19
|
+
AUTH_HOSTS = {
|
|
20
|
+
"MCO": "auth.mercadolibre.com.co",
|
|
21
|
+
"MLA": "auth.mercadolibre.com.ar",
|
|
22
|
+
"MLM": "auth.mercadolibre.com.mx",
|
|
23
|
+
"MLB": "auth.mercadolivre.com.br",
|
|
24
|
+
"MLC": "auth.mercadolibre.cl",
|
|
25
|
+
"MPE": "auth.mercadolibre.com.pe",
|
|
26
|
+
"MLU": "auth.mercadolibre.com.uy",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _validate_timeout(timeout):
|
|
31
|
+
"""Return a validated timeout, raising ValueError when it is not usable."""
|
|
32
|
+
message = (
|
|
33
|
+
"timeout must be a positive int/float or a (connect, read) tuple of "
|
|
34
|
+
f"positive numbers, got {timeout!r}"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
if isinstance(timeout, bool):
|
|
38
|
+
raise ValueError(message)
|
|
39
|
+
|
|
40
|
+
if isinstance(timeout, (int, float)):
|
|
41
|
+
if not math.isfinite(timeout) or timeout <= 0:
|
|
42
|
+
raise ValueError(message)
|
|
43
|
+
return timeout
|
|
44
|
+
|
|
45
|
+
if isinstance(timeout, tuple) and len(timeout) == 2:
|
|
46
|
+
for value in timeout:
|
|
47
|
+
if (
|
|
48
|
+
isinstance(value, bool)
|
|
49
|
+
or not isinstance(value, (int, float))
|
|
50
|
+
or not math.isfinite(value)
|
|
51
|
+
or value <= 0
|
|
52
|
+
):
|
|
53
|
+
raise ValueError(message)
|
|
54
|
+
return timeout
|
|
55
|
+
|
|
56
|
+
raise ValueError(message)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _validate_max_retries(value):
|
|
60
|
+
"""Return a validated max_retries, raising ValueError when it is not usable."""
|
|
61
|
+
message = f"max_retries must be an int >= 0, got {value!r}"
|
|
62
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
|
63
|
+
raise ValueError(message)
|
|
64
|
+
return value
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _validate_backoff_factor(value):
|
|
68
|
+
"""Return a validated backoff_factor, raising ValueError when it is not usable."""
|
|
69
|
+
message = f"backoff_factor must be a finite number >= 0, got {value!r}"
|
|
70
|
+
if (
|
|
71
|
+
isinstance(value, bool)
|
|
72
|
+
or not isinstance(value, (int, float))
|
|
73
|
+
or not math.isfinite(value)
|
|
74
|
+
or value < 0
|
|
75
|
+
):
|
|
76
|
+
raise ValueError(message)
|
|
77
|
+
return value
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _validate_max_backoff(value):
|
|
81
|
+
"""Return a validated max_backoff, raising ValueError when it is not usable."""
|
|
82
|
+
message = f"max_backoff must be a finite number > 0, got {value!r}"
|
|
83
|
+
if (
|
|
84
|
+
isinstance(value, bool)
|
|
85
|
+
or not isinstance(value, (int, float))
|
|
86
|
+
or not math.isfinite(value)
|
|
87
|
+
or value <= 0
|
|
88
|
+
):
|
|
89
|
+
raise ValueError(message)
|
|
90
|
+
return value
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _validate_user_agent(user_agent):
|
|
94
|
+
"""Return a validated User-Agent prefix, raising ValueError when not usable."""
|
|
95
|
+
if user_agent is None:
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
message = f"user_agent must be a non-empty single-line string, got {user_agent!r}"
|
|
99
|
+
if not isinstance(user_agent, str) or not user_agent.strip():
|
|
100
|
+
raise ValueError(message)
|
|
101
|
+
if "\r" in user_agent or "\n" in user_agent:
|
|
102
|
+
raise ValueError(message)
|
|
103
|
+
return user_agent
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class MeliClient:
|
|
107
|
+
"""Cliente central de la API de Mercado Libre."""
|
|
108
|
+
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
client_id: str,
|
|
112
|
+
client_secret: str,
|
|
113
|
+
token_storage: TokenStorage,
|
|
114
|
+
api_url: str = "https://api.mercadolibre.com",
|
|
115
|
+
token_buffer_seconds: int = 300,
|
|
116
|
+
*,
|
|
117
|
+
timeout: float | tuple[float, float] = 30.0,
|
|
118
|
+
session: requests.Session | None = None,
|
|
119
|
+
max_retries: int = 3,
|
|
120
|
+
backoff_factor: float = 0.5,
|
|
121
|
+
max_backoff: float = 60.0,
|
|
122
|
+
user_agent: str | None = None,
|
|
123
|
+
) -> None:
|
|
124
|
+
self.client_id = client_id
|
|
125
|
+
self.client_secret = client_secret
|
|
126
|
+
self.token_storage = token_storage
|
|
127
|
+
self.api_url = api_url.rstrip("/")
|
|
128
|
+
self.token_buffer_seconds = token_buffer_seconds
|
|
129
|
+
self.timeout = _validate_timeout(timeout)
|
|
130
|
+
self.session = session if session is not None else requests.Session()
|
|
131
|
+
self._owns_session = session is None
|
|
132
|
+
self._closed = False
|
|
133
|
+
self.max_retries = _validate_max_retries(max_retries)
|
|
134
|
+
self.backoff_factor = _validate_backoff_factor(backoff_factor)
|
|
135
|
+
self.max_backoff = _validate_max_backoff(max_backoff)
|
|
136
|
+
self.user_agent = _validate_user_agent(user_agent)
|
|
137
|
+
self._sleep = time.sleep
|
|
138
|
+
self._refresh_lock = threading.Lock()
|
|
139
|
+
|
|
140
|
+
# Recursos (Lazy imports or direct instantiations to avoid circular dependencies)
|
|
141
|
+
from .bills import Bills
|
|
142
|
+
from .items import Items
|
|
143
|
+
from .metrics import Metrics
|
|
144
|
+
from .orders import Orders
|
|
145
|
+
from .shipments import Shipments
|
|
146
|
+
|
|
147
|
+
self.orders = Orders(self)
|
|
148
|
+
self.bills = Bills(self)
|
|
149
|
+
self.shipments = Shipments(self)
|
|
150
|
+
self.items = Items(self)
|
|
151
|
+
self.metrics = Metrics(self)
|
|
152
|
+
|
|
153
|
+
def request(self, method: str, path: str, **kwargs) -> dict:
|
|
154
|
+
"""
|
|
155
|
+
Realiza una petición HTTP a la API de Mercado Libre,
|
|
156
|
+
asegurando primero que el token de acceso sea válido.
|
|
157
|
+
"""
|
|
158
|
+
# Asegurar token de acceso válido
|
|
159
|
+
access_token = self.ensure_token_valid()
|
|
160
|
+
|
|
161
|
+
# Configurar URL completa
|
|
162
|
+
url = path if path.startswith("http") else f"{self.api_url}{path}"
|
|
163
|
+
|
|
164
|
+
# Configurar cabeceras
|
|
165
|
+
headers = kwargs.pop("headers", {})
|
|
166
|
+
headers.update({
|
|
167
|
+
"Authorization": f"Bearer {access_token}",
|
|
168
|
+
"Accept": "application/json",
|
|
169
|
+
"format-new": "true",
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
timeout = kwargs.pop("timeout", self.timeout)
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
response = self._send(method, url, headers=headers, timeout=timeout, **kwargs)
|
|
176
|
+
|
|
177
|
+
if response.status_code == 401 and self._rewind_files(kwargs.get("files")):
|
|
178
|
+
access_token = self._refresh_under_lock(stale_access_token=access_token)
|
|
179
|
+
headers["Authorization"] = f"Bearer {access_token}"
|
|
180
|
+
response = self._send(
|
|
181
|
+
method, url, headers=headers, timeout=timeout, **kwargs
|
|
182
|
+
)
|
|
183
|
+
except requests.RequestException as e:
|
|
184
|
+
raise MeliConnectionError(
|
|
185
|
+
f"Error de conexión con la API de Mercado Libre: {e}"
|
|
186
|
+
) from e
|
|
187
|
+
|
|
188
|
+
# Manejar respuestas con errores
|
|
189
|
+
if response.status_code >= 400:
|
|
190
|
+
error_data = {}
|
|
191
|
+
try:
|
|
192
|
+
error_data = response.json()
|
|
193
|
+
except ValueError:
|
|
194
|
+
pass
|
|
195
|
+
|
|
196
|
+
message = error_data.get("message") or error_data.get("error") or response.text
|
|
197
|
+
error_code = error_data.get("error") or error_data.get("code")
|
|
198
|
+
|
|
199
|
+
raise MeliAPIError(
|
|
200
|
+
message=f"API Error: {message}",
|
|
201
|
+
status_code=response.status_code,
|
|
202
|
+
error_code=error_code,
|
|
203
|
+
response_text=response.text,
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
# Retornar parsed JSON o response vacío si no hay contenido
|
|
207
|
+
if response.status_code == 204 or not response.text:
|
|
208
|
+
return {}
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
return response.json()
|
|
212
|
+
except ValueError as e:
|
|
213
|
+
raise MeliAPIError(
|
|
214
|
+
message=f"No se pudo decodificar JSON de la respuesta: {e}",
|
|
215
|
+
status_code=response.status_code,
|
|
216
|
+
response_text=response.text,
|
|
217
|
+
) from e
|
|
218
|
+
|
|
219
|
+
def _user_agent_header(self) -> str:
|
|
220
|
+
"""Return the identifying User-Agent, with the custom prefix when set."""
|
|
221
|
+
default = f"meli-sdk/{__version__} python-requests/{requests.__version__}"
|
|
222
|
+
if self.user_agent:
|
|
223
|
+
return f"{self.user_agent} {default}"
|
|
224
|
+
return default
|
|
225
|
+
|
|
226
|
+
def _send(self, method: str, url: str, **kwargs) -> requests.Response:
|
|
227
|
+
"""Send a request and retry the safe subset of transient failures."""
|
|
228
|
+
headers = dict(kwargs.get("headers") or {})
|
|
229
|
+
if not any(name.lower() == "user-agent" for name in headers):
|
|
230
|
+
headers["User-Agent"] = self._user_agent_header()
|
|
231
|
+
kwargs["headers"] = headers
|
|
232
|
+
|
|
233
|
+
method_name = method.upper()
|
|
234
|
+
idempotent = method_name in IDEMPOTENT_METHODS
|
|
235
|
+
attempt = 0
|
|
236
|
+
|
|
237
|
+
while True:
|
|
238
|
+
try:
|
|
239
|
+
response = self.session.request(method, url, **kwargs)
|
|
240
|
+
except (requests.ConnectionError, requests.Timeout) as exc:
|
|
241
|
+
if (
|
|
242
|
+
not idempotent
|
|
243
|
+
or attempt >= self.max_retries
|
|
244
|
+
or not self._rewind_files(kwargs.get("files"))
|
|
245
|
+
):
|
|
246
|
+
raise
|
|
247
|
+
delay = self._backoff_delay(attempt)
|
|
248
|
+
self._log_retry(method_name, url, delay, type(exc).__name__, attempt)
|
|
249
|
+
self._sleep(delay)
|
|
250
|
+
attempt += 1
|
|
251
|
+
continue
|
|
252
|
+
|
|
253
|
+
retryable = response.status_code == 429 or (
|
|
254
|
+
response.status_code in RETRYABLE_STATUSES and idempotent
|
|
255
|
+
)
|
|
256
|
+
if (
|
|
257
|
+
retryable
|
|
258
|
+
and attempt < self.max_retries
|
|
259
|
+
and self._rewind_files(kwargs.get("files"))
|
|
260
|
+
):
|
|
261
|
+
delay = self._retry_delay(response, attempt)
|
|
262
|
+
self._log_retry(method_name, url, delay, response.status_code, attempt)
|
|
263
|
+
self._sleep(delay)
|
|
264
|
+
attempt += 1
|
|
265
|
+
continue
|
|
266
|
+
|
|
267
|
+
return response
|
|
268
|
+
|
|
269
|
+
def _log_retry(self, method: str, url: str, delay: float, reason, attempt: int) -> None:
|
|
270
|
+
"""Log a retry without headers, query strings, tokens or bodies."""
|
|
271
|
+
logger.warning(
|
|
272
|
+
"Retry %d/%d for %s %s in %.2fs (reason: %s)",
|
|
273
|
+
attempt + 1,
|
|
274
|
+
self.max_retries,
|
|
275
|
+
method,
|
|
276
|
+
urlsplit(url).path,
|
|
277
|
+
delay,
|
|
278
|
+
reason,
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
def _backoff_delay(self, attempt: int) -> float:
|
|
282
|
+
"""Return the exponential backoff delay for an attempt, capped."""
|
|
283
|
+
return min(self.backoff_factor * 2**attempt, self.max_backoff)
|
|
284
|
+
|
|
285
|
+
def _retry_delay(self, response: requests.Response, attempt: int) -> float:
|
|
286
|
+
"""Return the delay requested by the response, capped by max_backoff."""
|
|
287
|
+
retry_after = self._parse_retry_after(response.headers.get("Retry-After"))
|
|
288
|
+
if retry_after is None:
|
|
289
|
+
return self._backoff_delay(attempt)
|
|
290
|
+
return min(retry_after, self.max_backoff)
|
|
291
|
+
|
|
292
|
+
@staticmethod
|
|
293
|
+
def _parse_retry_after(value):
|
|
294
|
+
"""Parse a Retry-After header as seconds or as an HTTP-date."""
|
|
295
|
+
if not value:
|
|
296
|
+
return None
|
|
297
|
+
|
|
298
|
+
value = value.strip()
|
|
299
|
+
try:
|
|
300
|
+
seconds = float(value)
|
|
301
|
+
except ValueError:
|
|
302
|
+
pass
|
|
303
|
+
else:
|
|
304
|
+
if math.isfinite(seconds) and seconds >= 0:
|
|
305
|
+
return seconds
|
|
306
|
+
return None
|
|
307
|
+
|
|
308
|
+
try:
|
|
309
|
+
retry_at = parsedate_to_datetime(value)
|
|
310
|
+
except (TypeError, ValueError):
|
|
311
|
+
return None
|
|
312
|
+
if retry_at is None:
|
|
313
|
+
return None
|
|
314
|
+
if retry_at.tzinfo is None:
|
|
315
|
+
retry_at = retry_at.replace(tzinfo=timezone.utc)
|
|
316
|
+
return max((retry_at - datetime.now(timezone.utc)).total_seconds(), 0.0)
|
|
317
|
+
|
|
318
|
+
def _rewind_files(self, files) -> bool:
|
|
319
|
+
"""Rewind the file objects of a request before retrying it."""
|
|
320
|
+
if not files:
|
|
321
|
+
return True
|
|
322
|
+
|
|
323
|
+
values = files.values() if hasattr(files, "values") else files
|
|
324
|
+
for value in values:
|
|
325
|
+
fileobj = value[1] if isinstance(value, tuple) and len(value) >= 2 else value
|
|
326
|
+
if not hasattr(fileobj, "read"):
|
|
327
|
+
continue
|
|
328
|
+
if not self._is_seekable(fileobj):
|
|
329
|
+
return False
|
|
330
|
+
fileobj.seek(0)
|
|
331
|
+
return True
|
|
332
|
+
|
|
333
|
+
@staticmethod
|
|
334
|
+
def _is_seekable(fileobj) -> bool:
|
|
335
|
+
"""Return True when seek(0) can safely rewind a file object."""
|
|
336
|
+
if not hasattr(fileobj, "seek"):
|
|
337
|
+
return False
|
|
338
|
+
seekable = getattr(fileobj, "seekable", None)
|
|
339
|
+
if callable(seekable) and not seekable():
|
|
340
|
+
return False
|
|
341
|
+
return True
|
|
342
|
+
|
|
343
|
+
def ensure_token_valid(self) -> str:
|
|
344
|
+
"""
|
|
345
|
+
Verifica el token actual. Si está expirado o próximo a expirar,
|
|
346
|
+
inicia la renovación automática y actualiza el almacenamiento.
|
|
347
|
+
Retorna el access_token válido.
|
|
348
|
+
"""
|
|
349
|
+
token_data = self.token_storage.load_token()
|
|
350
|
+
|
|
351
|
+
if not token_data:
|
|
352
|
+
raise MeliTokenExpiredError("No hay un token almacenado. Debe autenticarse primero.")
|
|
353
|
+
|
|
354
|
+
if self._token_is_valid(token_data):
|
|
355
|
+
return token_data["access_token"]
|
|
356
|
+
|
|
357
|
+
return self._refresh_under_lock()
|
|
358
|
+
|
|
359
|
+
def _token_is_valid(self, token_data: dict) -> bool:
|
|
360
|
+
"""Return True when the access token is outside the refresh buffer."""
|
|
361
|
+
access_token = token_data.get("access_token")
|
|
362
|
+
expires_at = token_data.get("expires_at")
|
|
363
|
+
if not access_token or not expires_at:
|
|
364
|
+
return False
|
|
365
|
+
return time.time() < (expires_at - self.token_buffer_seconds)
|
|
366
|
+
|
|
367
|
+
def _refresh_under_lock(self, stale_access_token=None) -> str:
|
|
368
|
+
"""Refresh the token once, re-reading the storage inside both locks."""
|
|
369
|
+
with self._refresh_lock, self.token_storage.lock():
|
|
370
|
+
token_data = self.token_storage.load_token()
|
|
371
|
+
|
|
372
|
+
if not token_data:
|
|
373
|
+
raise MeliTokenExpiredError(
|
|
374
|
+
"No hay un token almacenado. Debe autenticarse primero."
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
access_token = token_data.get("access_token")
|
|
378
|
+
if self._token_is_valid(token_data) and (
|
|
379
|
+
stale_access_token is None or access_token != stale_access_token
|
|
380
|
+
):
|
|
381
|
+
return access_token
|
|
382
|
+
|
|
383
|
+
refresh_token_str = token_data.get("refresh_token")
|
|
384
|
+
if not refresh_token_str:
|
|
385
|
+
raise MeliTokenExpiredError(
|
|
386
|
+
"El access token ha expirado y no hay un refresh token disponible."
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
return self.refresh_token(refresh_token_str)["access_token"]
|
|
390
|
+
|
|
391
|
+
def refresh_token(self, refresh_token_str: str) -> dict:
|
|
392
|
+
"""Solicita un nuevo token de acceso usando el token de refresco."""
|
|
393
|
+
url = f"{self.api_url}/oauth/token"
|
|
394
|
+
payload = {
|
|
395
|
+
"grant_type": "refresh_token",
|
|
396
|
+
"client_id": self.client_id,
|
|
397
|
+
"client_secret": self.client_secret,
|
|
398
|
+
"refresh_token": refresh_token_str,
|
|
399
|
+
}
|
|
400
|
+
headers = {
|
|
401
|
+
"Accept": "application/json",
|
|
402
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
try:
|
|
406
|
+
response = self._send(
|
|
407
|
+
"POST", url, data=payload, headers=headers, timeout=self.timeout
|
|
408
|
+
)
|
|
409
|
+
except requests.RequestException as e:
|
|
410
|
+
raise MeliConnectionError(f"Error al conectar para renovar el token: {e}") from e
|
|
411
|
+
|
|
412
|
+
if response.status_code >= 400:
|
|
413
|
+
error_data = {}
|
|
414
|
+
try:
|
|
415
|
+
error_data = response.json()
|
|
416
|
+
except ValueError:
|
|
417
|
+
pass
|
|
418
|
+
|
|
419
|
+
message = error_data.get("message") or error_data.get("error") or response.text
|
|
420
|
+
raise MeliTokenExpiredError(f"Fallo al renovar el token: {message}")
|
|
421
|
+
|
|
422
|
+
token_response = response.json()
|
|
423
|
+
return self._store_token_response(token_response)
|
|
424
|
+
|
|
425
|
+
def _store_token_response(self, token_response: dict) -> dict:
|
|
426
|
+
"""Add local timestamps to a token response and persist it."""
|
|
427
|
+
now = time.time()
|
|
428
|
+
token_response["created_at"] = now
|
|
429
|
+
token_response["expires_at"] = now + token_response.get("expires_in", 21600)
|
|
430
|
+
self.token_storage.save_token(token_response)
|
|
431
|
+
return token_response
|
|
432
|
+
|
|
433
|
+
def get_authorization_url(
|
|
434
|
+
self,
|
|
435
|
+
redirect_uri: str,
|
|
436
|
+
state: str,
|
|
437
|
+
site_id: str = "MCO",
|
|
438
|
+
code_challenge: str | None = None,
|
|
439
|
+
) -> str:
|
|
440
|
+
"""Return the URL that starts the authorization-code flow.
|
|
441
|
+
|
|
442
|
+
``state`` must be an unguessable value tied to the user session (CSRF protection), not a
|
|
443
|
+
predictable id such as the user id.
|
|
444
|
+
"""
|
|
445
|
+
host = AUTH_HOSTS.get(site_id)
|
|
446
|
+
if host is None:
|
|
447
|
+
raise ValueError(
|
|
448
|
+
f"Unknown site_id {site_id!r}; expected one of {sorted(AUTH_HOSTS)}"
|
|
449
|
+
)
|
|
450
|
+
if not isinstance(state, str) or not state.strip():
|
|
451
|
+
raise ValueError("state is required and must be a non-empty string")
|
|
452
|
+
|
|
453
|
+
params = {
|
|
454
|
+
"response_type": "code",
|
|
455
|
+
"client_id": self.client_id,
|
|
456
|
+
"redirect_uri": redirect_uri,
|
|
457
|
+
"state": state,
|
|
458
|
+
}
|
|
459
|
+
if code_challenge:
|
|
460
|
+
params["code_challenge"] = code_challenge
|
|
461
|
+
params["code_challenge_method"] = "S256"
|
|
462
|
+
|
|
463
|
+
return f"https://{host}/authorization?{urlencode(params)}"
|
|
464
|
+
|
|
465
|
+
def exchange_code(
|
|
466
|
+
self, code: str, redirect_uri: str, code_verifier: str | None = None
|
|
467
|
+
) -> dict:
|
|
468
|
+
"""Exchange an authorization code for the first token of the user."""
|
|
469
|
+
url = f"{self.api_url}/oauth/token"
|
|
470
|
+
payload = {
|
|
471
|
+
"grant_type": "authorization_code",
|
|
472
|
+
"client_id": self.client_id,
|
|
473
|
+
"client_secret": self.client_secret,
|
|
474
|
+
"code": code,
|
|
475
|
+
"redirect_uri": redirect_uri,
|
|
476
|
+
}
|
|
477
|
+
if code_verifier is not None:
|
|
478
|
+
payload["code_verifier"] = code_verifier
|
|
479
|
+
headers = {
|
|
480
|
+
"Accept": "application/json",
|
|
481
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
with self._refresh_lock, self.token_storage.lock():
|
|
485
|
+
try:
|
|
486
|
+
response = self._send(
|
|
487
|
+
"POST", url, data=payload, headers=headers, timeout=self.timeout
|
|
488
|
+
)
|
|
489
|
+
except requests.RequestException as e:
|
|
490
|
+
raise MeliConnectionError(
|
|
491
|
+
f"Error de conexión al intercambiar el código de autorización: {e}"
|
|
492
|
+
) from e
|
|
493
|
+
|
|
494
|
+
if response.status_code >= 400:
|
|
495
|
+
error_data = {}
|
|
496
|
+
try:
|
|
497
|
+
error_data = response.json()
|
|
498
|
+
except ValueError:
|
|
499
|
+
pass
|
|
500
|
+
|
|
501
|
+
message = (
|
|
502
|
+
error_data.get("message") or error_data.get("error") or response.text
|
|
503
|
+
)
|
|
504
|
+
raise MeliAPIError(
|
|
505
|
+
message=f"API Error: {message}",
|
|
506
|
+
status_code=response.status_code,
|
|
507
|
+
error_code=error_data.get("error"),
|
|
508
|
+
response_text=response.text,
|
|
509
|
+
)
|
|
510
|
+
|
|
511
|
+
return self._store_token_response(response.json())
|
|
512
|
+
|
|
513
|
+
def close(self) -> None:
|
|
514
|
+
"""Close the underlying session when this client owns it."""
|
|
515
|
+
if self._owns_session and not self._closed:
|
|
516
|
+
self.session.close()
|
|
517
|
+
self._closed = True
|
|
518
|
+
|
|
519
|
+
def __enter__(self) -> "MeliClient":
|
|
520
|
+
return self
|
|
521
|
+
|
|
522
|
+
def __exit__(self, exc_type, exc_value, traceback) -> None:
|
|
523
|
+
self.close()
|
meli_sdk/exceptions.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
class MeliError(Exception):
|
|
2
|
+
"""Clase base para todas las excepciones de Meli SDK."""
|
|
3
|
+
pass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MeliAPIError(MeliError):
|
|
7
|
+
"""Excepción para errores devueltos por la API de Mercado Libre."""
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
message: str,
|
|
12
|
+
status_code: int = None,
|
|
13
|
+
error_code: str = None,
|
|
14
|
+
response_text: str = None,
|
|
15
|
+
) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.status_code = status_code
|
|
18
|
+
self.error_code = error_code
|
|
19
|
+
self.response_text = response_text
|
|
20
|
+
|
|
21
|
+
def __str__(self) -> str:
|
|
22
|
+
code_str = f" [{self.error_code}]" if self.error_code else ""
|
|
23
|
+
status_str = f" (Status: {self.status_code})" if self.status_code else ""
|
|
24
|
+
return f"{super().__str__()}{code_str}{status_str}"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MeliTokenExpiredError(MeliError):
|
|
28
|
+
"""Excepción lanzada cuando el refresh token ha expirado o ya no es válido."""
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class MeliConnectionError(MeliError):
|
|
33
|
+
"""Excepción lanzada por fallos de red o de conexión."""
|
|
34
|
+
pass
|