Skip to content

Commit

Permalink
refactor: Convert percent formatted strings to f-strings
Browse files Browse the repository at this point in the history
find . -name '*.py' -exec pyupgrade --py39-plus {} +
find . -name '*.py' -exec pyupgrade --py39-plus {} +
  • Loading branch information
chrisburr committed Aug 19, 2022
1 parent 79b85ba commit 9948d0e
Show file tree
Hide file tree
Showing 18 changed files with 54 additions and 52 deletions.
4 changes: 2 additions & 2 deletions src/WebAppDIRAC/Core/App.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def bootstrap(self):
message += "The following protocols are provided: %s" % str(aviableProtocols)
gLogger.warn(message)

self.log.debug(" - %s" % "\n - ".join(["%s = %s" % (k, sslops[k]) for k in sslops]))
self.log.debug(" - %s" % "\n - ".join([f"{k} = {sslops[k]}" for k in sslops]))
srv = tornado.httpserver.HTTPServer(self.__app, ssl_options=sslops, xheaders=True)
port = Conf.HTTPSPort()
srv.listen(port)
Expand All @@ -164,7 +164,7 @@ def run(self):
bu = Conf.rootURL().strip("/")
urls = []
for proto, port in self.__servers:
urls.append("%s://0.0.0.0:%s/%s/" % (proto, port, bu))
urls.append(f"{proto}://0.0.0.0:{port}/{bu}/")
self.log.always("Listening on %s" % " and ".join(urls))
tornado.autoreload.add_reload_hook(self.__reloadAppCB)
tornado.ioloop.IOLoop.instance().start()
6 changes: 3 additions & 3 deletions src/WebAppDIRAC/Core/CoreHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ def get(self, setup, group, route):
proto = self.request.protocol
if "X-Scheme" in self.request.headers:
proto = self.request.headers["X-Scheme"]
nurl = "%s://%s%s/" % (proto, self.request.host, o.path)
nurl = f"{proto}://{self.request.host}{o.path}/"
if o.query:
nurl = "%s?%s" % (nurl, o.query)
nurl = f"{nurl}?{o.query}"
self.redirect(nurl, permanent=True)
elif self.__action == "sendToRoot":
dest = "/"
rootURL = Conf.rootURL()
if rootURL:
dest += "%s/" % rootURL.strip("/")
if setup and group:
dest += "s:%s/g:%s/" % (setup, group)
dest += f"s:{setup}/g:{group}/"
self.redirect(dest)
12 changes: 6 additions & 6 deletions src/WebAppDIRAC/Lib/Conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def getCSValue(opt, defValue=None):
:return: defValue type result
"""
return gConfig.getValue("%s/%s" % (BASECS, opt), defValue)
return gConfig.getValue(f"{BASECS}/{opt}", defValue)


def getCSSections(opt):
Expand All @@ -28,7 +28,7 @@ def getCSSections(opt):
:return: S_OK(list)/S_ERROR()
"""
return gConfig.getSections("%s/%s" % (BASECS, opt))
return gConfig.getSections(f"{BASECS}/{opt}")


def getCSOptions(opt):
Expand All @@ -38,7 +38,7 @@ def getCSOptions(opt):
:return: S_OK(list)/S_ERROR()
"""
return gConfig.getOptions("%s/%s" % (BASECS, opt))
return gConfig.getOptions(f"{BASECS}/{opt}")


def getCSOptionsDict(opt):
Expand All @@ -48,7 +48,7 @@ def getCSOptionsDict(opt):
:return: S_OK(dict)/S_ERROR()
"""
return gConfig.getOptionsDict("%s/%s" % (BASECS, opt))
return gConfig.getOptionsDict(f"{BASECS}/{opt}")


