MeliAPIClient 0.0.1__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.
@@ -0,0 +1,3 @@
1
+ from MeliAPIClient.session import Session
2
+ from MeliAPIClient.order import Order
3
+ from MeliAPIClient.actions import Actions
@@ -0,0 +1,36 @@
1
+ from requests import request
2
+ import json
3
+
4
+
5
+ class Actions:
6
+
7
+ def get(self, url, headers, params={}, data={}):
8
+
9
+ response = request("GET",
10
+ url,
11
+ headers=headers,
12
+ params=params,
13
+ data=data)
14
+
15
+ if response.status_code == 404:
16
+ return False
17
+
18
+ return json.loads(response.text)
19
+
20
+ def post(self, url: str, headers, params: dict = {},
21
+ data: dict = {}, file: dict = {}):
22
+
23
+ response = request("POST",
24
+ url,
25
+ headers=headers,
26
+ params=params,
27
+ data=data,
28
+ files=file)
29
+
30
+ if response.status_code == 404:
31
+ response = json.loads(response.text)
32
+ return print("[ERROR] ", response)
33
+
34
+ elif response.status_code == 204:
35
+ response = json.loads(response.text)
36
+ return print(response)
MeliAPIClient/bill.py ADDED
@@ -0,0 +1,42 @@
1
+ from .actions import Actions
2
+
3
+
4
+ class Bill(Actions):
5
+
6
+ def __init__(self, session) -> None:
7
+ self.session = session
8
+
9
+ def info(self, id):
10
+
11
+ '''Return billing information from a order by id'''
12
+
13
+ url = f"https://api.mercadolibre.com/orders/{id}/billing_info"
14
+
15
+ response = self.get(url, self.session.headers)
16
+
17
+ return response
18
+
19
+ def documents(self, pack_id):
20
+
21
+ '''check if order has a invoice return True of False'''
22
+
23
+ url = f"https://api.mercadolibre.com/packs/{pack_id}/fiscal_documents"
24
+
25
+ response = self.get(url, self.session.headers)
26
+
27
+ if response is False:
28
+ return response
29
+
30
+ return True
31
+
32
+ def upload(self, id, url_file):
33
+
34
+ url = f"https://api.mercadolibre.com/packs/{id}/fiscal_documents"
35
+
36
+ files = {
37
+ 'fiscal_document': open(url_file, 'rb')
38
+ }
39
+
40
+ response = self.post(url, self.session.headers, fl=files)
41
+
42
+ return response
MeliAPIClient/order.py ADDED
@@ -0,0 +1,66 @@
1
+ from calendar import monthrange
2
+ from datetime import datetime
3
+ from .actions import Actions
4
+
5
+
6
+ class Order(Actions):
7
+
8
+ def __init__(self, session) -> None:
9
+
10
+ self.session = session
11
+
12
+ def date(self, year=None, month=None):
13
+
14
+ dt = datetime.now()
15
+
16
+ if year is not None and month is not None:
17
+ dt = datetime(year, month, 1)
18
+
19
+ days = monthrange(int(dt.strftime("%Y")), int(dt.strftime("%m")))[1]
20
+
21
+ date: dict = {"start": dt.strftime("%Y-%m-01T00:00:00.000-00:00"),
22
+ "end": dt.strftime(f"%Y-%m-{days}T23:59:59.000-00:00"),
23
+ "year": int(dt.strftime("%Y")),
24
+ "month": str(dt.strftime("%b"))}
25
+
26
+ return date
27
+
28
+ def list(self, offset=0, year=None, month=None):
29
+
30
+ '''read orders from mercado libre api, max 50 orders, and starts with \
31
+ a order offset to read new orders'''
32
+
33
+ # set date range
34
+ date = self.date(year, month)
35
+
36
+ # endpoint
37
+ url = "https://api.mercadolibre.com/orders/search"
38
+
39
+ params = {
40
+ "seller": self.session.ml_user["id"],
41
+ "order.date_created.from": date["start"],
42
+ "order.date_created.to": date["end"],
43
+ "limit": 50,
44
+ "sort": "date_asc",
45
+ "offset": offset
46
+ }
47
+ print(params)
48
+ response = self.get(url, self.session.headers, params)
49
+
50
+ return response
51
+
52
+ def info(self, id):
53
+
54
+ url = f"https://api.mercadolibre.com/orders/{id}"
55
+
56
+ response = self.get(url, self.session.headers)
57
+
58
+ return response
59
+
60
+ def pack(self, order):
61
+
62
+ url = f"https://api.mercadolibre.com/packs/{order}"
63
+
64
+ response = self.get(url, self.session.headers)
65
+
66
+ return response
@@ -0,0 +1,74 @@
1
+ from datetime import datetime, timedelta
2
+ from requests import request
3
+ import json
4
+
5
+
6
+ class Session:
7
+
8
+ def __init__(self, keys: json, token: json, user: json) -> None:
9
+
10
+ self.headers: dict = {
11
+ "Authorization": "",
12
+ "format-new": "true"
13
+ }
14
+
15
+ self.ml_keys = read(keys)
16
+ self.ml_token = read(token)
17
+ self.ml_user = read(user)
18
+
19
+ self.access()
20
+
21
+ def access(self) -> dict:
22
+
23
+ time_flag = timedelta(hours=5, minutes=59, seconds=0.0)
24
+ date_token = datetime.fromisoformat(self.ml_token['date'])
25
+ token_time = datetime.now()-date_token
26
+
27
+ if time_flag > token_time:
28
+ self.headers['Authorization'] = \
29
+ f'Bearer {self.ml_token["access_token"]}'
30
+ return self.ml_token
31
+
32
+ self.refresh()
33
+ self.headers['Authorization'] = \
34
+ f'Bearer {self.ml_token["access_token"]}'
35
+
36
+ return self.ml_token
37
+
38
+ def refresh(self) -> None:
39
+
40
+ url = "https://api.mercadolibre.com/oauth/token"
41
+
42
+ payload: dict = {
43
+ "grant_type": "refresh_token",
44
+ "client_id": self.ml_keys['client_id'],
45
+ "client_secret": self.ml_keys['client_secret'],
46
+ "refresh_token": self.ml_token['refresh_token']
47
+ }
48
+
49
+ headers: dict = {
50
+ 'accept': 'application/json',
51
+ 'content-type': 'application/x-www-form-urlencoded'
52
+ }
53
+
54
+ response = request("POST", url, headers=headers, data=payload)
55
+
56
+ ml_response: dict = json.loads(response.text)
57
+ ml_response["date"] = datetime.isoformat(datetime.now())
58
+
59
+ write("ml_token.json", ml_response)
60
+
61
+
62
+ def read(file_name: str) -> dict:
63
+ with open(file_name, "r") as content:
64
+ return (json.load(content))
65
+
66
+
67
+ def write(file_name: str, data: dict) -> None:
68
+ with open(file_name, 'w') as content:
69
+ json.dump(data, content, ensure_ascii=False, indent=2)
70
+
71
+
72
+ if __name__ == "__main__":
73
+ session = Session()
74
+ print(session.user["id"])
MeliAPIClient/ship.py ADDED
@@ -0,0 +1,18 @@
1
+ from .actions import Actions
2
+
3
+
4
+ class Ship(Actions):
5
+
6
+ def __init__(self, session) -> None:
7
+
8
+ self.session = session
9
+
10
+ def info(self, id) -> dict:
11
+
12
+ '''Return shipping information from a order by id'''
13
+
14
+ url = f"https://api.mercadolibre.com/shipments/{id}"
15
+
16
+ response = self.get(url, self.session.headers)
17
+
18
+ return response
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.1
2
+ Name: MeliAPIClient
3
+ Version: 0.0.1
4
+ Summary: Este paquete nos permite consumir el API de mercado libre
5
+ Home-page: https://github.com/andresroh/MeliAPIClient
6
+ Author: Camilo Andrés Rodríguez Higuera
7
+ Author-email: hola@camilordz.com
8
+ License: MIT
9
+ Keywords: python,mercado libre,mercadolibre.com
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Software Development :: Build Tools
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: requests
17
+
18
+ # MeliAPIClient
19
+
20
+ Este módulo permite interactuar con el API de mercado libre para leer, actualizar y crear productos y órdenes. Este módulo es útil para integrar el API de Mercado libre con otros sistemas.
21
+
22
+ ## Instalación
23
+
24
+ Para instalar este módulo, ejecute el siguiente comando:
25
+
26
+ ```bash
27
+ pip install MeliAPIClient
28
+ ```
29
+
30
+ ### Uso básico
31
+
32
+ Para usar este módulo, debemos guardar las credenciales en 3 archivos tipo JSON. El archivo `ml_keys` almacena el `client_id` y `client_secret`, `ml_token` almacena la información para renovar la sesión después del límite de 6 horas, y `ml_user` que almacena la información del usuario, donde el dato más importante es el ID del usuario.
33
+
34
+ ```python
35
+ from MeliAPIClient import Session
36
+ from MeliAPIClient import Order
37
+
38
+
39
+ def run():
40
+
41
+ session = Session("ml_keys.json", 'ml_token.json', "ml_user.json")
42
+ orders = Order(session)
43
+
44
+ orders.list(year=2024, month=5)
45
+
46
+
47
+ if __name__ == "__main__":
48
+ run()
49
+ ```
50
+
51
+ ## Créditos
52
+
53
+ Camilo Andrés Rodriguez
54
+
55
+ ## referencias
56
+
57
+ https://developers.mercadolibre.com/
58
+
59
+ ## Licencia
60
+
61
+ Este proyecto está bajo la Licencia [MIT].
@@ -0,0 +1,10 @@
1
+ MeliAPIClient/__init__.py,sha256=-MWwWZTibxeHdWaDiPNgBtXEPS4itojHnkSVey7GC0k,122
2
+ MeliAPIClient/actions.py,sha256=RQXTD5DKpBBAYfobXlPBiAxZEpeicwki-KSeFkBUkaA,1012
3
+ MeliAPIClient/bill.py,sha256=AddPUwAFZKAWQbLfijbs2cdL_UP_hrS6H-j0tR7Q9iY,965
4
+ MeliAPIClient/order.py,sha256=bcfmk7fGHb717iAKPYH4zF_NLoTyCPeVFP_Fp9TUBok,1760
5
+ MeliAPIClient/session.py,sha256=69UnZYD-kXLd_zFaUQEhc6dbAYQpgzlMcuwpyr__Aas,2011
6
+ MeliAPIClient/ship.py,sha256=zYqlfjuEmH1fTAKWywFvzLeMS1ipJYD--hYr4kKLw_0,364
7
+ MeliAPIClient-0.0.1.dist-info/METADATA,sha256=c1b11erqUfPdwONPUZ3xpt80i_dsnHSPvSf3eqBJujc,1733
8
+ MeliAPIClient-0.0.1.dist-info/WHEEL,sha256=5sUXSg9e4bi7lTLOHcm6QEYwO5TIF1TNbTSVFVjcJcc,92
9
+ MeliAPIClient-0.0.1.dist-info/top_level.txt,sha256=s2zCcSYLZCh3Ms7tnho_S9DZI1gmdzj-IyU_Ly4IYKI,14
10
+ MeliAPIClient-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.41.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ MeliAPIClient