def post(self, request: Request) -> JsonResponse: try: token = verify_jwt_token(request.META['HTTP_AUTHORIZATION']) if (token == 0): self.logger.error("Error in Upload File Import API token: ") return JsonResponse( create_failure(400, 'Invalid token', 'Fail')) except Exception as e: self.logger.error("Error in Authentication." + str(e)) return JsonResponse( create_failure_modified(500, 'Authentication Error', 'Failed', '', 'failed')) try: self.uniqueID = request.data['uniqueID'] except Exception as e: self.logger.error("Please provide uniqueid " + str(e)) return JsonResponse( create_failure_modified(500, 'Please provide uniqueid', 'Failed', '', 'failed')) try: self.fileName = request.data['fileName'] except Exception as e: self.logger.error("Error in FileName " + str(e)) return JsonResponse( create_failure_modified(500, 'Error in FileName ', 'Failed', '', 'failed')) try: if (not request.data['file']): return JsonResponse( create_failure_modified(500, 'Failed to Upload File', 'Failed', '', 'failed')) elif (len(self.uniqueID.strip()) == 0): return JsonResponse( create_failure_modified(500, 'Failed to Upload File', 'Failed', '', 'failed')) else: if (self.save_file(request) != True): return JsonResponse( create_failure_modified(500, 'File is Corrupted', 'Failed', '', 'failed')) if (self.fileName.split('.')[-1] == "csv"): response = self.read_csv_file(request) elif (self.fileName.split('.')[-1] == 'xlsx'): response = self.read_excel_file(request) else: JsonResponse( create_failure_modified( 500, 'Invalid file type , Please upload Excel or CSV file', 'Failed', '', 'failed')) except Exception as e: self.logger.error("Error in API" + str(e)) return JsonResponse( create_failure_modified(500, 'API Fail due to Exception', 'Failed', '', 'failed')) return JsonResponse(response)
def post(self, request: Request) -> JsonResponse: try: token = verify_jwt_token(request.META['HTTP_AUTHORIZATION']) if token == 0: self.logger.error("Error in Delete API token: ") return JsonResponse( create_failure(400, 'Invalid token', 'Failed')) except Exception as e: self.logger.error("Error in Authentication Delete API." + str(e)) return JsonResponse( create_failure(500, 'Authentication Error', 'Failed')) try: response = self.main_function(request) return JsonResponse(response) except Exception as e: self.logger.error("Error in Delete API " + str(e)) return JsonResponse( create_failure(500, 'API Fail due to Exception', 'Failed'))
def post(self, request:Request) -> JsonResponse: try: userid = verify_jwt_token(request.META['HTTP_AUTHORIZATION']) if userid == 0: self.logger.error("Error in View Results API token: ") return JsonResponse(create_failure(400, 'Invalid token', 'Fail')) except Exception as e: self.logger.error("Error in View Results API: "+str(e)) return JsonResponse(create_failure(400, 'Please provide valid token', 'Fail')) try: session_id = request.data['SessionID'] except Exception as e: self.logger.error("invalid SessionID"+str(e)) return JsonResponse(create_failure(400, 'invalid SessionID', 'Fail')) try: resultset = [] testdetails = Sessiontestmapping.objects.filter(userid=userid, sessionid=session_id).values_list('ruledetailsid', 'todolistid','ruleid','createddate') if testdetails.exists(): for mappingitems in testdetails: resultdict = {} try: ruledetails = dashboardModels.Ruledetails.objects.filter(ruledetailsid=mappingitems[0]).values_list('shortdescription') for ruledetailsitem in ruledetails: resultdict['ShortDescription'] = ruledetailsitem[0] rulemaster = dashboardModels.Rulemaster.objects.filter(rulemasterid=mappingitems[2]).values_list('testno', 'testname') resultdict['TestNo'] = rulemaster[0][0] resultdict['TestName'] = rulemaster[0][1] todoliststatus = Todolist.objects.filter(id=mappingitems[1]).values_list('status') resultdict['Status'] = todoliststatus[0][0] resultdict['CreatedDate'] = mappingitems[3] resultdict['RuleId'] = mappingitems[2] resultset.append(resultdict) except Exception as e: self.logger.error("Occured error while fetching list of Results: "+str(e)) return JsonResponse(create_failure(400, 'Invalid SessionID', 'Fail')) else: return JsonResponse(create_failure(500, 'No Records Found', 'Fail')) except Exception as e: self.logger.error("Occured error while fetching list of Results: "+str(e)) return JsonResponse(create_failure(400, 'Bad Request', 'Fail')) return JsonResponse(create_success('success', resultset))
def post(self,request : Request) -> JsonResponse: try: token = verify_jwt_token(request.META['HTTP_AUTHORIZATION']) if token == 0: self.logger.error("Error in Download API token: ") return JsonResponse(create_failure(400, 'Invalid token', 'Failed')) except Exception as e: self.logger.error("Error in Download API."+str(e)) return JsonResponse(create_failure(500, 'Authentication Error', 'Failed')) try: toDoListID = request.data['toDoListID'] zipFilePath = self.config['ENV_VARIABLE']['file_path_zip'] downloadFilePath = self.config['ENV_VARIABLE']['file_path_download'] if not os.path.exists(zipFilePath): os.makedirs(zipFilePath) try: settingsObject = Settings.objects.all() settingsData = settingsSerializer(settingsObject, many=True) if(settingsData.data): try: appUrl = settingsData.data[0]['appurl'] self.zipCount = settingsData.data[0]['layercount'] except Exception as e: self.logger.error("Failed to convert files into zip "+str(e)) return JsonResponse(create_failure(500, 'Failed to convert files into zip - Error in Settings Table', 'Failed')) else: self.logger.error("Failed to convert files into zip - Error in Settings Table "+str(e)) return JsonResponse(create_failure(500, 'Failed to convert files into zip - Error in Settings Table', 'Failed')) except Exception as e: self.logger.error("Failed to convert files into zip "+str(e)) return JsonResponse(create_failure(500, 'Failed to convert files into zip - Error in Settings Table', 'Failed')) urlList = [] filePathList = [] for toDoID in toDoListID: try: toDoListObject = Todolist.objects.filter(id=toDoID) todoListData = todolistSerializer(toDoListObject, many=True) if(todoListData.data): try: fileName = todoListData.data[0]['outputfilename'] fileList = fileName.split(',') for files in fileList: urlJson = dict() url = appUrl + self.config['ENV_VARIABLE']['download_files'] + toDoID + '/' + files urlJson['ID'] = toDoID urlJson['DownloadUrl'] = url urlJson['Zip'] = False urlList.append(urlJson) filePath = toDoID + '/' + files filePathList.append(filePath) except Exception as e: self.logger.error("Failed to Fetch Output file name - Error in Todolist Table "+str(e)) return JsonResponse(create_failure(500, 'Failed to Fetch Output file name - Error in Todolist Table ', 'Failed')) except Exception as e: self.logger.error("Failed to Fetch Output file name - Error in Todolist Table "+str(e)) return JsonResponse(create_failure(500, 'Failed to Fetch Output file name - Error in Todolist Table ', 'Failed')) if(len(filePathList) >= self.zipCount): compression = zipfile.ZIP_DEFLATED now = datetime.datetime.now() timeStamp = datetime.datetime.timestamp(now) zipfileName = zipFilePath + str(timeStamp) + ".zip" zipFiles = zipfile.ZipFile(zipfileName, mode="w") for files in filePathList: try: fileName = files.split("/")[-1] filesVar = downloadFilePath + files zipFiles.write(filesVar, fileName, compress_type=compression) except Exception as e: self.logger.error("Failed to convert files into zip"+str(e)) return JsonResponse(create_failure(500, 'Failed to convert files into zip', 'Failed')) zipFiles.close() zipUrl = appUrl + self.config['ENV_VARIABLE']['zip_files'] + str(timeStamp) + '.zip' for i in range(len(urlList)): urlList[i]['DownloadUrl'] = zipUrl urlList[i]['Zip'] = True output = {'DownloadURL' : urlList} except Exception as e: self.logger.error("Failed to convert files into zip "+str(e)) return JsonResponse(create_failure(500, 'Failed to convert files into zip', 'Failed')) return JsonResponse(create_success('URL Generated Successfully',output ))
def post(self, request): try: token = verify_jwt_token(request.META['HTTP_AUTHORIZATION']) if token == 0: self.logger.error("Error in Upload File Import API token: ") return JsonResponse( create_failure(400, 'Invalid token', 'Fail')) except Exception as e: self.logger.error("Error in Fetching Data." + str(e)) return JsonResponse( create_failure_modified(500, 'Data Request Error', 'Failed', '', 'failed')) try: toDoID = request.data['toDoID'] try: toDoCount = Todolist.objects.filter(id=toDoID).count() if (toDoCount == 0): return JsonResponse( create_failure_modified(500, 'No Entry in DB', 'Failed', '', 'failed')) else: toDo = Todolist.objects.get(id=toDoID) toDoVal = list(Todolist.objects.filter(id=toDoID).values()) if (toDo.status == 'Pending'): trigger_event(toDoID) if (data['status'] == 'success'): res = self.response_filter(data['data'][0]) data['data'][0] = res return JsonResponse( create_success(data['message'], data['data'])) else: res = self.response_filter(data['data'][0]) data['data'][0] = res return JsonResponse( create_failure_modified( 500, data['message'], 'Fail', data['data'])) elif (toDo.status == 'Failed'): toDoVal[0] = self.response_filter(toDoVal[0]) return JsonResponse( create_failure_modified(500, 'fetched failed status', 'Fail', toDoVal)) else: toDoVal[0] = self.response_filter(toDoVal[0]) return JsonResponse( create_success('fetched success status', toDoVal)) if (data['status'] == 'success'): res = self.response_filter(data['data'][0]) data['data'][0] = res return JsonResponse( create_success_modified(data['message'], data['data'])) else: res = self.response_filter(data['data'][0]) data['data'][0] = res return JsonResponse( create_failure_modified(500, data['message'], 'Fail', data['data'])) except Exception as e: self.logger.error("Bad Request." + str(e)) return JsonResponse( create_failure_modified(500, 'Bad Request', 'Fail')) except Exception as e: self.logger.error("Value Missing." + str(e)) return JsonResponse( create_failure_modified(500, 'Value Missing', 'Fail'))
def post(self, request: Request) -> JsonResponse: try: userid = verify_jwt_token(request.META['HTTP_AUTHORIZATION']) if userid == 0: self.logger.error("Error in changePassword API token: ") return JsonResponse( create_failure(400, 'invalid Token', 'Fail')) except Exception as e: self.logger.error("Error in changePassword API: " + str(e)) return JsonResponse( create_failure(400, 'Please provide valid Token', 'Fail')) try: email = request.data['email'] if not email: self.logger.error("invalid email") return JsonResponse( create_failure(400, 'provide valid email', 'Fail')) except Exception as e: self.logger.error("invalid email" + str(e)) return JsonResponse(create_failure(400, 'provide email', 'Fail')) try: oldPassword = request.data['old_password'] if not oldPassword: self.logger.error("invalid password") return JsonResponse( create_failure(400, 'provide valid old password', 'Fail')) userInfo = Userlogindetails.objects.get(emailaddress=email) self.logger.info(userInfo.password) if userInfo.password != (oldPassword): self.logger.error("invalid password") return JsonResponse( create_failure(400, 'invalid old password', 'Fail')) except Exception as e: self.logger.error("invalid password." + str(e)) return JsonResponse( create_failure(400, 'provide valid old password', 'Fail')) try: newPassword = request.data['new_password'] if not newPassword: self.logger.error("invalid new password") return JsonResponse( create_failure(400, 'provide valid new password', 'Fail')) except Exception as e: self.logger.error("invalid new password" + str(e)) return JsonResponse( create_failure(400, 'provide valid new password', 'Fail')) try: if newPassword == oldPassword: self.logger.error( "old password and new password should not be same") return JsonResponse( create_failure( 400, 'old password and new password should not be same', 'Fail')) except Exception as e: self.logger.error( "old password and new password should not be same" + str(e)) return JsonResponse( create_failure( 400, 'old password and new password should not be same', 'Fail')) try: currentTime = timezone.now() UserlogindetailsUpdate = Userlogindetails.objects.filter( emailaddress=email).update(password=newPassword, modifieddate=currentTime) if UserlogindetailsUpdate == 0: return JsonResponse( create_failure(204, 'Failed to update password', 'Fail')) except Exception as e: self.logger.error("invalid email" + str(e)) return JsonResponse( create_failure(500, 'Failed to update password', 'Fail')) return JsonResponse( create_success("Password Updated Successfully!", []))
def post(self, request: Request) -> JsonResponse: try: userid = verify_jwt_token(request.META['HTTP_AUTHORIZATION']) if userid == 0: self.logger.error("Error in Publish Message API token: ") return JsonResponse( create_failure(400, 'Invalid token', 'Fail')) except Exception as e: self.logger.error("Error in Publish Message API: " + str(e)) return JsonResponse( create_failure(400, 'Please provide valid token', 'Fail')) try: #for send email! sendMailFlag = False attachFilepath = [] # To insert record into ToDoList table for requestDataVar in request.data: try: statusInsert = self.insert_todo_list(requestDataVar) # for Run-Test API if (self.eventType == 'TestExec'): try: # TODO: implement messageQueue and scheduler payload = { "RuleID": requestDataVar['RuleID'], "SessionID": requestDataVar['SessionID'], "ToDoListID": requestDataVar['ID'], "UserID": userid } runTest = run_test_api() responseRuntest = runTest.run_test_function( payload) if responseRuntest['statusCode'] == 200: self.update_todo_list(request, "Success") else: self.update_todo_list( request, responseRuntest['replyCode'], responseRuntest['message']) except Exception as e: self.logger.error( "Error in run test execution API: " + str(e)) self.update_todo_list(request, "Failed", str(e)) # For Upload file functionality elif (self.eventType == 'Import'): try: dbVar = FetchDatabaseName() dbName = dbVar.fetch(self.sessionId) if (len(dbName) != 0): try: if (self.fileType == 'CSV'): payload = { "FileType": self.fileType, "ClientID": self.clientId, "FilePath": self.filePath, "SheetName": self.sheetName, "Overwrite_merge": self.overWriteMerge, "DatabaseName": dbName, "TableName": self.tableName, "textqualifier": self.textQualifier, "rowdelimeter": self.rowDelimeter, "columndelimeter": self.columnDelimeter, "numberRowToSkip": self.numberRowToSkip, "iscolumnnameinfirstrow": self.isColumnNameInFirstRow } else: payload = { "FileType": self.fileType, "ClientID": self.clientId, "FilePath": self.filePath, "SheetName": self.sheetName, "Overwrite_merge": self.overWriteMerge, "DatabaseName": dbName, "TableName": self.tableName } resUpload = dump_file(payload) if (resUpload['statusCode'] == 200): self.update_todo_list( request, "Success") else: self.logger.info( "Response DumpFile- {}".format( resUpload)) self.update_todo_list( request, "Failed", resUpload['message']) except Exception as e: self.logger.error("Error in DumpFile: " + str(e)) self.update_todo_list( request, "Failed", str(e)) else: self.logger.info( "Response FetchDB- {}".format(dbName)) self.update_todo_list(request, "Failed", dbName['message']) except Exception as e: self.logger.error("Error in FetchDB: " + str(e)) self.update_todo_list(request, "Failed", str(e)) # For Export test output file elif (self.eventType == 'Output'): try: classVar = export_test() resExport = classVar.export_class(requestDataVar) if (resExport['statusCode'] == 200): self.fileName = resExport['data']['fileName'] self.appUrl = resExport['data']['appUrl'] self.update_todo_list(request, "Success", 'Output') else: self.logger.error( "Response Export- {}".format(resExport)) self.update_todo_list(request, "Failed", resExport['message']) except Exception as e: self.logger.error("Error in Export Test: " + str(e)) self.update_todo_list(request, "Failed", str(e)) # for sending Email elif (self.eventType == 'Email'): try: classVar = export_test( ) #using export function to attaching files in Email resExport = classVar.export_class(requestDataVar) if (resExport['statusCode'] == 200): self.fileName = resExport['data']['fileName'] self.outputPublishFolderPath = self.config[ 'ENV_VARIABLE'][ 'file_path_download'] + requestDataVar[ 'ID'] self.appUrl = resExport['data']['appUrl'] self.update_todo_list(request, "Success", 'Output') attachFilepath.append( str(self.outputPublishFolderPath) + "/" + str(self.fileName)) print(attachFilepath) try: emailIds = requestDataVar[ 'To'] # stroing email from request pyaload emailIds = emailIds.split( ';' ) # spliting emails from string to List emailIds = [ x.strip(' ') for x in emailIds ] # storing email ids without white spaces sendMailFlag = True # to confirm for sending email except Exception as e: self.logger.error( "Error In Fething Emails", str(e)) else: self.logger.error( "Response Export- {}".format(resExport)) self.update_todo_list(request, "Failed", resExport['message']) except Exception as e: self.logger.error( "Error in Export Test for sending email: " + str(e)) self.update_todo_list(request, "Failed", str(e)) # For creating New Session elif (self.eventType == 'NewSession'): try: #TODO: Implement scheduler and messageQueue payload = { "ClientID": requestDataVar['ClientID'], "SessionID": requestDataVar['SessionID'], "AuditFrom": requestDataVar['AuditFrom'], "AuditTo": requestDataVar['AuditTo'], "ProjectName": requestDataVar['ProjectName'], "SerialNo": requestDataVar['SerialNo'], "userid": userid } newSess = new_session() responseNewSess = newSess.post(payload) if responseNewSess['statusCode'] == 200: self.update_todo_list(request, "Success") else: self.update_todo_list( request, responseNewSess['replyCode'], responseNewSess['message']) except Exception as e: self.logger.error("Error in new session API: " + str(e)) self.update_todo_list(request, "Failed", str(e)) # For Power BI URL Validity elif (self.eventType == 'ViewInPowerBI'): try: payload = {"ruleid": requestDataVar['RuleID']} powerbi_func = powerbi_url() response_powerbi = powerbi_func.powerbi(payload) if response_powerbi['statusCode'] == 200: self.update_todo_list(request, "Success") else: self.update_todo_list( request, response_powerbi['replyCode'], response_powerbi['message']) except Exception as e: self.logger.error("Error in powerbi url API: " + str(e)) self.update_todo_list(request, "Failed", str(e)) except Exception as e: self.logger.error("Error in Publish Message API: " + str(e)) return JsonResponse( create_failure(400, 'Error in Publish Message API', 'Fail')) if sendMailFlag: #if true mail will be send self.send_email(attachFilepath, emailIds) #calling send_email Function except Exception as e: self.logger.error("Error in publish_message API: " + str(e)) return JsonResponse( create_failure(500, 'Error in publish_message API', 'Fail')) return JsonResponse(create_success('Success', ''))