rb-commons 0.2.2__py3-none-any.whl → 0.2.4__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,91 @@
1
+ import json
2
+ import requests
3
+ from rb_commons.http.exceptions import BadRequestException, InternalException
4
+ from requests import RequestException
5
+
6
+ class BaseAPI:
7
+ def __init__(self, base_url: str):
8
+ self.BASE_URL = base_url
9
+
10
+ def _make_request(self, method: str, path: str, data: dict = None,
11
+ params: dict = None, headers: dict = None, reset_base_url: bool = False, form_encoded: bool = False) -> requests.Response:
12
+ """
13
+ A general method to make HTTP requests (GET, POST, etc.)
14
+
15
+ This method abstracts the process of making HTTP requests, allowing for
16
+ different types of requests (GET, POST, PUT, DELETE) to be easily performed
17
+ by specifying the method and other parameters. This adheres to the DRY
18
+ (Don't Repeat Yourself) principle by centralizing request handling.
19
+
20
+ :param method: HTTP method to use for the request (e.g., 'GET', 'POST', 'PUT', 'DELETE').
21
+ :param path: The API endpoint path to which the request is made. This should be
22
+ relative to the base URL defined in the class.
23
+ :param data: Optional dictionary containing the data to be sent in the body of
24
+ the request (used for POST and PUT requests). Default is None.
25
+ :param params: Optional dictionary containing query parameters to be included
26
+ in the request URL. Default is None.
27
+ :param headers: Optional dictionary containing any custom headers to be sent
28
+ with the request. Default is None.
29
+ :return: Response object containing the server's response to the HTTP request.
30
+ :raises HttpException: Raises a custom HttpException if the request fails for
31
+ any reason, including invalid HTTP methods, network issues,
32
+ or JSON parsing errors.
33
+
34
+ The method constructs the full URL from the base URL and the provided path.
35
+ It uses a dictionary to map HTTP methods to their respective request functions
36
+ from the requests library. After making the request, it checks the response
37
+ status and attempts to parse the response as JSON.
38
+ """
39
+ url = self.BASE_URL + path
40
+
41
+ if reset_base_url:
42
+ url = path
43
+
44
+ try:
45
+ request_methods = {
46
+ 'POST': requests.post,
47
+ 'GET': requests.get,
48
+ 'PUT': requests.put,
49
+ 'DELETE': requests.delete
50
+ }
51
+
52
+ if method not in request_methods:
53
+ raise BadRequestException(f"Unsupported HTTP method: {method}")
54
+
55
+ kwargs = {
56
+ 'params': params,
57
+ 'headers': headers,
58
+ 'data' if form_encoded else 'json': data
59
+ }
60
+
61
+ response = request_methods[method](url, **kwargs)
62
+
63
+ data = response.json()
64
+
65
+ if not (200 <= response.status_code < 300):
66
+ error_message = data.get("message")
67
+ if error_message is not None:
68
+ raise BadRequestException(error_message)
69
+
70
+ raise BadRequestException(f"Unexpected error occured: {response.text}")
71
+
72
+ return response
73
+
74
+ except RequestException as e:
75
+ raise BadRequestException(f"Request failed: {e}")
76
+ except (json.JSONDecodeError, ValueError) as e:
77
+ raise InternalException(f"Failed to parse JSON: {e}")
78
+ except Exception as e:
79
+ raise InternalException("Something went wrong")
80
+
81
+ def _post(self, path: str, data: dict, headers: dict = None, params: dict = None, reset_base_url: bool = False, form_encoded: bool = False) -> requests.Response:
82
+ return self._make_request('POST', path, data=data, headers=headers, params=params, reset_base_url=reset_base_url, form_encoded=form_encoded)
83
+
84
+ def _get(self, path: str, params: dict = None, headers: dict = None, reset_base_url: bool = False, form_encoded: bool = False) -> requests.Response:
85
+ return self._make_request('GET', path, params=params, headers=headers, reset_base_url=reset_base_url, form_encoded=form_encoded)
86
+
87
+ def _put(self, path: str, params: dict = None, data: dict = None, headers: dict = None, reset_base_url: bool = False, form_encoded: bool = False) -> requests.Response:
88
+ return self._make_request('PUT', path, params=params, data=data, headers=headers, reset_base_url=reset_base_url, form_encoded=form_encoded)
89
+
90
+ def _delete(self, path: str, headers: dict = None, reset_base_url: bool = False, form_encoded: bool = False) -> requests.Response:
91
+ return self._make_request('DELETE', path, headers=headers, reset_base_url=reset_base_url, form_encoded=form_encoded)
@@ -0,0 +1,46 @@
1
+ import aiocache
2
+ import consul
3
+ from fastapi import HTTPException, Request
4
+ from rb_commons.configs.config import configs
5
+
6
+
7
+ class ServiceDiscovery:
8
+ def __init__(self) -> None:
9
+ self.consul_client = consul.Consul(host=configs.consul_host, port=configs.consul_port)
10
+ self.cache = aiocache.Cache(aiocache.SimpleMemoryCache)
11
+
12
+ async def get_service_instances(self, service_name: str) -> dict:
13
+ """Get a healthy service instance from Consul"""
14
+ index, services = self.consul_client.health.service(service_name, passing=True)
15
+
16
+ if not services:
17
+ raise HTTPException(status_code=503,
18
+ detail="Service not available")
19
+ return services
20
+
21
+ def select_instance(self, instances: list, request: Request) -> dict:
22
+ """Select instance using consistent hashing"""
23
+ if not instances:
24
+ raise HTTPException(status_code=503, detail="No healthy instances")
25
+
26
+ key = request.client.host
27
+ hash_value = hash(key)
28
+ return instances[hash_value % len(instances)]
29
+
30
+ async def _get_cached_service_instances(self, service_name: str) -> list:
31
+ """Get service instances with caching"""
32
+ cache_key = f"service:{service_name}"
33
+ instances = await self.cache.get(cache_key)
34
+ if not instances:
35
+ instances = await self.get_service_instances(service_name)
36
+ if instances:
37
+ await self.cache.set(cache_key, instances, ttl=30) # Cache for 30 seconds
38
+ return instances
39
+
40
+ def build_target_url(self, instance: dict, path: str,
41
+ request: Request) -> str:
42
+ """Build target URL with proper path handling"""
43
+ service_address = instance['Service']['Address'] or instance['Node']['Address']
44
+ service_port = instance['Service']['Port']
45
+ target_path = request.url.path.replace(path, "", 1)
46
+ return f"http://{service_address}:{service_port}{path}{target_path}"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rb-commons
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: Commons of project and simplified orm based on sqlalchemy.
5
5
  Home-page: https://github.com/RoboSell-organization/rb-commons
