From 97a4c471df2bb58db9712b77c0cacdc7009438f3 Mon Sep 17 00:00:00 2001 From: Chris Burr Date: Tue, 14 Feb 2023 10:04:28 +0100 Subject: [PATCH] refactor: Run pre-commit autoupdate and add pyupgrade+flynt --- .pre-commit-config.yaml | 19 +++++++++++++---- .prettierrc | 3 ++- src/WebAppDIRAC/Core/App.py | 10 ++++----- src/WebAppDIRAC/Core/CoreHandler.py | 2 +- src/WebAppDIRAC/Core/HandlerMgr.py | 4 ++-- src/WebAppDIRAC/Core/TemplateLoader.py | 2 +- src/WebAppDIRAC/Lib/SessionData.py | 7 +++---- src/WebAppDIRAC/Lib/WebHandler.py | 6 ++---- .../WebApp/handler/AccountingHandler.py | 11 +++++----- .../handler/ApplicationWizardHandler.py | 1 - .../WebApp/handler/ComponentHistoryHandler.py | 5 ++--- .../handler/ConfigurationManagerHandler.py | 20 +++++++----------- .../WebApp/handler/DowntimesHandler.py | 1 - .../WebApp/handler/ExampleAppHandler.py | 1 - .../WebApp/handler/FileCatalogHandler.py | 13 ++++++------ .../WebApp/handler/JobLaunchpadHandler.py | 10 ++++----- .../WebApp/handler/JobMonitorHandler.py | 21 +++++++++---------- .../WebApp/handler/JobSummaryHandler.py | 5 ++--- .../WebApp/handler/MonitoringHandler.py | 7 +++---- .../WebApp/handler/NotepadHandler.py | 1 - .../WebApp/handler/PilotMonitorHandler.py | 1 - .../WebApp/handler/PilotSummaryHandler.py | 3 +-- .../WebApp/handler/ProxyManagerHandler.py | 1 - .../WebApp/handler/ProxyUploadHandler.py | 7 +++---- .../handler/PublicStateManagerHandler.py | 1 - .../WebApp/handler/RegistryManagerHandler.py | 13 ------------ .../WebApp/handler/RequestMonitorHandler.py | 1 - .../WebApp/handler/ResourceSummaryHandler.py | 11 ++-------- src/WebAppDIRAC/WebApp/handler/RootHandler.py | 3 +-- .../WebApp/handler/SiteSummaryHandler.py | 7 +++---- .../WebApp/handler/SpaceOccupancyHandler.py | 9 ++++---- .../handler/SystemAdministrationHandler.py | 5 +---- .../WebApp/handler/TokenManagerHandler.py | 3 +-- .../handler/TransformationMonitorHandler.py | 7 +++---- src/WebAppDIRAC/scripts/dirac_webapp_run.py | 4 ++-- src/WebAppDIRAC/scripts/tornado-start-web.py | 2 +- 36 files changed, 93 insertions(+), 134 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 264fb09f9..c5678b497 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,7 +11,7 @@ exclude: | repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.1.0 + rev: v4.4.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer @@ -19,12 +19,12 @@ repos: - id: check-added-large-files - repo: https://github.com/psf/black - rev: 22.3.0 + rev: 23.1.0 hooks: - id: black - repo: https://github.com/pre-commit/mirrors-prettier - rev: v2.4.1 + rev: v3.0.0-alpha.4 hooks: - id: prettier exclude: | @@ -33,9 +33,20 @@ repos: )$ - repo: https://github.com/pre-commit/mirrors-eslint - rev: v8.0.1 + rev: v8.34.0 hooks: - id: eslint additional_dependencies: - eslint@8.0.1 - http://diracproject.web.cern.ch/diracproject/externalLibraries/@sencha_eslint-plugin-extjs.7.0.0.tgz + + - repo: https://github.com/ikamensh/flynt/ + rev: "0.77" + hooks: + - id: flynt + + - repo: https://github.com/asottile/pyupgrade + rev: v3.3.1 + hooks: + - id: pyupgrade + args: ["--py39-plus"] diff --git a/.prettierrc b/.prettierrc index 50ffd400a..fccaa4f24 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,5 +1,6 @@ { "useTabs": false, "printWidth": 150, - "singleQuote": false + "singleQuote": false, + "trailingComma": "es5" } diff --git a/src/WebAppDIRAC/Core/App.py b/src/WebAppDIRAC/Core/App.py index 28fd41250..cce986444 100644 --- a/src/WebAppDIRAC/Core/App.py +++ b/src/WebAppDIRAC/Core/App.py @@ -118,7 +118,7 @@ def bootstrap(self): # Configure tornado app self.__app = tornado.web.Application(routes, **kw) port = Conf.HTTPPort() - self.log.notice("Configuring HTTP on port %s" % port) + self.log.notice(f"Configuring HTTP on port {port}") # Create the web servers srv = tornado.httpserver.HTTPServer(self.__app, xheaders=True) srv.listen(port) @@ -127,7 +127,7 @@ def bootstrap(self): Conf.generateRevokedCertsFile() # it is used by nginx.... if Conf.HTTPS(): - self.log.notice("Configuring HTTPS on port %s" % Conf.HTTPSPort()) + self.log.notice(f"Configuring HTTPS on port {Conf.HTTPSPort()}") sslops = dict( certfile=Conf.HTTPSCert(), keyfile=Conf.HTTPSKey(), @@ -142,8 +142,8 @@ def bootstrap(self): if sslprotocol in aviableProtocols: sslops["ssl_version"] = getattr(ssl, sslprotocol) else: - message = "%s protocol is not provided." % sslprotocol - message += "The following protocols are provided: %s" % str(aviableProtocols) + message = f"{sslprotocol} protocol is not provided." + message += f"The following protocols are provided: {str(aviableProtocols)}" gLogger.warn(message) self.log.debug(" - %s" % "\n - ".join([f"{k} = {sslops[k]}" for k in sslops])) @@ -165,6 +165,6 @@ def run(self): urls = [] for proto, port in self.__servers: urls.append(f"{proto}://0.0.0.0:{port}/{bu}/") - self.log.always("Listening on %s" % " and ".join(urls)) + self.log.always(f"Listening on {' and '.join(urls)}") tornado.autoreload.add_reload_hook(self.__reloadAppCB) tornado.ioloop.IOLoop.instance().start() diff --git a/src/WebAppDIRAC/Core/CoreHandler.py b/src/WebAppDIRAC/Core/CoreHandler.py index b7f362145..b8af58da5 100644 --- a/src/WebAppDIRAC/Core/CoreHandler.py +++ b/src/WebAppDIRAC/Core/CoreHandler.py @@ -22,7 +22,7 @@ def get(self, setup, group, route): dest = "/" rootURL = Conf.rootURL() if rootURL: - dest += "%s/" % rootURL.strip("/") + dest += f"{rootURL.strip('/')}/" if setup and group: dest += f"s:{setup}/g:{group}/" self.redirect(dest) diff --git a/src/WebAppDIRAC/Core/HandlerMgr.py b/src/WebAppDIRAC/Core/HandlerMgr.py index 8b322f1a7..1e512ab42 100644 --- a/src/WebAppDIRAC/Core/HandlerMgr.py +++ b/src/WebAppDIRAC/Core/HandlerMgr.py @@ -72,7 +72,7 @@ def __calculateRoutes(self): # Add some standard paths for static files statDirectories = Conf.getStaticDirs() - self.log.info("The following static directories are used: %s" % str(statDirectories)) + self.log.info(f"The following static directories are used: {str(statDirectories)}") for staticDirectory in statDirectories: # Get real static files directory realStaticDirectory = f"{rootPath}/webRoot/www/{staticDirectory}" @@ -95,7 +95,7 @@ def __calculateRoutes(self): handler_base_url = self.__baseURL + self.__setupGroupRE for hn in self.__handlers: - self.log.info("Found handler %s" % hn) + self.log.info(f"Found handler {hn}") handler = self.__handlers[hn] # Set the base URL of the request diff --git a/src/WebAppDIRAC/Core/TemplateLoader.py b/src/WebAppDIRAC/Core/TemplateLoader.py index 58e8d44d0..6f40092ec 100644 --- a/src/WebAppDIRAC/Core/TemplateLoader.py +++ b/src/WebAppDIRAC/Core/TemplateLoader.py @@ -22,4 +22,4 @@ def _create_template(self, name): template = Template(f.read(), name=name, loader=self) f.close() return template - raise RuntimeError("Can't find template %s" % name) + raise RuntimeError(f"Can't find template {name}") diff --git a/src/WebAppDIRAC/Lib/SessionData.py b/src/WebAppDIRAC/Lib/SessionData.py index 892cbf6f5..beacc68a7 100644 --- a/src/WebAppDIRAC/Lib/SessionData.py +++ b/src/WebAppDIRAC/Lib/SessionData.py @@ -47,7 +47,6 @@ class SessionData: - __handlers = {} __groupMenu = {} __extensions = [] @@ -153,7 +152,7 @@ def __getGroupMenu(self): :return: list """ - menuSection = "%s/Schema" % (Conf.BASECS) + menuSection = f"{Conf.BASECS}/Schema" # Somebody coming from HTTPS and not with a valid group group = self.__credDict.get("group", "") # Cache time! @@ -219,6 +218,6 @@ def getData(self): # if result['OK']: # data['groupsStatuses'] = result['Value'] # Calculate baseURL - baseURL = [Conf.rootURL().strip("/"), "s:%s" % data["setup"], "g:%s" % self.__credDict.get("group", "")] - data["baseURL"] = "/%s" % "/".join(baseURL) + baseURL = [Conf.rootURL().strip("/"), f"s:{data['setup']}", f"g:{self.__credDict.get('group', '')}"] + data["baseURL"] = f"/{'/'.join(baseURL)}" return data diff --git a/src/WebAppDIRAC/Lib/WebHandler.py b/src/WebAppDIRAC/Lib/WebHandler.py index fda76c256..1ea212668 100644 --- a/src/WebAppDIRAC/Lib/WebHandler.py +++ b/src/WebAppDIRAC/Lib/WebHandler.py @@ -263,7 +263,7 @@ def _authzSESSION(self): try: return self._authzJWT(token["access_token"]) except Exception as e: - sLog.debug("Cannot check access token %s, try to fetch.." % repr(e)) + sLog.debug(f"Cannot check access token {repr(e)}, try to fetch..") # Try to refresh access_token and refresh_token result = self._idps.getIdProvider("DIRACWeb") if not result["OK"]: @@ -320,9 +320,7 @@ def write_error(self, status_code, **kwargs): def finishWithImage(self, data, plotImageFile, disableCaching=False): # Set headers self.set_header("Content-Type", "image/png") - self.set_header( - "Content-Disposition", 'attachment; filename="%s.png"' % md5(plotImageFile.encode()).hexdigest() - ) + self.set_header("Content-Disposition", f'attachment; filename="{md5(plotImageFile.encode()).hexdigest()}.png"') self.set_header("Content-Length", len(data)) self.set_header("Content-Transfer-Encoding", "Binary") if disableCaching: diff --git a/src/WebAppDIRAC/WebApp/handler/AccountingHandler.py b/src/WebAppDIRAC/WebApp/handler/AccountingHandler.py index a870d3e1d..723b234b8 100644 --- a/src/WebAppDIRAC/WebApp/handler/AccountingHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/AccountingHandler.py @@ -102,13 +102,13 @@ def web_getSelectionData(self, type, **kwargs): callback["selectionValues"] = records # Cache for plotsList? - data = AccountingHandler.__keysCache.get("reportsList:%s" % typeName) + data = AccountingHandler.__keysCache.get(f"reportsList:{typeName}") if not data: retVal = self.repClient.listReports(typeName) if not retVal["OK"]: return {"success": "false", "result": "", "error": retVal["Message"]} data = retVal["Value"] - AccountingHandler.__keysCache.add("reportsList:%s" % typeName, 300, data) + AccountingHandler.__keysCache.add(f"reportsList:{typeName}", 300, data) callback["plotsList"] = data return {"success": "true", "result": callback} @@ -144,7 +144,6 @@ def __parseFormParams(self, timeSelector, typeName=None, **pD): if not pinDates: extraParams["lastSeconds"] = pD["timeSelector"] else: - end = False if "endTime" in pD: end = TimeUtilities.fromString(pD["endTime"]) @@ -295,14 +294,14 @@ def web_getCsvPlotData(self, typeName, plotName, timeSelector: int, grouping, ** data = rawData["data"] tS = int(TimeUtilities.toEpoch(start)) timeStart = tS - tS % granularity - strData = "epoch,%s\n" % ",".join(groupKeys) + strData = f"epoch,{','.join(groupKeys)}\n" for timeSlot in range(timeStart, int(TimeUtilities.toEpoch(end)), granularity): lineData = [str(timeSlot)] for key in groupKeys: lineData.append(str(data[key][timeSlot]) if timeSlot in data[key] else "") - strData += "%s\n" % ",".join(lineData) + strData += f"{','.join(lineData)}\n" else: - strData = "%s\n" % ",".join(groupKeys) + strData = f"{','.join(groupKeys)}\n" strData += ",".join([str(rawData["data"][k]) for k in groupKeys]) return FileResponse(strData, str(params), "csv", cache=False) diff --git a/src/WebAppDIRAC/WebApp/handler/ApplicationWizardHandler.py b/src/WebAppDIRAC/WebApp/handler/ApplicationWizardHandler.py index 847646167..f60a138bf 100644 --- a/src/WebAppDIRAC/WebApp/handler/ApplicationWizardHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/ApplicationWizardHandler.py @@ -2,5 +2,4 @@ class ApplicationWizardHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" diff --git a/src/WebAppDIRAC/WebApp/handler/ComponentHistoryHandler.py b/src/WebAppDIRAC/WebApp/handler/ComponentHistoryHandler.py index d0c2ec090..51b03596a 100644 --- a/src/WebAppDIRAC/WebApp/handler/ComponentHistoryHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/ComponentHistoryHandler.py @@ -6,7 +6,6 @@ class ComponentHistoryHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def web_getInstallationData(self): @@ -118,7 +117,7 @@ def __request(self): time = self.get_argument("startTime") else: time = "00:00" - date = datetime.datetime.strptime("{}-{}".format(self.get_argument("startDate"), time), "%Y-%m-%d-%H:%M") + date = datetime.datetime.strptime(f"{self.get_argument('startDate')}-{time}", "%Y-%m-%d-%H:%M") req["installation"]["InstallationTime.bigger"] = date if "endDate" in self.request.arguments and len(self.get_argument("endDate")) > 0: @@ -126,7 +125,7 @@ def __request(self): time = self.get_argument("endTime") else: time = "00:00" - date = datetime.datetime.strptime("{}-{}".format(self.get_argument("endDate"), time), "%Y-%m-%d-%H:%M") + date = datetime.datetime.strptime(f"{self.get_argument('endDate')}-{time}", "%Y-%m-%d-%H:%M") req["installation"]["UnInstallationTime.smaller"] = date return req diff --git a/src/WebAppDIRAC/WebApp/handler/ConfigurationManagerHandler.py b/src/WebAppDIRAC/WebApp/handler/ConfigurationManagerHandler.py index a0649d716..e47a144ff 100644 --- a/src/WebAppDIRAC/WebApp/handler/ConfigurationManagerHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/ConfigurationManagerHandler.py @@ -12,7 +12,6 @@ class ConfigurationManagerHandler(WebSocketHandler): - AUTH_PROPS = "authenticated" def on_open(self): @@ -91,7 +90,6 @@ def __getRemoteConfiguration(self, funcName): return {"success": 1, "op": funcName, "version": version, "name": configName} def __getSubnodes(self, parentNodeId, sectionPath): - self.log.info("Expanding section", sectionPath) retData = [] @@ -101,7 +99,6 @@ def __getSubnodes(self, parentNodeId, sectionPath): return {"success": 1, "op": "getSubnodes", "nodes": retData, "parentNodeId": parentNodeId} def __getSubnodesForPath(self, sectionPath, retData): - try: sectionCfg = self.__configData["cfgData"].getCFG() for section in [section for section in sectionPath.split("/") if not section.strip() == ""]: @@ -146,7 +143,7 @@ def __htmlComment(self, rawComment): continue commentLines.append(line) if commentLines or commiter: - return "{}{}".format("
".join(commentLines), commiter) + return f"{'
'.join(commentLines)}{commiter}" return False def __showConfigurationAsText(self): @@ -176,7 +173,7 @@ def __setOptionValue(self, params): if self.__configData["cfgData"].getValue(optionPath) == optionValue: self.log.info("Set option value", f"{optionPath} = {optionValue}") return {"success": 1, "op": "setOptionValue", "parentNodeId": params["parentNodeId"], "value": optionValue} - return {"success": 0, "op": "setOptionValue", "message": "Can't update %s" % optionPath} + return {"success": 0, "op": "setOptionValue", "message": f"Can't update {optionPath}"} def __setComment(self, params): try: @@ -373,7 +370,7 @@ def __moveNode(self, params): "oldIndex": params["oldIndex"], } # Calculate the old parent path - oldParentPath = "/%s" % "/".join(List.fromChar(nodePath, "/")[:-1]) + oldParentPath = f"/{'/'.join(List.fromChar(nodePath, '/')[:-1])}" if not oldParentPath == destinationParentPath and newParentDict["value"].existsKey(nodeDict["key"]): return { "success": 0, @@ -437,7 +434,7 @@ def __copyKey(self, params): if not newParentDict: return {"success": 0, "op": "copyKey", "message": "Destination does not exist"} # Calculate the old parent path - oldParentPath = "/%s" % "/".join(List.fromChar(nodePath, "/")[:-1]) + oldParentPath = f"/{'/'.join(List.fromChar(nodePath, '/')[:-1])}" if not oldParentPath == destinationParentPath and newParentDict["value"].existsKey(newNodeName): return {"success": 0, "op": "copyKey", "message": "Another entry with the same name already exists"} @@ -547,7 +544,7 @@ def __showDiff(self, params): fromDate = str(params["fromVersion"]) toDate = str(params["toVersion"]) except Exception as e: - raise WErr(500, "Can't decode params: %s" % e) + raise WErr(500, f"Can't decode params: {e}") rpcClient = ConfigurationClient( url=gConfig.getValue("/DIRAC/Configuration/MasterServer", "Configuration/Server") ) @@ -561,7 +558,7 @@ def __showDiff(self, params): "totalLines": processedData["totalLines"], "html": self.render_string( "ConfigurationManager/diffConfig.tpl", - titles=("From version %s" % fromDate, "To version %s" % toDate), + titles=(f"From version {fromDate}", f"To version {toDate}"), diffList=processedData["diff"], ).decode("utf-8"), } @@ -573,7 +570,7 @@ def __rollback(self, params): try: rollbackVersion = str(params["rollbackToVersion"]) except Exception as e: - raise WErr(500, "Can't decode params: %s" % e) + raise WErr(500, f"Can't decode params: {e}") rpcClient = ConfigurationClient( url=gConfig.getValue("/DIRAC/Configuration/MasterServer", "Configuration/Server") ) @@ -605,10 +602,9 @@ def __history(self): return {"success": 1, "op": "showshowHistory", "result": cDict} def __download(self): - version = str(self.__configData["cfgData"].getCFG()["DIRAC"]["Configuration"]["Version"]) configName = str(self.__configData["cfgData"].getCFG()["DIRAC"]["Configuration"]["Name"]) - fileName = "cs.{}.{}".format(configName, version.replace(":", "").replace("-", "").replace(" ", "")) + fileName = f"cs.{configName}.{version.replace(':', '').replace('-', '').replace(' ', '')}" return {"success": 1, "op": "download", "result": self.__configData["strCfgData"], "fileName": fileName} diff --git a/src/WebAppDIRAC/WebApp/handler/DowntimesHandler.py b/src/WebAppDIRAC/WebApp/handler/DowntimesHandler.py index cf522c9f4..a2b6ae695 100644 --- a/src/WebAppDIRAC/WebApp/handler/DowntimesHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/DowntimesHandler.py @@ -10,7 +10,6 @@ class DowntimesHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" # Publisher client diff --git a/src/WebAppDIRAC/WebApp/handler/ExampleAppHandler.py b/src/WebAppDIRAC/WebApp/handler/ExampleAppHandler.py index c5d86d0a6..f3aa64c12 100644 --- a/src/WebAppDIRAC/WebApp/handler/ExampleAppHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/ExampleAppHandler.py @@ -3,7 +3,6 @@ class ExampleAppHandler(WebHandler): - DEFAULT_AUTHORIZATION = "all" def web_getJobData(self): diff --git a/src/WebAppDIRAC/WebApp/handler/FileCatalogHandler.py b/src/WebAppDIRAC/WebApp/handler/FileCatalogHandler.py index 4a6e6ebda..d8354fa10 100644 --- a/src/WebAppDIRAC/WebApp/handler/FileCatalogHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/FileCatalogHandler.py @@ -14,7 +14,6 @@ class FileCatalogHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" # Supported operands @@ -46,7 +45,7 @@ def web_getSelectedFiles(self, archivePath=None, lfnPath=None): os.makedirs(tmpdir) os.chdir(tmpdir) for lfn in lfnPath.split(","): - gLogger.always("Data manager get file %s" % lfn) + gLogger.always(f"Data manager get file {lfn}") last_slash = lfn.rfind("/") pos_relative = lfn.find("/") pos_relative = lfn.find("/", pos_relative + 1) @@ -54,7 +53,7 @@ def web_getSelectedFiles(self, archivePath=None, lfnPath=None): pos_relative = pos_relative pathInZip = lfn[pos_relative:last_slash] tmpPathInZip = tmpdir + pathInZip - gLogger.always("path in zip %s" % tmpPathInZip) + gLogger.always(f"path in zip {tmpPathInZip}") if not os.path.isdir(tmpPathInZip): os.makedirs(tmpPathInZip) result = dataMgr.getFile(str(lfn), destinationDir=str(tmpPathInZip)) @@ -107,10 +106,10 @@ def web_getMetadataFields(self): filemeta, dirmeta = result["Value"] for key in filemeta: callback[key] = "label" - gLogger.debug("getSelectorGrid: FileMetaFields callback %s" % callback) + gLogger.debug(f"getSelectorGrid: FileMetaFields callback {callback}") for key, value in dirmeta.items(): callback[key] = value.lower() - gLogger.debug("getSelectorGrid: Resulting callback %s" % callback) + gLogger.debug(f"getSelectorGrid: Resulting callback {callback}") return {"success": "true", "result": callback} def web_getQueryData(self, lfnPath=None, **kwargs): @@ -212,7 +211,7 @@ def web_getFilesData(self, limit=25, start=0, lfnPath=None, **kwargs): if lfnPath: req["path"] = lfnPath - gLogger.debug("submit: incoming request %s" % req) + gLogger.debug(f"submit: incoming request {req}") result = self.fc.findFilesByMetadataWeb(req["selection"], req["path"], start, limit) gLogger.debug("submit: result of findFilesByMetadataDetailed", result) if not result["OK"]: @@ -314,7 +313,7 @@ def web_getMetadataFilesInFile(self, selection="", lfnPath=None): gLogger.debug("submit: incoming request", req) result = self.fc.findFilesByMetadata(req["selection"], req["path"]) if not result["OK"]: - gLogger.error("submit: %s" % result["Message"]) + gLogger.error(f"submit: {result['Message']}") return {"success": "false", "error": result["Message"]} return FileResponse("\n".join([fileName for fileName in result["Value"]]), str(req)) diff --git a/src/WebAppDIRAC/WebApp/handler/JobLaunchpadHandler.py b/src/WebAppDIRAC/WebApp/handler/JobLaunchpadHandler.py index ba4408b46..2c7769ddd 100644 --- a/src/WebAppDIRAC/WebApp/handler/JobLaunchpadHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/JobLaunchpadHandler.py @@ -12,7 +12,6 @@ class JobLaunchpadHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" defaultParams = { "JobName": [1, "DIRAC"], @@ -48,7 +47,6 @@ def web_getProxyStatus(self): return self.__getProxyStatus() def __getProxyStatus(self): - proxyManager = ProxyManagerClient() group = self.getUserGroup() @@ -162,12 +160,12 @@ def web_jobSubmit(self): for key in self.request.files: try: if self.request.files[key][0].filename: - gLogger.info("\033[0;31m file - %s \033[0m " % self.request.files[key][0].filename) + gLogger.info(f"\x1b[0;31m file - {self.request.files[key][0].filename} \x1b[0m ") store.append(self.request.files[key][0]) except Exception: pass - gLogger.info("\033[0;31m *** %s \033[0m " % params) + gLogger.info(f"\x1b[0;31m *** {params} \x1b[0m ") clearFS = False # Clear directory flag fileNameList = [] @@ -193,7 +191,7 @@ def web_jobSubmit(self): exception_counter = 1 callback = { "success": "false", - "error": "An EXCEPTION happens during saving your sandbox file(s): %s" % str(x), + "error": f"An EXCEPTION happens during saving your sandbox file(s): {str(x)}", } sndBox = "" @@ -212,7 +210,7 @@ def web_jobSubmit(self): else: callback = {"success": "false", "error": result["Message"]} except Exception as x: - callback = {"success": "false", "error": "An EXCEPTION happens during job submittion: %s" % str(x)} + callback = {"success": "false", "error": f"An EXCEPTION happens during job submittion: {str(x)}"} if clearFS: shutil.rmtree(storePath) return callback diff --git a/src/WebAppDIRAC/WebApp/handler/JobMonitorHandler.py b/src/WebAppDIRAC/WebApp/handler/JobMonitorHandler.py index cb64d72a5..f4b3ba7f4 100644 --- a/src/WebAppDIRAC/WebApp/handler/JobMonitorHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/JobMonitorHandler.py @@ -16,7 +16,6 @@ class JobMonitorHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" __dataCache = DictCache.DictCache() @@ -109,7 +108,7 @@ def web_getSelectionData(self): else: prod = [["Nothing to display"]] else: - gLogger.error("JobMonitoringClient().getJobGroups() return error: %s" % result["Message"]) + gLogger.error(f"JobMonitoringClient().getJobGroups() return error: {result['Message']}") prod = [["Error happened on service side"]] callback["prod"] = prod @@ -127,7 +126,7 @@ def web_getSelectionData(self): else: site = [["Nothing to display"]] else: - gLogger.error("JobMonitoringClient().getSites() return error: %s" % result["Message"]) + gLogger.error(f"JobMonitoringClient().getSites() return error: {result['Message']}") site = [["Error happened on service side"]] callback["site"] = site # ## @@ -140,7 +139,7 @@ def web_getSelectionData(self): else: stat = [["Nothing to display"]] else: - gLogger.error("JobMonitoringClient().getStates() return error: %s" % result["Message"]) + gLogger.error(f"JobMonitoringClient().getStates() return error: {result['Message']}") stat = [["Error happened on service side"]] callback["status"] = stat # ## @@ -153,7 +152,7 @@ def web_getSelectionData(self): else: stat = [["Nothing to display"]] else: - gLogger.error("JobMonitoringClient().getMinorStates() return error: %s" % result["Message"]) + gLogger.error(f"JobMonitoringClient().getMinorStates() return error: {result['Message']}") stat = [["Error happened on service side"]] callback["minorstat"] = stat # ## @@ -166,7 +165,7 @@ def web_getSelectionData(self): else: app = [["Nothing to display"]] else: - gLogger.error("JobMonitoringClient().getApplicationstates() return error: %s" % result["Message"]) + gLogger.error(f"JobMonitoringClient().getApplicationstates() return error: {result['Message']}") app = [["Error happened on service side"]] callback["app"] = app # ## @@ -179,7 +178,7 @@ def web_getSelectionData(self): else: types = [["Nothing to display"]] else: - gLogger.error("JobMonitoringClient().getJobTypes() return error: %s" % result["Message"]) + gLogger.error(f"JobMonitoringClient().getJobTypes() return error: {result['Message']}") types = [["Error happened on service side"]] callback["types"] = types # ## @@ -199,7 +198,7 @@ def web_getSelectionData(self): owner = [[user]] callback["owner"] = owner else: - gLogger.error("JobMonitoringClient().getOwners() return error: %s" % result["Message"]) + gLogger.error(f"JobMonitoringClient().getOwners() return error: {result['Message']}") owner = [["Error happened on service side"]] callback["owner"] = owner @@ -298,7 +297,7 @@ def web_jobAction(self, JobID): return {"success": "true", "result": ""} if "InvalidJobIDs" in result: - return {"success": "false", "error": "Invalid JobIDs: %s" % result["InvalidJobIDs"]} + return {"success": "false", "error": f"Invalid JobIDs: {result['InvalidJobIDs']}"} if "NonauthorizedJobIDs" in result: return { "success": "false", @@ -464,7 +463,7 @@ def web_getSandbox(self, jobID: int = None, sandbox: str = "Output", check=None) result = client.downloadSandboxForJob(jobID, sandbox, inMemory=True) if not result["OK"]: - return {"success": "false", "error": "Error: %s" % result["Message"]} + return {"success": "false", "error": f"Error: {result['Message']}"} if check: return {"success": "true"} @@ -472,7 +471,7 @@ def web_getSandbox(self, jobID: int = None, sandbox: str = "Output", check=None) data = result["Value"] fname = f"{str(jobID)}_{sandbox}Sandbox.tar" self.set_header("Content-type", "application/x-tar") - self.set_header("Content-Disposition", 'attachment; filename="%s"' % fname) + self.set_header("Content-Disposition", f'attachment; filename="{fname}"') self.set_header("Content-Length", len(data)) self.set_header("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0") self.set_header("Pragma", "no-cache") diff --git a/src/WebAppDIRAC/WebApp/handler/JobSummaryHandler.py b/src/WebAppDIRAC/WebApp/handler/JobSummaryHandler.py index 8fb9fa5b8..8b2e44477 100644 --- a/src/WebAppDIRAC/WebApp/handler/JobSummaryHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/JobSummaryHandler.py @@ -253,7 +253,6 @@ class JobSummaryHandler(WebHandler): - DEFAULT_AUTHORIZATION = "all" pageNumber = 0 @@ -264,7 +263,7 @@ def web_getSelectionData(self): callback = {} result = WMSAdministratorClient().getSiteSummarySelectors() - gLogger.info("\033[0;31m ++++++: \033[0m %s" % result) + gLogger.info(f"\x1b[0;31m ++++++: \x1b[0m {result}") if result["OK"]: result = result["Value"] if len(result.get("Status", [])) > 0: @@ -356,7 +355,7 @@ def web_getData(self): else: gLogger.always("- E R R O R -") result = {"success": "false", "error": retVal["Message"]} - gLogger.info("\033[0;31m SITESUMMARY INDEX REQUEST: \033[0m %s" % (time() - pagestart)) + gLogger.info(f"\x1b[0;31m SITESUMMARY INDEX REQUEST: \x1b[0m {time() - pagestart}") return result def __request(self): diff --git a/src/WebAppDIRAC/WebApp/handler/MonitoringHandler.py b/src/WebAppDIRAC/WebApp/handler/MonitoringHandler.py index b9760f9b2..0fe22126f 100644 --- a/src/WebAppDIRAC/WebApp/handler/MonitoringHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/MonitoringHandler.py @@ -13,7 +13,6 @@ class MonitoringHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" __keysCache = DictCache.DictCache() @@ -237,7 +236,7 @@ def web_getCsvPlotData(self): data = rawData["data"] tS = int(TimeUtilities.toEpoch(params[2])) timeStart = tS - tS % granularity - strData = "epoch,%s\n" % ",".join(groupKeys) + strData = f"epoch,{','.join(groupKeys)}\n" for timeSlot in range(timeStart, int(TimeUtilities.toEpoch(params[3])), granularity): lineData = [str(timeSlot)] for key in groupKeys: @@ -245,9 +244,9 @@ def web_getCsvPlotData(self): lineData.append(str(data[key][timeSlot])) else: lineData.append("") - strData += "%s\n" % ",".join(lineData) + strData += f"{','.join(lineData)}\n" else: - strData = "%s\n" % ",".join(groupKeys) + strData = f"{','.join(groupKeys)}\n" strData += ",".join([str(rawData["data"][k]) for k in groupKeys]) return FileResponse(strData, str(params), ext="csv", cache=False) diff --git a/src/WebAppDIRAC/WebApp/handler/NotepadHandler.py b/src/WebAppDIRAC/WebApp/handler/NotepadHandler.py index 522e63cdf..2c994af7d 100644 --- a/src/WebAppDIRAC/WebApp/handler/NotepadHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/NotepadHandler.py @@ -2,7 +2,6 @@ class NotepadHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def index(self): diff --git a/src/WebAppDIRAC/WebApp/handler/PilotMonitorHandler.py b/src/WebAppDIRAC/WebApp/handler/PilotMonitorHandler.py index 198275293..3e7b69304 100644 --- a/src/WebAppDIRAC/WebApp/handler/PilotMonitorHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/PilotMonitorHandler.py @@ -9,7 +9,6 @@ class PilotMonitorHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def web_getPilotData(self): diff --git a/src/WebAppDIRAC/WebApp/handler/PilotSummaryHandler.py b/src/WebAppDIRAC/WebApp/handler/PilotSummaryHandler.py index 6465c7222..694fb4e1c 100644 --- a/src/WebAppDIRAC/WebApp/handler/PilotSummaryHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/PilotSummaryHandler.py @@ -8,7 +8,6 @@ class PilotSummaryHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def web_getPilotSummaryData(self): @@ -64,7 +63,7 @@ def __dict2string(self, req): result = result + str(key) + ": " + ", ".join(value) + "; " except Exception as x: pass - gLogger.info("\033[0;31m Exception: \033[0m %s" % x) + gLogger.info(f"\x1b[0;31m Exception: \x1b[0m {x}") result = result.strip() result = result[:-1] return result diff --git a/src/WebAppDIRAC/WebApp/handler/ProxyManagerHandler.py b/src/WebAppDIRAC/WebApp/handler/ProxyManagerHandler.py index 6e743ec78..0aaadaae1 100644 --- a/src/WebAppDIRAC/WebApp/handler/ProxyManagerHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/ProxyManagerHandler.py @@ -9,7 +9,6 @@ class ProxyManagerHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def web_getSelectionData(self, **kwargs): diff --git a/src/WebAppDIRAC/WebApp/handler/ProxyUploadHandler.py b/src/WebAppDIRAC/WebApp/handler/ProxyUploadHandler.py index c21d52dcc..13f4cc416 100644 --- a/src/WebAppDIRAC/WebApp/handler/ProxyUploadHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/ProxyUploadHandler.py @@ -7,7 +7,6 @@ class ProxyUploadHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def web_proxyUpload(self, pass_p12=None): @@ -89,7 +88,7 @@ def web_proxyUpload(self, pass_p12=None): shutil.rmtree(storePath) gLogger.exception(x) error = f"An exception has happen '{x}' {disclaimer}" - gLogger.debug("Service response: %s" % error) + gLogger.debug(f"Service response: {error}") return {"success": "false", "error": error} gLogger.info("Split certificate(s) to public and private keys") @@ -123,10 +122,10 @@ def web_proxyUpload(self, pass_p12=None): proxyChain = X509Chain() if not (result := proxyChain.loadChainFromFile(keyDict["pub"]))["OK"]: - return {"error": "Could not load the proxy: %s" % result["Message"], "success": "false"} + return {"error": f"Could not load the proxy: {result['Message']}", "success": "false"} if not (result := proxyChain.getIssuerCert())["OK"]: - return {"error": "Could not load the proxy: %s" % result["Message"], "success": "false"} + return {"error": f"Could not load the proxy: {result['Message']}", "success": "false"} issuerCert = result["Value"] diff --git a/src/WebAppDIRAC/WebApp/handler/PublicStateManagerHandler.py b/src/WebAppDIRAC/WebApp/handler/PublicStateManagerHandler.py index 4c7a43733..64c2b65f3 100644 --- a/src/WebAppDIRAC/WebApp/handler/PublicStateManagerHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/PublicStateManagerHandler.py @@ -2,7 +2,6 @@ class PublicStateManagerHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def web_getTreeMenuItems(self): diff --git a/src/WebAppDIRAC/WebApp/handler/RegistryManagerHandler.py b/src/WebAppDIRAC/WebApp/handler/RegistryManagerHandler.py index 15bdf5b87..265f01646 100644 --- a/src/WebAppDIRAC/WebApp/handler/RegistryManagerHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/RegistryManagerHandler.py @@ -8,14 +8,12 @@ class RegistryManagerHandler(WebSocketHandler): - DEFAULT_AUTHORIZATION = "authenticated" def on_open(self): self.__configData = {} def _on_message(self, msg): - self.log.info(f"RECEIVED {msg}") try: params = json.loads(msg) @@ -72,7 +70,6 @@ def __getData(self, params): sectionCfg = self.getSectionCfg("/Registry/Users") for username in sectionCfg.listAll(): - item = {} item["name"] = username props = sectionCfg[username] @@ -186,12 +183,10 @@ def getIfExists(self, elem, propsList): return "" def __addItem(self, params): - sectionPath = "/Registry/" configText = "" params = {k: str(v).strip() if v else v for k, v in params.items()} if params["type"] == "users": - sectionPath = sectionPath + "Users" if params["dn"]: configText = "DN = " + params["dn"] + "\n" @@ -203,7 +198,6 @@ def __addItem(self, params): configText = configText + "Email = " + params["email"] elif params["type"] == "groups": - sectionPath = sectionPath + "Groups" if params["users"]: configText = "Users = " + params["users"] + "\n" @@ -224,7 +218,6 @@ def __addItem(self, params): configText = configText + "AutoAddVOMS = " + params["autoaddvoms"] elif params["type"] == "hosts": - sectionPath = sectionPath + "Hosts" if params["dn"]: configText = "DN = " + params["dn"] + "\n" @@ -233,11 +226,9 @@ def __addItem(self, params): configText = configText + "Properties = " + params["properties"] elif params["type"] == "voms": - sectionPath = sectionPath + "VOMS/Servers" elif params["type"] == "servers": - sectionPath = sectionPath + "VOMS/Servers/" + params["vom"] if params["dn"]: configText = "DN = " + params["dn"] + "\n" @@ -259,7 +250,6 @@ def __addItem(self, params): return {"success": 0, "op": "addItem", "message": "Section can't be created. It already exists?"} def __editItem(self, params): - ret = self.__deleteItem(params) if ret["success"] == 1: ret = self.__addItem(params) @@ -272,7 +262,6 @@ def __editItem(self, params): configText = "" params = {k: str(v).strip() if v else v for k, v in params.items()} if params["type"] == "users": - sectionPath = sectionPath + "Users" if params["dn"]: configText = "DN = " + params["dn"] + "\n" @@ -284,7 +273,6 @@ def __editItem(self, params): configText = configText + "Email = " + params["email"] elif params["type"] == "groups": - sectionPath = sectionPath + "Groups" if params["users"]: configText = "Users = " + params["users"] + "\n" @@ -305,7 +293,6 @@ def __editItem(self, params): configText = configText + "AutoAddVOMS = " + params["autoaddvoms"] elif params["type"] == "hosts": - sectionPath = sectionPath + "Hosts" if params["dn"]: configText = "DN = " + params["dn"] + "\n" diff --git a/src/WebAppDIRAC/WebApp/handler/RequestMonitorHandler.py b/src/WebAppDIRAC/WebApp/handler/RequestMonitorHandler.py index 6f7809780..68b1ff956 100644 --- a/src/WebAppDIRAC/WebApp/handler/RequestMonitorHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/RequestMonitorHandler.py @@ -8,7 +8,6 @@ class RequestMonitorHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def initializeRequest(self): diff --git a/src/WebAppDIRAC/WebApp/handler/ResourceSummaryHandler.py b/src/WebAppDIRAC/WebApp/handler/ResourceSummaryHandler.py index 8d9d25549..2e31a1fb1 100644 --- a/src/WebAppDIRAC/WebApp/handler/ResourceSummaryHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/ResourceSummaryHandler.py @@ -22,7 +22,6 @@ def _getSelectionData(self, **kwargs) -> dict: elementStatuses = pub.getElementStatuses(self.ELEMENT_TYPE, None, None, None, None, None) if elementStatuses["OK"]: - for elementStatus in elementStatuses["Value"]: callback["status"].add(elementStatus[2]) callback["name"].add(elementStatus[0]) @@ -31,7 +30,6 @@ def _getSelectionData(self, **kwargs) -> dict: callback["tokenOwner"].add(elementStatus[8]) for key, value in callback.items(): - callback[key] = sorted([item] for item in list(value)) callback[key] = [["all"]] + callback[key] @@ -49,10 +47,9 @@ def combine(self, elementValues: list) -> dict: if len(statusSet) == 1: status = statusSet.pop() - reason = "All %s" % status + reason = f"All {status}" else: - if {"Active", "Degraded"} & set(statusSet): status = "Degraded" reason = "Not completely active" @@ -64,7 +61,7 @@ def combine(self, elementValues: list) -> dict: # Make a copy combined = {} combined.update(elementValues[0]) - combined["StatusType"] = "%d elements" % len(statuses) + combined["StatusType"] = f"{len(statuses)} elements" combined["Status"] = status combined["Reason"] = reason combined["DateEffective"] = "" @@ -229,7 +226,6 @@ def _getTimeline(self, requestParams: dict) -> dict: history = [] for status, dateEffective, reason in result["Value"]: - # history.append( [ history[ -1 ][ 0 ], str( dateEffective - timedelta( seconds = 1 ) ), '' ] ) history.append([status, str(dateEffective), reason]) @@ -297,7 +293,6 @@ def _getInfo(self, requestParams: dict) -> dict: class ResourceSummaryHandler(SummaryHandlerMix): - ELEMENT_TYPE = "Resource" def web_getSelectionData(self): @@ -336,7 +331,6 @@ def web_getResourceSummaryData(self, name=None, status=None, elementType=None, s elementTree = collections.defaultdict(list) for element in elementStatuses["Value"]: - elementDict = dict(zip(elementStatuses["Columns"], element)) elementDict["DateEffective"] = str(elementDict["DateEffective"]) @@ -348,7 +342,6 @@ def web_getResourceSummaryData(self, name=None, status=None, elementType=None, s elementList = [] for elementValues in elementTree.values(): - if len(elementValues) == 1: elementList.append(elementValues[0]) else: diff --git a/src/WebAppDIRAC/WebApp/handler/RootHandler.py b/src/WebAppDIRAC/WebApp/handler/RootHandler.py index 338dffd69..c31b5637a 100644 --- a/src/WebAppDIRAC/WebApp/handler/RootHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/RootHandler.py @@ -13,7 +13,6 @@ class RootHandler(WebHandler): - DEFAULT_AUTHORIZATION = "all" DEFAULT_LOCATION = "/" SUPPORTED_METHODS = ("GET",) @@ -178,7 +177,7 @@ def web_index(self, *, url_state="", theme="crisp", open_app="", **kwargs): with open(welcomeFile) as f: welcome = f.read().replace("\n", "") except Exception: - gLogger.warn("Welcome page not found here: %s" % welcomeFile) + gLogger.warn(f"Welcome page not found here: {welcomeFile}") # pylint: disable=no-member return TornadoResponse().render( diff --git a/src/WebAppDIRAC/WebApp/handler/SiteSummaryHandler.py b/src/WebAppDIRAC/WebApp/handler/SiteSummaryHandler.py index 165f27c94..3022c4c8b 100644 --- a/src/WebAppDIRAC/WebApp/handler/SiteSummaryHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/SiteSummaryHandler.py @@ -13,7 +13,6 @@ class SiteSummaryHandler(SummaryHandlerMix): - ELEMENT_TYPE = "Site" def web_getSelectionData(self, **kwargs): @@ -94,7 +93,7 @@ def _getInfo(self, requestParams: dict) -> dict: else: elementStatus["GOCDB"] += "(" for i in dirac_names["Value"]: - elementStatus["GOCDB"] += "%s " % i + elementStatus["GOCDB"] += f"{i} " elementStatus["GOCDB"] += ")" elementStatus["GGUS"] = ' {gocdb_name} tickets' convertName = { "CERN-PROD": "CERN", diff --git a/src/WebAppDIRAC/WebApp/handler/SpaceOccupancyHandler.py b/src/WebAppDIRAC/WebApp/handler/SpaceOccupancyHandler.py index 011dfd509..8f934b435 100644 --- a/src/WebAppDIRAC/WebApp/handler/SpaceOccupancyHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/SpaceOccupancyHandler.py @@ -9,7 +9,6 @@ class SpaceOccupancyHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def initializeRequest(self): @@ -54,13 +53,13 @@ def web_getSpaceOccupancyData(self, StorageElement="null"): spRes["LastCheckTime"] = str(sp[5]) if sp[4]: - spRes["Ratio"] = float("%.2f" % (sp[3] * 100 / sp[4])) + spRes["Ratio"] = float(f"{sp[3] * 100 / sp[4]:.2f}") else: spRes["Ratio"] = "-" - spRes["Free"] = float("%.2f" % sp[3]) - spRes["Total"] = float("%.2f" % sp[4]) - spRes["Guaranteed"] = float("%.2f" % sp[2]) + spRes["Free"] = float(f"{sp[3]:.2f}") + spRes["Total"] = float(f"{sp[4]:.2f}") + spRes["Guaranteed"] = float(f"{sp[2]:.2f}") # FIXME: call here SpaceTokenOccupancyPolicy and avoid hardcoding twice diff --git a/src/WebAppDIRAC/WebApp/handler/SystemAdministrationHandler.py b/src/WebAppDIRAC/WebApp/handler/SystemAdministrationHandler.py index ebedeec90..5f0771490 100644 --- a/src/WebAppDIRAC/WebApp/handler/SystemAdministrationHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/SystemAdministrationHandler.py @@ -13,7 +13,6 @@ class SystemAdministrationHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def web_getSysInfo(self): @@ -155,7 +154,7 @@ def web_hostAction(self, host=None, action=None, version=None): if not result["OK"]: if result["Message"].find("Unexpected EOF") > 0: - msg = "Signal 'Unexpected EOF' received: %s. Most likely DIRAC components" % result["Message"] + msg = f"Signal 'Unexpected EOF' received: {result['Message']}. Most likely DIRAC components" msg += _host + ": " + msg + " were successfully restarted." actionSuccess.append(msg) continue @@ -208,7 +207,6 @@ def web_componentAction(self, action=None, **kwargs): ) for i in result[hostname]: - system = i[0] component = i[1] try: @@ -234,7 +232,6 @@ def web_componentAction(self, action=None, **kwargs): return self.aftermath(actionSuccess, actionFailed, action, "Component") def aftermath(self, actionSuccess, actionFailed, action, prefix): - success = ", ".join(actionSuccess) failure = "\n".join(actionFailed) diff --git a/src/WebAppDIRAC/WebApp/handler/TokenManagerHandler.py b/src/WebAppDIRAC/WebApp/handler/TokenManagerHandler.py index ee24afe45..1549bd5ae 100644 --- a/src/WebAppDIRAC/WebApp/handler/TokenManagerHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/TokenManagerHandler.py @@ -9,7 +9,6 @@ class TokenManagerHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" @classmethod @@ -38,7 +37,7 @@ def web_getTokenManagerData(self, username="[]", **kwargs): return {"success": "false", "error": "You are not authorize to access these data"} result = self.tm.getUsersTokensInfo(list(json.loads(username))) - gLogger.info("*!*!*! RESULT: \n%s" % result) + gLogger.info(f"*!*!*! RESULT: \n{result}") if not result["OK"]: return {"success": "false", "error": result["Message"]} diff --git a/src/WebAppDIRAC/WebApp/handler/TransformationMonitorHandler.py b/src/WebAppDIRAC/WebApp/handler/TransformationMonitorHandler.py index b1243708e..34ae48e00 100644 --- a/src/WebAppDIRAC/WebApp/handler/TransformationMonitorHandler.py +++ b/src/WebAppDIRAC/WebApp/handler/TransformationMonitorHandler.py @@ -12,7 +12,6 @@ class TransformationMonitorHandler(WebHandler): - DEFAULT_AUTHORIZATION = "authenticated" def web_getSelectionData(self): @@ -149,7 +148,7 @@ def web_getTransformationData( else: callback = {"success": "true", "result": callback, "total": total, "date": None} - gLogger.info("\033[0;31m PRODUCTION SUBMIT REQUEST: \033[0m %s" % (datetime.datetime.utcnow() - pagestart)) + gLogger.info(f"\x1b[0;31m PRODUCTION SUBMIT REQUEST: \x1b[0m {datetime.datetime.utcnow() - pagestart}") return callback def web_action(self, data_kind, id: int, tasks: int = None): @@ -231,7 +230,7 @@ def __fileRetry(self, prodid, mode): return {"success": "false", "error": "No files found"} for status in sorted(result["Value"]): count = result["Value"][status] - percent = "%.1f" % ((count * 100.0) / total) + percent = f"{count * 100.0 / total:.1f}" resList.append((status, str(count), percent)) resList.append(("Total", total, "-")) gLogger.debug("#######", result) @@ -291,7 +290,7 @@ def __transformationFileStatus(self, transid): return {"success": "false", "error": "No files found"} for status in sorted(result["Value"]): count = result["Value"][status] - percent = "%.1f" % ((count * 100.0) / total) + percent = f"{count * 100.0 / total:.1f}" resList.append((status, str(count), percent)) resList.append(("Total", total, "-")) gLogger.debug("#######", result) diff --git a/src/WebAppDIRAC/scripts/dirac_webapp_run.py b/src/WebAppDIRAC/scripts/dirac_webapp_run.py index badf6178b..6c6be0ebb 100755 --- a/src/WebAppDIRAC/scripts/dirac_webapp_run.py +++ b/src/WebAppDIRAC/scripts/dirac_webapp_run.py @@ -37,7 +37,7 @@ def _createStaticSymlinks(targetDir): destination = os.path.join(targetDir, extension) # If there is more than one suffix append a counter if i >= 1: - destination += "-%s" % i + destination += f"-{i}" gLogger.notice(" creating symlink from", f"{path} to {destination}") if os.path.islink(destination): if path == os.readlink(destination): @@ -67,7 +67,7 @@ def _checkDIRACVersion(): deps = [Requirement(x) for x in requires("WebAppDIRAC")] deps = [x for x in deps if x.name.lower() == "dirac"] if len(deps) != 1: - raise NotImplementedError("This shouldn't be possible: %r" % deps) + raise NotImplementedError(f"This shouldn't be possible: {deps!r}") dirac_version = version("DIRAC") dirac_spec = deps[0].specifier if dirac_version not in dirac_spec: diff --git a/src/WebAppDIRAC/scripts/tornado-start-web.py b/src/WebAppDIRAC/scripts/tornado-start-web.py index c5e410573..aaa76fbff 100644 --- a/src/WebAppDIRAC/scripts/tornado-start-web.py +++ b/src/WebAppDIRAC/scripts/tornado-start-web.py @@ -35,7 +35,7 @@ def main(): try: from WebAppDIRAC.Core.App import App except ImportError as e: - gLogger.fatal("Web portal is not installed. %s" % repr(e)) + gLogger.fatal(f"Web portal is not installed. {repr(e)}") sys.exit(1) # Get routes and settings for a portal