2121from .config import CloudEndureConfig
2222from .exceptions import CloudEndureException , CloudEndureUnauthorized
2323
24- HOST : str = os .environ .get ('CLOUDENDURE_HOST' , 'https://console.cloudendure.com' )
25- API_VERSION : str = os .environ .get ('CLOUDENDURE_API_VERSION' , 'latest' ).lower ()
26- AUTH_TTL = datetime .timedelta (seconds = int (os .environ .get ('CLOUDENDURE_AUTH_TTL' , '3600' ))) # Default to 60 minutes.
27- METHOD_TYPES = ['get' , 'post' , 'patch' , 'delete' , 'put' ]
24+ HOST : str = os .environ .get ("CLOUDENDURE_HOST" , "https://console.cloudendure.com" )
25+ API_VERSION : str = os .environ .get ("CLOUDENDURE_API_VERSION" , "latest" ).lower ()
26+ AUTH_TTL = datetime .timedelta (
27+ seconds = int (os .environ .get ("CLOUDENDURE_AUTH_TTL" , "3600" ))
28+ ) # Default to 60 minutes.
29+ METHOD_TYPES = ["get" , "post" , "patch" , "delete" , "put" ]
2830
2931logger = logging .getLogger (__name__ )
3032
@@ -40,7 +42,7 @@ class CloudEndureAPI:
4042
4143 """
4244
43- TOP_LEVEL : List [str ] = [' projects' , ' blueprints' ]
45+ TOP_LEVEL : List [str ] = [" projects" , " blueprints" ]
4446
4547 def __init__ (self , * args , ** kwargs ):
4648 """Initialize the CloudEndure API client.
@@ -51,19 +53,26 @@ def __init__(self, *args, **kwargs):
5153 """
5254 time_now = datetime .datetime .utcnow ()
5355
54- self .api_endpoint : str = f' { HOST } /api/{ API_VERSION } '
56+ self .api_endpoint : str = f" { HOST } /api/{ API_VERSION } "
5557 self .config = CloudEndureConfig ()
5658
5759 self .projects : List [str ] = []
5860 self .session = requests .Session ()
59- _xsrf_token : str = self .config .active_config .get ('token' , '' )
60- self .session .headers : Dict [str , str ] = {'Content-Type' : 'application/json' , 'Accept' : 'text/plain' , }
61- self .timestamps : Dict [str , Any ] = {'created' : time_now , 'updated' : time_now , 'last_call' : time_now }
61+ _xsrf_token : str = self .config .active_config .get ("token" , "" )
62+ self .session .headers : Dict [str , str ] = {
63+ "Content-Type" : "application/json" ,
64+ "Accept" : "text/plain" ,
65+ }
66+ self .timestamps : Dict [str , Any ] = {
67+ "created" : time_now ,
68+ "updated" : time_now ,
69+ "last_call" : time_now ,
70+ }
6271
6372 if _xsrf_token :
64- self .session .headers .update ({' X-XSRF-TOKEN' : _xsrf_token })
73+ self .session .headers .update ({" X-XSRF-TOKEN" : _xsrf_token })
6574
66- def login (self , username = '' , password = '' ):
75+ def login (self , username = "" , password = "" ):
6776 """Login to the CloudEndure API console.
6877
6978 Args:
@@ -81,27 +90,35 @@ def login(self, username='', password=''):
8190 _xsrf_token (str): The XSRF token to be used for subsequent API requests.
8291
8392 """
84- endpoint : str = ' login'
85- _username : str = self .config .active_config [' username' ] or username
86- _password : str = self .config .active_config [' password' ] or password
87- _auth : Dict [str , str ] = {' username' : _username , ' password' : _password }
93+ endpoint : str = " login"
94+ _username : str = self .config .active_config [" username" ] or username
95+ _password : str = self .config .active_config [" password" ] or password
96+ _auth : Dict [str , str ] = {" username" : _username , " password" : _password }
8897
8998 # Attempt to login to the CloudEndure API via a POST request.
90- response : requests .Response = self .api_call ('login' , 'post' , data = json .dumps (_auth ))
99+ response : requests .Response = self .api_call (
100+ "login" , "post" , data = json .dumps (_auth )
101+ )
91102 # response: requests.Response = self.session.post(f'{self.api_endpoint}/{endpoint}', json=_auth)
92103
93104 # Check whether or not the request was successful.
94105 if response .status_code not in [200 , 307 ]:
95106 if response .status_code == 401 :
96- logger .error ('Bad CloudEndure Credentials! Check your username/password and try again!' )
107+ logger .error (
108+ "Bad CloudEndure Credentials! Check your username/password and try again!"
109+ )
97110 elif response .status_code == 402 :
98- logger .error ('No CloudEndure License! Please configure your account and try again!' )
111+ logger .error (
112+ "No CloudEndure License! Please configure your account and try again!"
113+ )
99114 elif response .status_code == 429 :
100- logger .error ('CloudEndure authentication failure limit reached! Please try again later!' )
115+ logger .error (
116+ "CloudEndure authentication failure limit reached! Please try again later!"
117+ )
101118 raise CloudEndureUnauthorized ()
102119
103120 # print('response: ', response, response.cookies)
104- _xsrf_token : str = str (response .cookies [' XSRF-TOKEN' ])
121+ _xsrf_token : str = str (response .cookies [" XSRF-TOKEN" ])
105122
106123 # Strip the XSRF token of wrapping double-quotes from the cookie.
107124 if _xsrf_token .startswith ('"' ) and _xsrf_token .endswith ('"' ):
@@ -110,21 +127,25 @@ def login(self, username='', password=''):
110127 # Set the XSRF token data on the CloudEndureAPI object.
111128 time_now = datetime .datetime .utcnow ()
112129 self .config .update_token (_xsrf_token )
113- self .session .headers .update ({' X-XSRF-TOKEN' : _xsrf_token })
114- self .timestamps [' last_call' ] = time_now
130+ self .session .headers .update ({" X-XSRF-TOKEN" : _xsrf_token })
131+ self .timestamps [" last_call" ] = time_now
115132 return True
116133
117134 @staticmethod
118- def get_endpoint (path : str , api_version : str = 'latest' , host : str = 'https://console.cloudendure.com' ) -> str :
135+ def get_endpoint (
136+ path : str ,
137+ api_version : str = "latest" ,
138+ host : str = "https://console.cloudendure.com" ,
139+ ) -> str :
119140 """Build the endpoint path.
120141
121142 Returns:
122143 str: The CloudEndure API endpoint to be used.
123144
124145 """
125- return f' { host } /api/{ api_version } /{ path } '
146+ return f" { host } /api/{ api_version } /{ path } "
126147
127- def api_call (self , path : str , method : str = ' get' , data = None ) -> Response :
148+ def api_call (self , path : str , method : str = " get" , data = None ) -> Response :
128149 """Handle CloudEndure API calls based on the defined parameters.
129150
130151 Args:
@@ -144,11 +165,13 @@ def api_call(self, path: str, method: str = 'get', data=None) -> Response:
144165 data = {}
145166
146167 if method not in METHOD_TYPES :
147- print (' Please specify a valid method type! Must be one of: ' , METHOD_TYPES )
168+ print (" Please specify a valid method type! Must be one of: " , METHOD_TYPES )
148169 return Response ()
149170
150- if method not in ['get' , 'delete' ] and data is None :
151- print ('Paramater mismatch! If calling anything other than get or delete provide data!' )
171+ if method not in ["get" , "delete" ] and data is None :
172+ print (
173+ "Paramater mismatch! If calling anything other than get or delete provide data!"
174+ )
152175 return Response ()
153176
154177 # Attempt to call the CloudEndure API.
@@ -157,44 +180,48 @@ def api_call(self, path: str, method: str = 'get', data=None) -> Response:
157180 _path = self .get_endpoint (path )
158181 return ce_call (_path , data = data )
159182 except Exception as e :
160- print (f' Exception encountered in CloudEndure API call: ({ e } )' )
183+ print (f" Exception encountered in CloudEndure API call: ({ e } )" )
161184 return Response ()
162185
163186 def check_creds (self , login = True ):
164187 threshold = datetime .datetime .utcnow () - AUTH_TTL
165188
166- if threshold < self .config .active_config .get (' last_updated' , 0 ):
189+ if threshold < self .config .active_config .get (" last_updated" , 0 ):
167190 if login :
168191 is_valid : bool = self .login ()
169192 if is_valid :
170- return {' status' : ' updated' }
171- return {' status' : ' expired' }
172- return {' status' : ' valid' }
193+ return {" status" : " updated" }
194+ return {" status" : " expired" }
195+ return {" status" : " valid" }
173196
174- def post_endpoint (self , path = '' ):
175- response : requests .Response = self .session .post (f' { self .api_endpoint } /{ path } ' )
197+ def post_endpoint (self , path = "" ):
198+ response : requests .Response = self .session .post (f" { self .api_endpoint } /{ path } " )
176199 return response
177200
178- def get_projects (self , current_project = '' ):
201+ def get_projects (self , current_project = "" ):
179202 """Get the CloudEndure projects associated with the authenticated account."""
180203 self .login ()
181- response : requests .Response = self .session .get (f' { self .api_endpoint } /projects' )
204+ response : requests .Response = self .session .get (f" { self .api_endpoint } /projects" )
182205 data : Dict [str , Any ] = response .json ()
183206 status_code : int = response .status_code
184207
185- if status_code not in [200 , ]:
208+ if status_code not in [200 ]:
186209 raise CloudEndureException ()
187- projects : List [Any ] = data [' items' ]
210+ projects : List [Any ] = data [" items" ]
188211 self .projects : List [Any ] = projects
189212
190213 if current_project :
191- return list (filter (lambda project : project ['name' ] == current_project , projects ))
214+ return list (
215+ filter (lambda project : project ["name" ] == current_project , projects )
216+ )
192217
193218 return projects
194219
195220 @classmethod
196221 def docs (self ):
197222 """Open the CloudEndure API documentation page."""
198- docs_url : str = os .environ .get ('CLOUDENDURE_API_DOCS' , 'https://console.cloudendure.com/api_doc/apis.html' )
223+ docs_url : str = os .environ .get (
224+ "CLOUDENDURE_API_DOCS" , "https://console.cloudendure.com/api_doc/apis.html"
225+ )
199226 open_new_tab (docs_url )
200227 return docs_url
0 commit comments