6
6
  Author: Abdulvoris
@@ -6,6 +6,8 @@ rb_commons/configs/config.py,sha256=zla62zy3UfjE2YpvSDwsfhP2Qsm0BbGsycngfyiVvE4,
6
6
  rb_commons/configs/injections.py,sha256=6B1EOgIGnkWv3UrFaV9PRgG0-CJAbLu1UZ3kq-SjPVU,273
7
7
  rb_commons/configs/rabbitmq.py,sha256=vUqa_PcZkPp1lX0B6HLSAXVMUcPR2_8-8cN-C7xFxRI,741
8
8
  rb_commons/http/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ rb_commons/http/base_api.py,sha256=W-nXoO0TcngSMVgmJHFRdXeOrI9FDPi36I_Ih8hP3VE,4824
10
+ rb_commons/http/consul.py,sha256=fFqvMueo_-AWxOE4NEsikC4tvHbS6QD8l5JnoW8jyIQ,2026
9
11
  rb_commons/http/exceptions.py,sha256=EGRMr1cRgiJ9Q2tkfANbf0c6-zzXf1CD6J3cmCaT_FA,1885
10
12
  rb_commons/orm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
13
  rb_commons/orm/exceptions.py,sha256=1aMctiEwrPjyehoXVX1l6ML5ZOhmDkmBISzlTD5ey1Y,509
@@ -16,7 +18,7 @@ rb_commons/schemes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuF
16
18
  rb_commons/schemes/jwt.py,sha256=F66JJDhholuOPPzlKeoC6f1TL4gXg4oRUrV5yheNpyo,1675
17
19
  rb_commons/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
20
  rb_commons/utils/media.py,sha256=KNY_9SdRa3Rp7d3B1tZaXkhmzVa65RcS62BYwZP1bVM,332
19
- rb_commons-0.2.2.dist-info/METADATA,sha256=_WLAr4eS8xznDVugZa1-aRQz4eKYo4_2Y12t8P7OH8c,6570
20
- rb_commons-0.2.2.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
21
- rb_commons-0.2.2.dist-info/top_level.txt,sha256=HPx_WAYo3_fbg1WCeGHsz3wPGio1ucbnrlm2lmqlJog,11
22
- rb_commons-0.2.2.dist-info/RECORD,,
21
+ rb_commons-0.2.4.dist-info/METADATA,sha256=I_QUMkGmUek2TX9zJIDw_U5Ws0lV5JhrwXS22Tw-t_g,6570
22
+ rb_commons-0.2.4.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
23
+ rb_commons-0.2.4.dist-info/top_level.txt,sha256=HPx_WAYo3_fbg1WCeGHsz3wPGio1ucbnrlm2lmqlJog,11
24
+ rb_commons-0.2.4.dist-info/RECORD,,