fromeptr2importEPTR2# Using .env file for credentialseptr=EPTR2(use_dotenv=True,recycle_tgt=True)# Direct credentialseptr=EPTR2(username="email@example.com",password="password")# Make API callsdf=eptr.call("mcp",start_date="2024-07-29",end_date="2024-07-29")
def__init__(self,username:str=None,password:str=None,recycle_tgt:bool=True,use_dotenv:bool=True,dotenv_path:str=".env",**kwargs,)->None:## kwargs are### map_param_labels: bool### secure: bool### query_parameters: dict### just_call_phrase: bool### root_phrase: strself.ssl_verify=kwargs.get("ssl_verify",True)self.check_postprocess(postprocess=kwargs.get("postprocess",True))self.get_raw_response=kwargs.get("get_raw_response",False)### Credentials and Loginself.username=usernameself.password=passwordself.is_test=kwargs.get("is_test",False)## Currently not being usedself.temp_new_login_method=kwargs.get("new_login_method",False)### Credentials file path is being deprecated in favor of dotenv usageself.credentials_file_path=kwargs.get("credentials_file_path",None)### Dotenv usage. Get EPTR_USERNAME and EPTR_PASSWORD from .env file if use_dotenv is True and environment file exists and credentials are recorded there.self.use_dotenv=use_dotenvifself.use_dotenv:env_check_d=self.check_dotenv(dotenv_path=dotenv_path)else:env_check_d=Noneself.upass_check(env_check_d=env_check_d,custom_root_phrase=kwargs.get("root_phrase",None))### Options to recycle tgtself.recycle_tgt=recycle_tgtself.tgt_dir_path=kwargs.get("tgt_path",".")input_tgt_d=kwargs.get("tgt_d",None)self.import_tgt_info(input_tgt_d)self.check_renew_tgt(**kwargs)## Path map keys and custom aliasesself.path_map_keys=get_path_map(just_call_keys=True)self.custom_aliases=kwargs.get("custom_aliases",{})
defcall(self,key:str,**kwargs):""" Main call function for the API. This function is used to process parameters and make calls to EPIAS Transparency API. """self.check_renew_tgt(**kwargs)raw_key=keykey=alias_to_path(alias=key,custom_aliases=self.custom_aliases)ifkeynotinself.path_map_keys:ifraw_key==key:raiseException(f"This call {raw_key} is not yet defined in calls or aliases. Call 'get_available_calls' method to see the available calls.")else:raiseException(f"This alias {raw_key} forwarded to key {key} is not yet defined in calls. Call 'get_available_calls' method to see the available calls.")call_path=get_total_path(key)call_method=get_call_method(key)required_body_params=get_required_parameters(key)call_body_raw=kwargs.pop("call_body",kwargs)### There are some calls requiring special handling, they have a special function to process themcall_body_raw=process_special_calls(key,call_body_raw)optional_body_params=get_optional_parameters(key)all_params=required_body_params+optional_body_paramscall_body={k:preprocess_parameter(k,v)fork,vincall_body_raw.items()## If there is a call_body parameter in kwargsi, use it, else use kwargsifkinall_params}forbody_keyinrequired_body_params:ifbody_keynotincall_body.keys():call_body[body_key]=preprocess_parameter(body_key,None)kwargs.pop(body_key,None)ifcall_bodyisnotNone:ifnotall([xincall_body.keys()forxinrequired_body_params]):raiseException("Some required parameters are missing in call body.")ifkwargs.get("map_param_labels",True):cb2={}fork,vincall_body.items():## Updated this part to handle multiple labels originating from a single labellabel=get_param_label(k)["label"]value=vifisinstance(label,list):forlinlabel:# noqa: E741cb2[l]=valueelse:cb2[label]=valuecall_body=copy.deepcopy(cb2)eliflen(required_body_params)>0:raiseException("Required parameters are missing in call body.")## If the call is uevm, change powerPlantId to powerplantId due to only non-standard naming in powerPlantIdifkey=="uevm"and"powerPlantId"incall_body.keys():call_body["powerplantId"]=call_body.pop("powerPlantId")res=transparency_call(call_path=call_path,call_method=call_method,call_body=call_body,root_phrase=self.root_phrase,ssl_verify=self.ssl_verify,is_test=self.is_test,tgt=self.tgt,**kwargs,)## Set soft timeout for tgt renewalself.tgt_exp_0=min(self.tgt_exp,datetime.now().timestamp()+60*90,)ifself.recycle_tgt:self.export_tgt_info()ifkwargs.get("get_raw_response",self.get_raw_response):returnresres=json.loads(res.data.decode("utf-8"))ifkwargs.get("postprocess",self.postprocess):fromeptr2.mapping.processingimportget_postprocess_functiondf=get_postprocess_function(key)(res,key=key)returndfreturnres
Gets all the available calls of eptr2 package. As a reminder, number of calls at eptr2 package might be lower than the actual calls. If include_aliases is set to True, it also includes the aliases.
defget_available_calls(self,include_aliases:bool=False):""" Gets all the available calls of eptr2 package. As a reminder, number of calls at eptr2 package might be lower than the actual calls. If include_aliases is set to True, it also includes the aliases. """ifinclude_aliases:return{"keys":self.path_map_keys,"default_aliases":get_alias_map(),"custom_aliases":self.custom_aliases,}returnself.path_map_keys
defget_number_of_calls(self):""" List the number of calls in the package. It also lists the number of derived calls and API calls (excluding derived calls). """d={"all_calls":self.path_map_keys,"derived_calls":get_derived_calls(),}d["n_total_calls"]=len(d["all_calls"])d["n_derived_calls"]=len(d["derived_calls"])d["n_api_calls"]=len(d["all_calls"])-len(d["derived_calls"])returnd
defget_aliases(self,include_custom_aliases:bool=False):""" Gets only the aliases. If include_custom_aliases is set to True, it also includes the user defined aliases (custom_aliases). """alias_d=get_alias_map()ifinclude_custom_aliases:alias_d.update(self.custom_aliases)returnalias_d
defget_tgt(self,**kwargs):ifself.usernameisNoneorself.passwordisNone:raiseException("Username and password must be provided for tgt renewal.")test_suffix="-prp"ifself.is_testelse""login_url=f"""https://giris{test_suffix}.epias.com.tr/cas/v1/tickets"""body_str=f"username={quote(self.username)}&password={quote(self.password)}"http=urllib3.PoolManager(cert_reqs="CERT_REQUIRED"ifself.ssl_verifyelse"CERT_NONE")res=http.request(method="POST",url=login_url,headers={"Content-Type":"application/x-www-form-urlencoded","Accept":"text/plain",},body=body_str,**kwargs.get("request_kwargs",{"timeout":10}),)ifres.statusnotin[200,201]:raiseException("Request failed with status code: "+str(res.status)+": "+res.data.decode("utf-8"))ifisinstance(res.data,bytes):res_data=res.data.decode("utf-8")else:res_data=res.dataifres_data.startswith("TGT-"):tgt=res_dataelse:raiseException("Login failed. TGT not found in response: "+res_data)self.tgt=tgttgt_start_time=datetime.now()## Hard timeoutself.tgt_exp=(tgt_start_time+timedelta(hours=1,minutes=45)).timestamp()## Soft timeoutself.tgt_exp_0=min(self.tgt_exp,(tgt_start_time+timedelta(hours=1,minutes=45)).timestamp(),)ifself.recycle_tgt:self.export_tgt_info()
result=eptr.call(key="mcp",# API endpoint keystart_date="2024-07-29",# Start date (YYYY-MM-DD)end_date="2024-07-29",# End date (YYYY-MM-DD)postprocess=True,# Return DataFramerequest_kwargs={"timeout":10}# urllib3 request options)