def getTitle():
Expand Down Expand Up @@ -235,7 +235,7 @@ def getAuthSectionForHandler(route):
:return: str
"""
return "%s/Access/%s" % (BASECS, route)
return f"{BASECS}/Access/{route}"


@deprecated("This funtion is deprecated, use 'tabs' instead.")
Expand Down Expand Up @@ -329,4 +329,4 @@ def getAppSettings(app):
:return: S_OK(dict)/S_ERROR
"""
return gConfig.getOptionsDictRecursively("%s/%s" % (BASECS, app))
return gConfig.getOptionsDictRecursively(f"{BASECS}/{app}")
10 changes: 5 additions & 5 deletions src/WebAppDIRAC/Lib/SessionData.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,11 @@ def __isGroupAuthApp(self, appLoc):
gLogger.error("Application handler does not exists:", appLoc)
return False
if handlerLoc not in self.__handlers:
gLogger.error("Handler %s required by %s does not exist!" % (handlerLoc, appLoc))
gLogger.error(f"Handler {handlerLoc} required by {appLoc} does not exist!")
return False
handler = self.__handlers[handlerLoc]
auth = AuthManager(Conf.getAuthSectionForHandler(handlerLoc))
gLogger.info("Authorization: %s -> %s" % (dict(self.__credDict), handler.AUTH_PROPS))
gLogger.info(f"Authorization: {dict(self.__credDict)} -> {handler.AUTH_PROPS}")
return auth.authQuery("", dict(self.__credDict), handler.AUTH_PROPS)

