Skip to content

Commit 4c23b93

Browse files
committed
refactured pypesa
1 parent 96308b2 commit 4c23b93

File tree

2 files changed

+84
-20
lines changed

2 files changed

+84
-20
lines changed

pypesa/__init__.py

+74-12
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ class Mpesa(object):
2929
def __init__(
3030
self,
3131
auth_path: Optional[str] = "keys.json",
32-
environment: Optional[str] = "testing",
32+
environment: Optional[str] = "sandbox",
3333
):
3434
"""
3535
Mpesa API client for Python
@@ -44,14 +44,24 @@ def __init__(
4444

4545
@property
4646
def authenticate(self) -> bool:
47-
""""""
47+
"""
48+
Property to check If the user is has has included auth keys
49+
either manually or through auth json file(keys.json)
50+
51+
>> import pypesa
52+
>> mpesa = pypesa()
53+
>> mpesa.authenticate
54+
55+
Return True if the environment has auth keys
56+
False if auth are not included
57+
"""
4858

4959
if self.auth_keys.get("public_key") and self.auth_keys.get("api_key"):
5060
self._encrypted_api_key = self.__generate_encrypted_key()
5161
return True
5262

5363
elif os.path.isfile(self.auth_path):
54-
print("loading from file")
64+
# print("loading from file")
5565
self.auth_keys = self.load_keys(self.auth_path)
5666
if self.auth_keys:
5767
self._encrypted_api_key = self.__generate_encrypted_key()
@@ -72,7 +82,17 @@ def authorized_method(self, *args, **kwargs):
7282

7383
@staticmethod
7484
def load_keys(keys_filename: Union[str, Path]) -> dict:
75-
""""""
85+
"""
86+
Pypesa internal method to load the auth file
87+
88+
>> import pypesa
89+
>> mpesa = pypesa()
90+
>> pypesa.load_keys()
91+
92+
Return keys Dict if auth file is present
93+
94+
Raise FileNotFoundError if auth file is absent
95+
"""
7696
try:
7797

7898
with open(keys_filename, "r") as auth:
@@ -88,7 +108,11 @@ def load_keys(keys_filename: Union[str, Path]) -> dict:
88108
raise LoadingKeyError
89109

90110
def __generate_encrypted_key(self, session: Optional[bool] = False) -> str:
91-
""""""
111+
"""
112+
113+
Method use to Encrypt the api key and public key
114+
so as to get a secure RSA Encrypted key
115+
"""
92116
try:
93117
pub_key = self.auth_keys.get("public_key")
94118
raw_key = self.auth_keys.get("api_key")
@@ -100,7 +124,6 @@ def __generate_encrypted_key(self, session: Optional[bool] = False) -> str:
100124
rsa_public_key = RSA.importKey(public_key_string)
101125
raw_cipher = rsa_cipher.new(rsa_public_key)
102126
encrypted_key = raw_cipher.encrypt(raw_key.encode())
103-
104127
return base64.b64encode(encrypted_key).decode("utf-8")
105128

106129
except Exception as bug:
@@ -111,10 +134,16 @@ def __generate_encrypted_key(self, session: Optional[bool] = False) -> str:
111134

112135
@property
113136
def path_to_auth(self) -> str:
137+
"""
138+
Return Path to Authentication file
139+
"""
114140
return self.auth_path
115141

116142
@path_to_auth.setter
117143
def path_to_auth(self, auth_path: Union[str, Path]) -> str:
144+
"""
145+
Setting new path to the authentication file
146+
"""
118147
if isinstance(auth_path, str):
119148
self.auth_path = auth_path
120149
return self.auth_path
@@ -124,20 +153,37 @@ def path_to_auth(self, auth_path: Union[str, Path]) -> str:
124153

125154
@property
126155
def environment(self) -> Union[sandbox, production]:
156+
"""
157+
Return the Environment the Pypesa is running
158+
159+
whether its Sandbox | Production
160+
"""
127161
return self.urls
128162

129163
@environment.setter
130164
def environment(self, enviro: str) -> Union[sandbox, production]:
165+
"""
166+
Set new pypesa environment
167+
168+
Eg. changing env to production;
169+
170+
>> import pypesa
171+
>> mpesa = pypesa()
172+
>> mpesa.environment = "production"
173+
<Using Production Urls>
174+
"""
131175
if isinstance(enviro, str):
132-
if enviro in ["testing", "production"]:
133-
if enviro == "testing":
176+
if enviro in ["sandbox", "production"]:
177+
if enviro == "sandbox":
134178
self.urls = sandbox()
135179
else:
136180
self.urls = production()
137181
print(self.urls)
138182
return self.urls
139-
return ValueError("Environment must be either testing or production")
140-
return TypeError(f"environment must be of type string not {type(enviro)}")
183+
raise ValueError(
184+
"Environment must be either sandbox or production")
185+
raise TypeError(
186+
f"environment must be of type string not {type(enviro)}")
141187

142188
@property
143189
def api_key(self) -> str:
@@ -164,21 +210,33 @@ def api_key(self, Api_key: str) -> str:
164210

165211
@property
166212
def public_key(self) -> str:
213+
"""
214+
Return the current Public key
215+
"""
167216
return self.auth_keys.get("public_key")
168217

169218
@public_key.setter
170219
def public_key(self, pb_key: str) -> str:
220+
"""
221+
Set a new public key
222+
"""
171223
if isinstance(pb_key, str):
172224
self.auth_keys["public_key"] = pb_key
173225
return self.auth_keys["public_key"]
174226
raise TypeError(f"Public key must be a string not a {type(pb_key)}")
175227

176228
@property
177229
def origin_address(self) -> str:
230+
"""
231+
Return the current origin address
232+
"""
178233
return self._origin_ip
179234

180235
@origin_address.setter
181236
def origin_address(self, ip_address: str) -> str:
237+
"""
238+
Set a new origin address
239+
"""
182240
if isinstance(ip_address, str):
183241
self._origin_ip = ip_address
184242
return self._origin_ip
@@ -187,6 +245,10 @@ def origin_address(self, ip_address: str) -> str:
187245

188246
@authenticated
189247
def default_headers(self, auth_key: Optional[str] = "") -> dict:
248+
"""
249+
Generate Default header to be used during a Request
250+
251+
"""
190252
if not auth_key:
191253
auth_key = self.__generate_encrypted_key(session=True)
192254
return {
@@ -205,9 +267,9 @@ def get_session_id(self) -> str:
205267
session_id = response["output_SessionID"]
206268
response_code = response["output_ResponseCode"]
207269
description = response["output_ResponseDesc"]
208-
print(description, " ", response_code)
270+
# print(description, " ", response_code)
209271
if response_code == "INS-989":
210-
print("Session creation failed!!")
272+
# print("Session creation failed!!")
211273
raise AuthenticationError
212274
return session_id
213275
except Exception as bug:

pypesa/service_urls.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -73,11 +73,12 @@ class Required(object):
7373

7474

7575
class sandbox(Required):
76-
def __init__(self):
77-
"""
78-
Service URL to be used during sandbox Development
76+
"""
77+
Service URL to be used during sandbox Development
78+
79+
"""
7980

80-
"""
81+
def __init__(self):
8182
self.session_id = (
8283
"https://openapi.m-pesa.com/sandbox/ipg/v2/vodacomTZN/getSession/"
8384
)
@@ -105,12 +106,13 @@ def __str__(self) -> str:
105106

106107

107108
class production(Required):
108-
def __init__(self):
109-
"""
109+
"""
110+
111+
Service URL to be used for Production Development
110112
111-
Service URL to be used for Production Development
113+
"""
112114

113-
"""
115+
def __init__(self):
114116
self.session_id = (
115117
"https://openapi.m-pesa.com/openapi/ipg/v2/vodacomTZN/getSession/"
116118
)

0 commit comments

Comments
 (0)