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/items.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
from typing import List, Union
|
|
2
|
+
|
|
3
|
+
from .exceptions import MeliAPIError
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Items:
|
|
7
|
+
"""Clase para interactuar con los recursos de Publicaciones de Productos (Items) de
|
|
8
|
+
Mercado Libre."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, client) -> None:
|
|
11
|
+
self.client = client
|
|
12
|
+
|
|
13
|
+
def create(self, data: dict) -> dict:
|
|
14
|
+
"""Crea/publica un nuevo producto en Mercado Libre."""
|
|
15
|
+
return self.client.request("POST", "/items", json=data)
|
|
16
|
+
|
|
17
|
+
def get(self, item_id: str) -> dict:
|
|
18
|
+
"""Obtiene la información de un producto por su ID."""
|
|
19
|
+
return self.client.request("GET", f"/items/{item_id}")
|
|
20
|
+
|
|
21
|
+
def update(self, item_id: str, data: dict) -> dict:
|
|
22
|
+
"""Actualiza atributos específicos de un producto."""
|
|
23
|
+
return self.client.request("PUT", f"/items/{item_id}", json=data)
|
|
24
|
+
|
|
25
|
+
def update_price(self, item_id: str, price: float) -> dict:
|
|
26
|
+
"""Método de conveniencia para actualizar el precio de un producto."""
|
|
27
|
+
return self.update(item_id, {"price": price})
|
|
28
|
+
|
|
29
|
+
def update_stock(self, item_id: str, available_quantity: int) -> dict:
|
|
30
|
+
"""Método de conveniencia para actualizar el stock/cantidad disponible de un producto."""
|
|
31
|
+
return self.update(item_id, {"available_quantity": available_quantity})
|
|
32
|
+
|
|
33
|
+
def search(
|
|
34
|
+
self,
|
|
35
|
+
seller_id: int = None,
|
|
36
|
+
offset: int = 0,
|
|
37
|
+
limit: int = 50,
|
|
38
|
+
extra_params: dict = None,
|
|
39
|
+
) -> dict:
|
|
40
|
+
"""Busca y lista los IDs de publicaciones de un vendedor."""
|
|
41
|
+
if seller_id is None:
|
|
42
|
+
token_data = self.client.token_storage.load_token()
|
|
43
|
+
seller_id = token_data.get("user_id")
|
|
44
|
+
if not seller_id:
|
|
45
|
+
raise ValueError("seller_id es requerido o no se pudo obtener del token activo.")
|
|
46
|
+
|
|
47
|
+
params = {"offset": offset, "limit": limit}
|
|
48
|
+
if extra_params:
|
|
49
|
+
params.update(extra_params)
|
|
50
|
+
|
|
51
|
+
return self.client.request("GET", f"/users/{seller_id}/items/search", params=params)
|
|
52
|
+
|
|
53
|
+
def iter_all(
|
|
54
|
+
self,
|
|
55
|
+
seller_id: int = None,
|
|
56
|
+
*,
|
|
57
|
+
page_size: int = 100,
|
|
58
|
+
extra_params: dict = None,
|
|
59
|
+
):
|
|
60
|
+
"""Yield the seller's item IDs using scan mode, in API order.
|
|
61
|
+
|
|
62
|
+
This yields IDs; use ``get_many`` to fetch the item details. The scan ``scroll_id``
|
|
63
|
+
expires after 5 minutes, so consume the generator without long pauses.
|
|
64
|
+
|
|
65
|
+
``page_size`` must be an int between 1 and 100 and ``extra_params`` must not contain
|
|
66
|
+
``offset``, ``limit``, ``search_type`` or ``scroll_id``; both are validated on the first
|
|
67
|
+
``next()``.
|
|
68
|
+
"""
|
|
69
|
+
if (
|
|
70
|
+
isinstance(page_size, bool)
|
|
71
|
+
or not isinstance(page_size, int)
|
|
72
|
+
or not 1 <= page_size <= 100
|
|
73
|
+
):
|
|
74
|
+
raise ValueError("page_size must be an int between 1 and 100")
|
|
75
|
+
|
|
76
|
+
pagination_keys = {"offset", "limit", "search_type", "scroll_id"}
|
|
77
|
+
if extra_params and pagination_keys.intersection(extra_params):
|
|
78
|
+
raise ValueError(
|
|
79
|
+
"extra_params must not contain 'offset', 'limit', 'search_type' or 'scroll_id'"
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
if seller_id is None:
|
|
83
|
+
token_data = self.client.token_storage.load_token()
|
|
84
|
+
seller_id = token_data.get("user_id")
|
|
85
|
+
if not seller_id:
|
|
86
|
+
raise ValueError(
|
|
87
|
+
"seller_id es requerido o no se pudo obtener del token activo."
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
url = f"/users/{seller_id}/items/search"
|
|
91
|
+
params = {"search_type": "scan", "limit": page_size}
|
|
92
|
+
if extra_params:
|
|
93
|
+
params.update(extra_params)
|
|
94
|
+
|
|
95
|
+
scroll_id = None
|
|
96
|
+
while True:
|
|
97
|
+
current = dict(params)
|
|
98
|
+
if scroll_id is not None:
|
|
99
|
+
current["scroll_id"] = scroll_id
|
|
100
|
+
|
|
101
|
+
page = self.client.request("GET", url, params=current)
|
|
102
|
+
results = page.get("results") or []
|
|
103
|
+
|
|
104
|
+
for item_id in results:
|
|
105
|
+
yield item_id
|
|
106
|
+
|
|
107
|
+
scroll_id = page.get("scroll_id")
|
|
108
|
+
if not results or not scroll_id:
|
|
109
|
+
return
|
|
110
|
+
|
|
111
|
+
@staticmethod
|
|
112
|
+
def _normalize_item_ids(item_ids) -> list:
|
|
113
|
+
"""Normalize ids to trimmed strings and deduplicate in first-seen order."""
|
|
114
|
+
if isinstance(item_ids, str):
|
|
115
|
+
item_ids = [item_ids]
|
|
116
|
+
elif isinstance(item_ids, (bytes, bytearray)) or not hasattr(item_ids, "__iter__"):
|
|
117
|
+
raise TypeError("item_ids must be a string or an iterable of ids")
|
|
118
|
+
|
|
119
|
+
normalized = []
|
|
120
|
+
seen = set()
|
|
121
|
+
for item_id in item_ids:
|
|
122
|
+
value = str(item_id).strip()
|
|
123
|
+
if not value:
|
|
124
|
+
raise ValueError("item ids must not be empty")
|
|
125
|
+
if value not in seen:
|
|
126
|
+
seen.add(value)
|
|
127
|
+
normalized.append(value)
|
|
128
|
+
return normalized
|
|
129
|
+
|
|
130
|
+
@staticmethod
|
|
131
|
+
def _normalize_attributes(attributes):
|
|
132
|
+
"""Return a comma-separated attribute list that always includes id."""
|
|
133
|
+
if attributes is None:
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
if isinstance(attributes, str):
|
|
137
|
+
names = attributes.split(",")
|
|
138
|
+
elif isinstance(attributes, (bytes, bytearray)) or not hasattr(attributes, "__iter__"):
|
|
139
|
+
raise TypeError("attributes must be a string or an iterable of names")
|
|
140
|
+
else:
|
|
141
|
+
names = attributes
|
|
142
|
+
|
|
143
|
+
cleaned = []
|
|
144
|
+
for name in names:
|
|
145
|
+
value = str(name).strip()
|
|
146
|
+
if value and value not in cleaned:
|
|
147
|
+
cleaned.append(value)
|
|
148
|
+
|
|
149
|
+
if not cleaned:
|
|
150
|
+
raise ValueError("attributes must contain at least one name")
|
|
151
|
+
if "id" not in cleaned:
|
|
152
|
+
cleaned.insert(0, "id")
|
|
153
|
+
return ",".join(cleaned)
|
|
154
|
+
|
|
155
|
+
def get_many(self, item_ids, *, attributes=None, include_errors: bool = False) -> list:
|
|
156
|
+
"""Fetch several items through the multiget endpoint, in batches of 20."""
|
|
157
|
+
unique_ids = self._normalize_item_ids(item_ids)
|
|
158
|
+
if not unique_ids:
|
|
159
|
+
return []
|
|
160
|
+
|
|
161
|
+
attributes_param = self._normalize_attributes(attributes)
|
|
162
|
+
|
|
163
|
+
results = []
|
|
164
|
+
for start in range(0, len(unique_ids), 20):
|
|
165
|
+
batch = unique_ids[start : start + 20]
|
|
166
|
+
params = {"ids": ",".join(batch)}
|
|
167
|
+
if attributes_param is not None:
|
|
168
|
+
params["attributes"] = attributes_param
|
|
169
|
+
|
|
170
|
+
response = self.client.request("GET", "/items", params=params)
|
|
171
|
+
if not isinstance(response, list):
|
|
172
|
+
raise MeliAPIError(
|
|
173
|
+
message="Unexpected non-list response from the items multiget",
|
|
174
|
+
status_code=200,
|
|
175
|
+
response_text=str(response),
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
if include_errors:
|
|
179
|
+
results.extend(response)
|
|
180
|
+
continue
|
|
181
|
+
|
|
182
|
+
# The API may return entries in another order; match them by body id.
|
|
183
|
+
entries_by_id = {}
|
|
184
|
+
for entry in response:
|
|
185
|
+
if entry.get("code") != 200:
|
|
186
|
+
continue
|
|
187
|
+
body = entry.get("body")
|
|
188
|
+
if isinstance(body, dict):
|
|
189
|
+
entries_by_id[body.get("id")] = body
|
|
190
|
+
for item_id in batch:
|
|
191
|
+
body = entries_by_id.get(item_id)
|
|
192
|
+
if body is not None:
|
|
193
|
+
results.append(body)
|
|
194
|
+
|
|
195
|
+
return results
|
|
196
|
+
|
|
197
|
+
def _format_ids(self, item_ids: Union[str, List[str]]) -> str:
|
|
198
|
+
"""Formatea una lista o cadena de IDs de items en un formato separado por comas."""
|
|
199
|
+
if isinstance(item_ids, list):
|
|
200
|
+
return ",".join(map(str, item_ids))
|
|
201
|
+
return str(item_ids)
|
|
202
|
+
|
|
203
|
+
def get_visits(
|
|
204
|
+
self,
|
|
205
|
+
item_ids: Union[str, List[str]],
|
|
206
|
+
date_from: str = None,
|
|
207
|
+
date_to: str = None,
|
|
208
|
+
) -> dict:
|
|
209
|
+
"""
|
|
210
|
+
Obtiene las visitas acumuladas de uno o varios productos en un periodo de fechas.
|
|
211
|
+
Rango de fechas en formato ISO 8601 (ej. '2026-06-01T00:00:00.000-00:00').
|
|
212
|
+
"""
|
|
213
|
+
ids_str = self._format_ids(item_ids)
|
|
214
|
+
params = {"ids": ids_str}
|
|
215
|
+
|
|
216
|
+
if date_from:
|
|
217
|
+
params["date_from"] = date_from
|
|
218
|
+
if date_to:
|
|
219
|
+
params["date_to"] = date_to
|
|
220
|
+
|
|
221
|
+
return self.client.request("GET", "/items/visits", params=params)
|
|
222
|
+
|
|
223
|
+
def get_visits_window(
|
|
224
|
+
self,
|
|
225
|
+
item_ids: Union[str, List[str]],
|
|
226
|
+
last: int = 5,
|
|
227
|
+
unit: str = "day",
|
|
228
|
+
) -> dict:
|
|
229
|
+
"""
|
|
230
|
+
Obtiene visitas usando una ventana de tiempo móvil (ej. últimas 5 horas o días).
|
|
231
|
+
- unit: 'day' o 'hour'
|
|
232
|
+
"""
|
|
233
|
+
ids_str = self._format_ids(item_ids)
|
|
234
|
+
params = {"ids": ids_str, "last": last, "unit": unit}
|
|
235
|
+
|
|
236
|
+
return self.client.request("GET", "/items/visits/time_window", params=params)
|
|
237
|
+
|
|
238
|
+
def get_user_items_visits(
|
|
239
|
+
self,
|
|
240
|
+
seller_id: int = None,
|
|
241
|
+
date_from: str = None,
|
|
242
|
+
date_to: str = None,
|
|
243
|
+
) -> dict:
|
|
244
|
+
"""Obtiene estadísticas agregadas de visitas a nivel usuario/vendedor."""
|
|
245
|
+
if seller_id is None:
|
|
246
|
+
token_data = self.client.token_storage.load_token()
|
|
247
|
+
seller_id = token_data.get("user_id")
|
|
248
|
+
if not seller_id:
|
|
249
|
+
raise ValueError("seller_id es requerido o no se pudo obtener del token activo.")
|
|
250
|
+
|
|
251
|
+
params = {}
|
|
252
|
+
if date_from:
|
|
253
|
+
params["date_from"] = date_from
|
|
254
|
+
if date_to:
|
|
255
|
+
params["date_to"] = date_to
|
|
256
|
+
|
|
257
|
+
return self.client.request("GET", f"/users/{seller_id}/items_visits", params=params)
|
meli_sdk/metrics.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
class Metrics:
|
|
2
|
+
"""Clase para obtener métricas, reputación, tendencias y opiniones en Mercado Libre."""
|
|
3
|
+
|
|
4
|
+
def __init__(self, client) -> None:
|
|
5
|
+
self.client = client
|
|
6
|
+
|
|
7
|
+
def get_seller_info(self, seller_id: int = None) -> dict:
|
|
8
|
+
"""Obtiene la información pública y de rendimiento de un vendedor."""
|
|
9
|
+
if seller_id is None:
|
|
10
|
+
token_data = self.client.token_storage.load_token()
|
|
11
|
+
seller_id = token_data.get("user_id")
|
|
12
|
+
if not seller_id:
|
|
13
|
+
raise ValueError("seller_id es requerido o no se pudo obtener del token activo.")
|
|
14
|
+
|
|
15
|
+
return self.client.request("GET", f"/users/{seller_id}")
|
|
16
|
+
|
|
17
|
+
def get_seller_reputation(self, seller_id: int = None) -> dict:
|
|
18
|
+
"""
|
|
19
|
+
Obtiene exclusivamente las métricas de reputación del vendedor
|
|
20
|
+
(reclamos, envíos con retraso, cancelaciones e historial de color).
|
|
21
|
+
"""
|
|
22
|
+
info = self.get_seller_info(seller_id)
|
|
23
|
+
return info.get("seller_reputation", {})
|
|
24
|
+
|
|
25
|
+
def get_item_reviews(self, item_id: str, limit: int = 50, offset: int = 0) -> dict:
|
|
26
|
+
"""
|
|
27
|
+
Obtiene las reseñas y opiniones de compradores para un ID de producto específico.
|
|
28
|
+
"""
|
|
29
|
+
params = {"limit": limit, "offset": offset}
|
|
30
|
+
return self.client.request("GET", f"/reviews/item/{item_id}", params=params)
|
|
31
|
+
|
|
32
|
+
def get_trends(self, site_id: str, category_id: str = None) -> list:
|
|
33
|
+
"""
|
|
34
|
+
Obtiene las tendencias de palabras clave de búsqueda más populares para un site_id
|
|
35
|
+
(ej. MCO, MLA).
|
|
36
|
+
Si se especifica category_id, filtra por esa categoría específica.
|
|
37
|
+
"""
|
|
38
|
+
params = {}
|
|
39
|
+
if category_id:
|
|
40
|
+
params["category"] = category_id
|
|
41
|
+
|
|
42
|
+
# El endpoint de tendencias comúnmente devuelve un listado directamente
|
|
43
|
+
response = self.client.request("GET", f"/sites/{site_id}/trends/search", params=params)
|
|
44
|
+
return response if isinstance(response, list) else []
|
|
45
|
+
|
|
46
|
+
def get_questions(
|
|
47
|
+
self,
|
|
48
|
+
seller_id: int = None,
|
|
49
|
+
item_id: str = None,
|
|
50
|
+
status: str = None,
|
|
51
|
+
limit: int = 50,
|
|
52
|
+
offset: int = 0,
|
|
53
|
+
) -> dict:
|
|
54
|
+
"""
|
|
55
|
+
Busca las preguntas recibidas por un vendedor, filtrando opcionalmente por producto o
|
|
56
|
+
estado.
|
|
57
|
+
Utiliza por defecto la recomendación oficial de api_version=4.
|
|
58
|
+
"""
|
|
59
|
+
if seller_id is None:
|
|
60
|
+
token_data = self.client.token_storage.load_token()
|
|
61
|
+
seller_id = token_data.get("user_id")
|
|
62
|
+
if not seller_id:
|
|
63
|
+
raise ValueError("seller_id es requerido o no se pudo obtener del token activo.")
|
|
64
|
+
|
|
65
|
+
params = {
|
|
66
|
+
"seller_id": seller_id,
|
|
67
|
+
"api_version": 4,
|
|
68
|
+
"limit": limit,
|
|
69
|
+
"offset": offset,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if item_id:
|
|
73
|
+
params["item"] = item_id
|
|
74
|
+
if status:
|
|
75
|
+
params["status"] = status
|
|
76
|
+
|
|
77
|
+
return self.client.request("GET", "/questions/search", params=params)
|
meli_sdk/orders.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from calendar import monthrange
|
|
3
|
+
from datetime import datetime, timedelta, timezone
|
|
4
|
+
from typing import Union
|
|
5
|
+
|
|
6
|
+
from .actions import Actions
|
|
7
|
+
|
|
8
|
+
DEFAULT_UTC_OFFSET = "-05:00"
|
|
9
|
+
_OFFSET_PATTERN = re.compile(r"^([+-])(\d{2}):(\d{2})$")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _parse_utc_offset(utc_offset: str) -> timezone:
|
|
13
|
+
"""Parse a +HH:MM or -HH:MM offset into a fixed timezone."""
|
|
14
|
+
match = _OFFSET_PATTERN.fullmatch(utc_offset) if isinstance(utc_offset, str) else None
|
|
15
|
+
if match is None:
|
|
16
|
+
raise ValueError(
|
|
17
|
+
f"utc_offset must match +HH:MM or -HH:MM, got {utc_offset!r}"
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
hours = int(match.group(2))
|
|
21
|
+
minutes = int(match.group(3))
|
|
22
|
+
if hours > 14 or minutes >= 60:
|
|
23
|
+
raise ValueError(
|
|
24
|
+
f"utc_offset must match +HH:MM or -HH:MM, got {utc_offset!r}"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
sign = -1 if match.group(1) == "-" else 1
|
|
28
|
+
return timezone(sign * timedelta(hours=hours, minutes=minutes))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Orders:
|
|
32
|
+
"""Clase moderna para interactuar con el recurso de Órdenes de Mercado Libre (Composición)."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, client) -> None:
|
|
35
|
+
self.client = client
|
|
36
|
+
|
|
37
|
+
def date(
|
|
38
|
+
self,
|
|
39
|
+
year: int = None,
|
|
40
|
+
month: int = None,
|
|
41
|
+
start: int = None,
|
|
42
|
+
end: int = None,
|
|
43
|
+
*,
|
|
44
|
+
utc_offset: str = DEFAULT_UTC_OFFSET,
|
|
45
|
+
) -> dict:
|
|
46
|
+
"""Calcula el rango de fecha para las búsquedas de órdenes."""
|
|
47
|
+
tz = _parse_utc_offset(utc_offset)
|
|
48
|
+
|
|
49
|
+
if (year is None) != (month is None):
|
|
50
|
+
raise ValueError("year and month must be given together")
|
|
51
|
+
|
|
52
|
+
if year is None:
|
|
53
|
+
dt = datetime.now(tz)
|
|
54
|
+
else:
|
|
55
|
+
dt = datetime(year, month, 1, tzinfo=tz)
|
|
56
|
+
|
|
57
|
+
last_day = monthrange(dt.year, dt.month)[1]
|
|
58
|
+
start_day = 1 if start is None else start
|
|
59
|
+
end_day = last_day if end is None else end
|
|
60
|
+
|
|
61
|
+
if not 1 <= start_day <= last_day or not 1 <= end_day <= last_day:
|
|
62
|
+
raise ValueError(f"start and end must be days inside the month (1..{last_day})")
|
|
63
|
+
if start_day > end_day:
|
|
64
|
+
raise ValueError("start must be less than or equal to end")
|
|
65
|
+
|
|
66
|
+
start_date = f"{dt:%Y-%m}-{start_day:02d}T00:00:00.000{utc_offset}"
|
|
67
|
+
end_date = f"{dt:%Y-%m}-{end_day:02d}T23:59:59.999{utc_offset}"
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
"start": start_date,
|
|
71
|
+
"end": end_date,
|
|
72
|
+
"year": dt.year,
|
|
73
|
+
"month": dt.strftime("%b"),
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
def search(
|
|
77
|
+
self,
|
|
78
|
+
seller_id: int = None,
|
|
79
|
+
offset: int = 0,
|
|
80
|
+
limit: int = 50,
|
|
81
|
+
year: int = None,
|
|
82
|
+
month: int = None,
|
|
83
|
+
*,
|
|
84
|
+
utc_offset: str = DEFAULT_UTC_OFFSET,
|
|
85
|
+
status: str = None,
|
|
86
|
+
sort: str = "date_asc",
|
|
87
|
+
extra_params: dict = None,
|
|
88
|
+
) -> dict:
|
|
89
|
+
"""
|
|
90
|
+
Busca órdenes del vendedor en un periodo de tiempo.
|
|
91
|
+
Si no se proporciona seller_id, se obtiene del token activo de Mercado Libre.
|
|
92
|
+
"""
|
|
93
|
+
if sort not in ("date_asc", "date_desc"):
|
|
94
|
+
raise ValueError("sort must be 'date_asc' or 'date_desc'")
|
|
95
|
+
|
|
96
|
+
if seller_id is None:
|
|
97
|
+
token_data = self.client.token_storage.load_token()
|
|
98
|
+
seller_id = token_data.get("user_id")
|
|
99
|
+
if not seller_id:
|
|
100
|
+
raise ValueError("seller_id es requerido o no se pudo obtener del token activo.")
|
|
101
|
+
|
|
102
|
+
# Obtener rango de fecha
|
|
103
|
+
date_range = self.date(year, month, utc_offset=utc_offset)
|
|
104
|
+
|
|
105
|
+
params = {
|
|
106
|
+
"seller": seller_id,
|
|
107
|
+
"order.date_created.from": date_range["start"],
|
|
108
|
+
"order.date_created.to": date_range["end"],
|
|
109
|
+
"limit": limit,
|
|
110
|
+
"sort": sort,
|
|
111
|
+
"offset": offset,
|
|
112
|
+
}
|
|
113
|
+
if status is not None:
|
|
114
|
+
params["order.status"] = status
|
|
115
|
+
if extra_params:
|
|
116
|
+
params.update(extra_params)
|
|
117
|
+
|
|
118
|
+
return self.client.request("GET", "/orders/search", params=params)
|
|
119
|
+
|
|
120
|
+
def iter_all(
|
|
121
|
+
self,
|
|
122
|
+
seller_id: int = None,
|
|
123
|
+
year: int = None,
|
|
124
|
+
month: int = None,
|
|
125
|
+
*,
|
|
126
|
+
status: str = None,
|
|
127
|
+
sort: str = "date_asc",
|
|
128
|
+
utc_offset: str = DEFAULT_UTC_OFFSET,
|
|
129
|
+
page_size: int = 50,
|
|
130
|
+
extra_params: dict = None,
|
|
131
|
+
):
|
|
132
|
+
"""Yield every order of the period, following the search pagination.
|
|
133
|
+
|
|
134
|
+
``page_size`` must be an int between 1 and 50; it is validated on the first ``next()``,
|
|
135
|
+
because this is a generator.
|
|
136
|
+
"""
|
|
137
|
+
if (
|
|
138
|
+
isinstance(page_size, bool)
|
|
139
|
+
or not isinstance(page_size, int)
|
|
140
|
+
or not 1 <= page_size <= 50
|
|
141
|
+
):
|
|
142
|
+
raise ValueError("page_size must be an int between 1 and 50")
|
|
143
|
+
|
|
144
|
+
if extra_params and ("offset" in extra_params or "limit" in extra_params):
|
|
145
|
+
raise ValueError("extra_params must not contain 'offset' or 'limit'")
|
|
146
|
+
|
|
147
|
+
if year is None and month is None:
|
|
148
|
+
now = datetime.now(_parse_utc_offset(utc_offset))
|
|
149
|
+
year, month = now.year, now.month
|
|
150
|
+
|
|
151
|
+
if seller_id is None:
|
|
152
|
+
token_data = self.client.token_storage.load_token()
|
|
153
|
+
seller_id = token_data.get("user_id")
|
|
154
|
+
if not seller_id:
|
|
155
|
+
raise ValueError(
|
|
156
|
+
"seller_id es requerido o no se pudo obtener del token activo."
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
offset = 0
|
|
160
|
+
while True:
|
|
161
|
+
page = self.search(
|
|
162
|
+
seller_id=seller_id,
|
|
163
|
+
offset=offset,
|
|
164
|
+
limit=page_size,
|
|
165
|
+
year=year,
|
|
166
|
+
month=month,
|
|
167
|
+
status=status,
|
|
168
|
+
sort=sort,
|
|
169
|
+
utc_offset=utc_offset,
|
|
170
|
+
extra_params=extra_params,
|
|
171
|
+
)
|
|
172
|
+
results = page.get("results") or []
|
|
173
|
+
paging = page.get("paging")
|
|
174
|
+
|
|
175
|
+
for order in results:
|
|
176
|
+
yield order
|
|
177
|
+
|
|
178
|
+
if not results:
|
|
179
|
+
return
|
|
180
|
+
|
|
181
|
+
offset += len(results)
|
|
182
|
+
if paging is not None:
|
|
183
|
+
total = paging.get("total")
|
|
184
|
+
if total is not None and offset >= total:
|
|
185
|
+
return
|
|
186
|
+
elif len(results) < page_size:
|
|
187
|
+
return
|
|
188
|
+
|
|
189
|
+
def get(self, order_id: Union[int, str]) -> dict:
|
|
190
|
+
"""Obtiene información de una orden específica."""
|
|
191
|
+
return self.client.request("GET", f"/orders/{order_id}")
|
|
192
|
+
|
|
193
|
+
def get_pack(self, pack_id: Union[int, str]) -> dict:
|
|
194
|
+
"""Obtiene información de un paquete (pack) específico."""
|
|
195
|
+
return self.client.request("GET", f"/packs/{pack_id}")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
# --- Capa de Compatibilidad Clásica (Legacy) ---
|
|
199
|
+
class Order(Actions):
|
|
200
|
+
"""Clase legacy Order compatible con la estructura original."""
|
|
201
|
+
|
|
202
|
+
def __init__(self, session) -> None:
|
|
203
|
+
self.session = session
|
|
204
|
+
|
|
205
|
+
def date(
|
|
206
|
+
self, year: int = None, month: int = None, start: int = None, end: int = None
|
|
207
|
+
) -> dict:
|
|
208
|
+
# Reutilizar el cálculo de la clase Orders moderna
|
|
209
|
+
return Orders(self.session.client).date(year, month, start, end)
|
|
210
|
+
|
|
211
|
+
def list(self, offset: int = 0, year: int = None, month: int = None) -> dict:
|
|
212
|
+
# Reutilizar la búsqueda moderna pasándole el ID de seller clásico
|
|
213
|
+
seller_id = self.session.ml_user.get("id")
|
|
214
|
+
return Orders(self.session.client).search(
|
|
215
|
+
seller_id=seller_id, offset=offset, year=year, month=month
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
def info(self, id: Union[int, str]) -> dict:
|
|
219
|
+
return Orders(self.session.client).get(id)
|
|
220
|
+
|
|
221
|
+
def pack(self, order: Union[int, str]) -> dict:
|
|
222
|
+
return Orders(self.session.client).get_pack(order)
|
meli_sdk/py.typed
ADDED
|
File without changes
|
meli_sdk/session.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Union
|
|
5
|
+
|
|
6
|
+
from dotenv import load_dotenv
|
|
7
|
+
|
|
8
|
+
from .client import MeliClient
|
|
9
|
+
from .storage import FileTokenStorage
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Session:
|
|
13
|
+
"""Capa de compatibilidad clásica para la gestión de sesiones y tokens."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
keys: Union[dict, str] = None,
|
|
18
|
+
token: Union[dict, str] = None,
|
|
19
|
+
user: Union[dict, str] = None,
|
|
20
|
+
) -> None:
|
|
21
|
+
self.headers: dict = {"Authorization": "", "format-new": "true"}
|
|
22
|
+
|
|
23
|
+
# Load .env lazily: only the legacy Session depends on environment variables
|
|
24
|
+
if not keys or not token:
|
|
25
|
+
load_dotenv()
|
|
26
|
+
|
|
27
|
+
# Si no se proporcionan parámetros, usar las variables de entorno
|
|
28
|
+
self.ml_keys = read(keys) if keys else self.load_env_keys()
|
|
29
|
+
self.ml_token = read(token) if token else self.load_env_token()
|
|
30
|
+
self.ml_user = read(user) if user else {}
|
|
31
|
+
|
|
32
|
+
# Determinar el archivo para persistir el token
|
|
33
|
+
token_path = (
|
|
34
|
+
token if isinstance(token, str) and token.endswith(".json") else "ml_token.json"
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
self.token_storage = FileTokenStorage(token_path)
|
|
38
|
+
|
|
39
|
+
# Si el token se pasó como un diccionario, o si el archivo no existe, lo inicializamos
|
|
40
|
+
if isinstance(token, dict) or not os.path.exists(token_path):
|
|
41
|
+
self.token_storage.save_token(self.ml_token)
|
|
42
|
+
|
|
43
|
+
# Inicializar el cliente moderno internamente
|
|
44
|
+
self.client = MeliClient(
|
|
45
|
+
client_id=self.ml_keys.get("client_id", ""),
|
|
46
|
+
client_secret=self.ml_keys.get("client_secret", ""),
|
|
47
|
+
token_storage=self.token_storage,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
self.access()
|
|
51
|
+
|
|
52
|
+
def access(self) -> dict:
|
|
53
|
+
"""Actualiza el token de acceso si ha expirado delegando en el cliente moderno."""
|
|
54
|
+
self.client.ensure_token_valid()
|
|
55
|
+
self.ml_token = self.token_storage.load_token()
|
|
56
|
+
self.headers["Authorization"] = f"Bearer {self.ml_token.get('access_token')}"
|
|
57
|
+
return self.ml_token
|
|
58
|
+
|
|
59
|
+
def refresh(self) -> dict:
|
|
60
|
+
"""Obtiene un nuevo token de acceso usando el refresh token."""
|
|
61
|
+
refresh_token_str = self.ml_token.get("refresh_token")
|
|
62
|
+
if not refresh_token_str:
|
|
63
|
+
raise ValueError("No refresh token available to perform renewal.")
|
|
64
|
+
|
|
65
|
+
self.ml_token = self.client.refresh_token(refresh_token_str)
|
|
66
|
+
self.headers["Authorization"] = f"Bearer {self.ml_token.get('access_token')}"
|
|
67
|
+
return self.ml_token
|
|
68
|
+
|
|
69
|
+
def load_env_keys(self) -> dict:
|
|
70
|
+
"""Carga las credenciales de Mercado Libre desde las variables de entorno."""
|
|
71
|
+
return {
|
|
72
|
+
"client_id": os.getenv("ML_CLIENT_ID"),
|
|
73
|
+
"client_secret": os.getenv("ML_CLIENT_SECRET"),
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
def load_env_token(self) -> dict:
|
|
77
|
+
"""Carga el token desde las variables de entorno."""
|
|
78
|
+
return {
|
|
79
|
+
"access_token": os.getenv("ML_ACCESS_TOKEN"),
|
|
80
|
+
"refresh_token": os.getenv("ML_REFRESH_TOKEN"),
|
|
81
|
+
"date": os.getenv("ML_TOKEN_DATE", datetime.isoformat(datetime.now())),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def read(file_name: Union[dict, str]) -> dict:
|
|
86
|
+
"""Lee un archivo JSON o retorna directamente el diccionario proporcionado."""
|
|
87
|
+
if isinstance(file_name, str) and file_name.endswith(".json"):
|
|
88
|
+
if not os.path.exists(file_name):
|
|
89
|
+
return {}
|
|
90
|
+
with open(file_name, "r") as content:
|
|
91
|
+
return json.load(content)
|
|
92
|
+
return file_name
|
meli_sdk/shipments.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from typing import Union
|
|
2
|
+
|
|
3
|
+
from .actions import Actions
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Shipments:
|
|
7
|
+
"""Clase moderna para interactuar con el recurso de Envíos (Shipments) de Mercado Libre
|
|
8
|
+
(Composición)."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, client) -> None:
|
|
11
|
+
self.client = client
|
|
12
|
+
|
|
13
|
+
def get(self, shipment_id: Union[int, str]) -> dict:
|
|
14
|
+
"""Obtiene información de un envío específico."""
|
|
15
|
+
return self.client.request("GET", f"/shipments/{shipment_id}")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# --- Capa de Compatibilidad Clásica (Legacy) ---
|
|
19
|
+
class Ship(Actions):
|
|
20
|
+
"""Clase legacy Ship compatible con la estructura original."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, session) -> None:
|
|
23
|
+
self.session = session
|
|
24
|
+
|
|
25
|
+
def info(self, id: Union[int, str]) -> dict:
|
|
26
|
+
return Shipments(self.session.client).get(id)
|