def __generateSchema(self, base, path):
Expand All @@ -106,21 +106,21 @@ def __generateSchema(self, base, path):
"""
# Calculate schema
schema = []
fullName = "%s/%s" % (base, path)
fullName = f"{base}/{path}"
result = gConfig.getSections(fullName)
if not result["OK"]:
return schema
sectionsList = result["Value"]
for sName in sectionsList:
subSchema = self.__generateSchema(base, "%s/%s" % (path, sName))
subSchema = self.__generateSchema(base, f"{path}/{sName}")
if subSchema:
schema.append((sName, subSchema))
result = gConfig.getOptions(fullName)
if not result["OK"]:
return schema
optionsList = result["Value"]
for opName in optionsList:
opVal = gConfig.getValue("%s/%s" % (fullName, opName))
opVal = gConfig.getValue(f"{fullName}/{opName}")
if opVal.startswith("link|"):
schema.append(("link", opName, opVal[5:])) # pylint: disable=unsubscriptable-object
continue
Expand Down
2 changes: 1 addition & 1 deletion src/WebAppDIRAC/WebApp/handler/AccountingHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def __getUniqueKeyValues(self, typeName):
siteLevel = {}
for siteName in retVal["Value"]["Site"]:
sitePrefix = siteName.split(".")[0].strip()
level = gConfig.getValue("/Resources/Sites/%s/%s/MoUTierLevel" % (sitePrefix, siteName), 10)
level = gConfig.getValue(f"/Resources/Sites/{sitePrefix}/{siteName}/MoUTierLevel", 10)
if level not in siteLevel:
siteLevel[level] = []
siteLevel[level].append(siteName)
Expand Down
4 changes: 2 additions & 2 deletions src/WebAppDIRAC/WebApp/handler/ComponentHistoryHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,15 +118,15 @@ def __request(self):
time = self.get_argument("startTime")
else:
time = "00:00"
date = datetime.datetime.strptime("%s-%s" % (self.get_argument("startDate"), time), "%Y-%m-%d-%H:%M")
date = datetime.datetime.strptime("{}-{}".format(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:
if len(self.get_argument("endTime")) > 0:
time = self.get_argument("endTime")
else:
time = "00:00"
date = datetime.datetime.strptime("%s-%s" % (self.get_argument("endDate"), time), "%Y-%m-%d-%H:%M")
date = datetime.datetime.strptime("{}-{}".format(self.get_argument("endDate"), time), "%Y-%m-%d-%H:%M")
req["installation"]["UnInstallationTime.smaller"] = date

return req
18 changes: 8 additions & 10 deletions src/WebAppDIRAC/WebApp/handler/ConfigurationManagerHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def __htmlComment(self, rawComment):
continue
commentLines.append(line)
if commentLines or commiter:
return "%s<small><strong>%s</strong></small>" % ("<br/>".join(commentLines), commiter)
return "{}<small><strong>{}</strong></small>".format("<br/>".join(commentLines), commiter)
return False

def __showConfigurationAsText(self):
Expand Down Expand Up @@ -174,7 +174,7 @@ def __setOptionValue(self, params):
self.__configData["cfgData"].setOptionValue(optionPath, optionValue)

if self.__configData["cfgData"].getValue(optionPath) == optionValue:
self.log.info("Set option value", "%s = %s" % (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}

Expand All @@ -188,7 +188,7 @@ def __setComment(self, params):
self.__setCommiter()

self.__configData["cfgData"].setComment(path, value)
self.log.info("Set comment", "%s = %s" % (path, value))
self.log.info("Set comment", f"{path} = {value}")
return {
"success": 1,
"op": "setComment",
Expand Down Expand Up @@ -303,8 +303,8 @@ def __createOption(self, params):
return {"success": 0, "op": "createOption", "message": "Options can't have a / in the name"}
if len(optionValue) == 0:
return {"success": 0, "op": "createOption", "message": "Options should have values!"}
optionPath = "%s/%s" % (parentPath, optionName)
self.log.info("Creating option", "%s = %s" % (optionPath, optionValue))
optionPath = f"{parentPath}/{optionName}"
self.log.info("Creating option", f"{optionPath} = {optionValue}")
if not self.__configData["cfgData"].existsOption(optionPath):
self.__setCommiter()
self.__configData["cfgData"].setOptionValue(optionPath, optionValue)
Expand Down Expand Up @@ -336,9 +336,7 @@ def __moveNode(self, params):
"oldIndex": params["oldIndex"],
}

self.log.info(
"Moving node", "Moving %s under %s before pos %s" % (nodePath, destinationParentPath, beforeOfIndex)
)
self.log.info("Moving node", f"Moving {nodePath} under {destinationParentPath} before pos {beforeOfIndex}")
cfgData = self.__configData["cfgData"].getCFG()

nodeDict = cfgData.getRecursive(nodePath)
Expand Down Expand Up @@ -584,7 +582,7 @@ def __rollback(self, params):
return {"success": 0, "op": "rollback", "message": retVal["Value"]}

def __setCommiter(self):
commiter = "%s@%s - %s" % (
commiter = "{}@{} - {}".format(
self.getUserName(),
self.getUserGroup(),
datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
Expand All @@ -610,7 +608,7 @@ def __download(self):

version = str(self.__configData["cfgData"].getCFG()["DIRAC"]["Configuration"]["Version"])
configName = str(self.__configData["cfgData"].getCFG()["DIRAC"]["Configuration"]["Name"])
fileName = "cs.%s.%s" % (configName, version.replace(":", "").replace("-", "").replace(" ", ""))
fileName = "cs.{}.{}".format(configName, version.replace(":", "").replace("-", "").replace(" ", ""))

return {"success": 1, "op": "download", "result": self.__configData["strCfgData"], "fileName": fileName}

Expand Down
4 changes: 2 additions & 2 deletions src/WebAppDIRAC/WebApp/handler/DowntimesHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ def web_getDowntimesData(

requestParams["startDate"] = datetime.utcnow()
if startDate and startTime:
requestParams["startDate"] = datetime.strptime("%s %s" % (startDate, startTime), "%Y-%m-%d %H:%M")
requestParams["startDate"] = datetime.strptime(f"{startDate} {startTime}", "%Y-%m-%d %H:%M")

requestParams["endDate"] = datetime.utcnow()
if endDate and endTime:
requestParams["endDate"] = datetime.strptime("%s %s" % (endDate, endTime), "%Y-%m-%d %H:%M")
requestParams["endDate"] = datetime.strptime(f"{endDate} {endTime}", "%Y-%m-%d %H:%M")

gLogger.info("Request parameters:", requestParams)

Expand Down
4 changes: 2 additions & 2 deletions src/WebAppDIRAC/WebApp/handler/FileCatalogHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def web_getSelectedFiles(self, archivePath=None, lfnPath=None):
pos_relative = absolutePath.find("/", pos_relative + 1)
pos_relative = pos_relative + 1
relativePath = absolutePath[pos_relative:]
gLogger.always("relativePath %s, file %s" % (relativePath, filename))
gLogger.always(f"relativePath {relativePath}, file {filename}")
zFile.write(os.path.join(absolutePath, filename))
zFile.close()
shutil.rmtree(tmpdir)
Expand Down Expand Up @@ -239,7 +239,7 @@ def web_getFilesData(self, limit=25, start=0, lfnPath=None, **kwargs):
meta = ""
if "Metadata" in value:
m = value["Metadata"]
meta = "; ".join(["%s: %s" % (i, j) for (i, j) in m.items()])
meta = "; ".join([f"{i}: {j}" for (i, j) in m.items()])

dirnameList = key.split("/")
dirname = "/".join(dirnameList[: len(dirnameList) - 1])
Expand Down
2 changes: 1 addition & 1 deletion src/WebAppDIRAC/WebApp/handler/JobLaunchpadHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def __getProxyStatus(self):
defaultSeconds = 24 * 3600 + 60 # 24H + 1min
validSeconds = gConfig.getValue("/Registry/DefaultProxyLifeTime", defaultSeconds)

gLogger.info("\033[0;31m userHasProxy(%s, %s, %s) \033[0m" % (userDN, group, validSeconds))
gLogger.info(f"\033[0;31m userHasProxy({userDN}, {group}, {validSeconds}) \033[0m")

if (result := proxyManager.userHasProxy(userDN, group, validSeconds))["OK"]:
return {"success": "true", "result": "true" if result["Value"] else "false"}
Expand Down
2 changes: 1 addition & 1 deletion src/WebAppDIRAC/WebApp/handler/JobMonitorHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ def web_getSandbox(self, jobID: int = None, sandbox: str = "Output", check=None)
return {"success": "true"}

data = result["Value"]
fname = "%s_%sSandbox.tar" % (str(jobID), sandbox)
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-Length", len(data))
Expand Down
2 changes: 1 addition & 1 deletion src/WebAppDIRAC/WebApp/handler/JobSummaryHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ def web_getSelectionData(self):
def web_getData(self):
pagestart = time()
result = self.__request()
gLogger.always("getSiteSummaryWeb(%s,%s,%s,%s)" % (result, self.globalSort, self.pageNumber, self.numberOfJobs))
gLogger.always(f"getSiteSummaryWeb({result},{self.globalSort},{self.pageNumber},{self.numberOfJobs})")
retVal = WMSAdministratorClient().getSiteSummaryWeb(result, [], self.pageNumber, self.numberOfJobs)
gLogger.always("\033[0;31m YO: \033[0m", result)
if retVal["OK"]:
Expand Down
2 changes: 1 addition & 1 deletion src/WebAppDIRAC/WebApp/handler/MonitoringHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __getUniqueKeyValues(self, typeName):
siteLevel = {}
for siteName in retVal["Value"]["Site"]:
sitePrefix = siteName.split(".")[0].strip()
level = gConfig.getValue("/Resources/Sites/%s/%s/MoUTierLevel" % (sitePrefix, siteName), 10)
level = gConfig.getValue(f"/Resources/Sites/{sitePrefix}/{siteName}/MoUTierLevel", 10)
if level not in siteLevel:
siteLevel[level] = []
siteLevel[level].append(siteName)
Expand Down
4 changes: 3 additions & 1 deletion src/WebAppDIRAC/WebApp/handler/RootHandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ def web_login(self, provider, next="/DIRAC", **kwargs):
cli = result["Value"]
cli.scope = ""
if provider:
cli.metadata["authorization_endpoint"] = "%s/%s" % (cli.get_metadata("authorization_endpoint"), provider)
cli.metadata["authorization_endpoint"] = "{}/{}".format(
cli.get_metadata("authorization_endpoint"), provider
)

uri, state, session = cli.submitNewSession()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def web_getSysInfo(self):
callback[i]["Host"] = callback[i]["HostName"]
callback[i]["Timestamp"] = str(callback[i].get("Timestamp", "unknown"))
# We have to keep the backward compatibility (this can heppen when we do not update one host to v6r15 ...
callback[i]["DIRAC"] = "%s,%s" % (
callback[i]["DIRAC"] = "{},{}".format(
callback[i].get("DIRACVersion", callback[i].get("DIRAC", "")),
callback[i].get("Extension", callback[i].get("Extensions", "")),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ def web_getTier1Sites(self):
return {"success": True, "data": tier1}

def web_setSite(self, TransformationId: int, RunNumber: int, Site):
gLogger.info("\033[0;31m setTransformationRunsSite(%s, %s, %s) \033[0m" % (TransformationId, RunNumber, Site))
gLogger.info(f"\033[0;31m setTransformationRunsSite({TransformationId}, {RunNumber}, {Site}) \033[0m")
result = TransformationClient().setTransformationRunsSite(TransformationId, RunNumber, Site)
if result["OK"]:
return {"success": "true", "result": "true"}
Expand Down
Loading

0 comments on commit 9948d0e

Please sign in to comment.