Skip to content

Commit f8b5414

Browse files
committed
style: f-strings and logging interpolation
1 parent b1a6d34 commit f8b5414

File tree

5 files changed

+63
-62
lines changed

5 files changed

+63
-62
lines changed

qualysapi/api_actions.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def getHost(self, host):
2323

2424
def getHostRange(self, start, end):
2525
call = "/api/2.0/fo/asset/host/"
26-
parameters = {"action": "list", "ips": start + "-" + end}
26+
parameters = {"action": "list", "ips": f"{start}-{end}"}
2727
hostData = objectify.fromstring(self.request(call, parameters).encode("utf-8"))
2828
hostArray = []
2929
for host in hostData.RESPONSE.HOST_LIST.HOST:
@@ -78,7 +78,7 @@ def listAssetGroups(self, groupName=""):
7878
agData = objectify.fromstring(self.request(call).encode("utf-8"))
7979
else:
8080
agData = objectify.fromstring(
81-
self.request(call, "title=" + groupName).encode("utf-8")
81+
self.request(call, f"title={groupName}").encode("utf-8")
8282
)
8383

8484
groupsArray = []

qualysapi/api_methods.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@
100100
for auth_type in set(
101101
["ibm_db2", "ms_sql", "oracle", "oracle_listener", "snmp", "unix", "windows",]
102102
):
103-
api_methods["2"].add("api/2.0/fo/auth/%s/" % auth_type)
103+
api_methods["2"].add(f"api/2.0/fo/auth/{auth_type}/")
104104
# WAS GET methods when no POST data.
105105
api_methods["was no data get"] = set(
106106
[

qualysapi/config.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def __init__(
6060

6161
# apply bitmask to current mode to check ONLY user access permissions.
6262
if (mode & (stat.S_IRWXG | stat.S_IRWXO)) != 0:
63-
logger.warning("%s permissions allows more than user access." % (filename,))
63+
logger.warning("%s permissions allows more than user access.", filename)
6464

6565
self._cfgparse.read(self._cfgfile)
6666

@@ -136,9 +136,10 @@ def __init__(
136136
proxy_port_url = proxy_port
137137
proxy_port = self._cfgparse.get("proxy", "proxy_port")
138138
logger.warning(
139-
"Proxy port from url overwritten by specified proxy_port from config:"
139+
"Proxy port from url overwritten by specified proxy_port from config: %s --> %s",
140+
proxy_port_url,
141+
proxy_port,
140142
)
141-
logger.warning("%s --> %s" % (proxy_port_url, proxy_port))
142143
else:
143144
proxy_port = self._cfgparse.get("proxy", "proxy_port")
144145
if not proxy_port:
@@ -169,10 +170,10 @@ def __init__(
169170
proxy_config = proxy_url
170171
if proxy_port:
171172
# Proxy port requested.
172-
proxy_config += ":" + proxy_port
173+
proxy_config += f":{proxy_port}"
173174
if proxy_username:
174175
# Proxy authentication requested.
175-
proxy_config = proxy_username + ":" + proxy_password + "@" + proxy_config
176+
proxy_config = f"{proxy_username}:{proxy_password}@{proxy_config}"
176177
# Prefix by proxy protocol.
177178
proxy_config = proxy_protocol + proxy_config
178179
# Set up proxy if applicable.

qualysapi/connector.py

+52-52
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@ def __init__(self, auth, server="qualysapi.qualys.com", proxies=None, max_retrie
5555
qualysapi.api_methods.api_methods_with_trailing_slash
5656
)
5757
self.proxies = proxies
58-
logger.debug("proxies = \n%s" % proxies)
58+
logger.debug("proxies = \n%s", proxies)
5959
# Set up requests max_retries.
60-
logger.debug("max_retries = \n%s" % max_retries)
60+
logger.debug("max_retries = \n%s", max_retries)
6161
self.session = requests.Session()
6262
http_max_retries = requests.adapters.HTTPAdapter(max_retries=max_retries)
6363
https_max_retries = requests.adapters.HTTPAdapter(max_retries=max_retries)
@@ -120,22 +120,22 @@ def url_api_version(self, api_version):
120120
# Set base url depending on API version.
121121
if api_version == 1:
122122
# QualysGuard API v1 url.
123-
url = "https://%s/msp/" % (self.server,)
123+
url = f"https://{self.server}/msp/"
124124
elif api_version == 2:
125125
# QualysGuard API v2 url.
126-
url = "https://%s/" % (self.server,)
126+
url = f"https://{self.server}/"
127127
elif api_version == "was":
128128
# QualysGuard REST v3 API url (Portal API).
129-
url = "https://%s/qps/rest/3.0/" % (self.server,)
129+
url = f"https://{self.server}/qps/rest/3.0/"
130130
elif api_version == "am":
131131
# QualysGuard REST v1 API url (Portal API).
132-
url = "https://%s/qps/rest/1.0/" % (self.server,)
132+
url = f"https://{self.server}/qps/rest/1.0/"
133133
elif api_version == "am2":
134134
# QualysGuard REST v1 API url (Portal API).
135-
url = "https://%s/qps/rest/2.0/" % (self.server,)
135+
url = f"https://{self.server}/qps/rest/2.0/"
136136
else:
137-
raise Exception("Unknown QualysGuard API Version Number (%s)" % (api_version,))
138-
logger.debug("Base url =\n%s" % (url))
137+
raise Exception(f"Unknown QualysGuard API Version Number {api_version}")
138+
logger.debug("Base url =\n%s", url)
139139
return url
140140

141141
def format_http_method(self, api_version, api_call, data):
@@ -185,7 +185,7 @@ def preformat_call(self, api_call):
185185
api_call_formatted = api_call_formatted.rstrip("?")
186186
if api_call != api_call_formatted:
187187
# Show difference
188-
logger.debug("api_call post strip =\n%s" % api_call_formatted)
188+
logger.debug("api_call post strip =\n%s", api_call_formatted)
189189
return api_call_formatted
190190

191191
def format_call(self, api_version, api_call):
@@ -195,7 +195,7 @@ def format_call(self, api_version, api_call):
195195
# Remove possible starting slashes or trailing question marks in call.
196196
api_call = api_call.lstrip("/")
197197
api_call = api_call.rstrip("?")
198-
logger.debug("api_call post strip =\n%s" % api_call)
198+
logger.debug("api_call post strip =\n%s", api_call)
199199
# Make sure call always ends in slash for API v2 calls.
200200
if api_version == 2 and api_call[-1] != "/":
201201
# Add slash.
@@ -216,25 +216,25 @@ def format_payload(self, api_version, data):
216216
# Check if string type.
217217
if type(data) == str:
218218
# Convert to dictionary.
219-
logger.debug("Converting string to dict:\n%s" % data)
219+
logger.debug("Converting string to dict:\n%s", data)
220220
# Remove possible starting question mark & ending ampersands.
221221
data = data.lstrip("?")
222222
data = data.rstrip("&")
223223
# Convert to dictionary.
224224
data = parse_qs(data)
225-
logger.debug("Converted:\n%s" % str(data))
225+
logger.debug("Converted:\n%s", str(data))
226226
elif api_version in ("am", "was", "am2"):
227227
if type(data) == etree._Element:
228228
logger.debug("Converting lxml.builder.E to string")
229229
data = etree.tostring(data)
230-
logger.debug("Converted:\n%s" % data)
230+
logger.debug("Converted:\n%s", data)
231231
return data
232232

233233
def build_request(self, api_call, data=None, api_version=None, http_method=None):
234-
logger.debug("api_call =\n%s" % api_call)
235-
logger.debug("api_version =\n%s" % api_version)
236-
logger.debug("data %s =\n %s" % (type(data), str(data)))
237-
logger.debug("http_method =\n%s" % http_method)
234+
logger.debug("api_call =\n%s", api_call)
235+
logger.debug("api_version =\n%s", api_version)
236+
logger.debug("data %s =\n %s", type(data), str(data))
237+
logger.debug("http_method =\n%s", http_method)
238238

239239
#
240240
# Determine API version.
@@ -252,32 +252,31 @@ def build_request(self, api_call, data=None, api_version=None, http_method=None)
252252
#
253253
# Set up headers.
254254
headers = {
255-
"X-Requested-With": "Parag Baxi QualysAPI (python) v%s"
256-
% (qualysapi.version.__version__,)
255+
"X-Requested-With": f"Parag Baxi QualysAPI (python) v{qualysapi.version.__version__}"
257256
}
258-
logger.debug("headers =\n%s" % (str(headers)))
257+
logger.debug("headers =\n%s", str(headers))
259258
# Portal API takes in XML text, requiring custom header.
260259
if api_version in ("am", "was", "am2"):
261260
headers["Content-type"] = "text/xml"
262261
#
263262
# Set up http request method, if not specified.
264263
if not http_method:
265264
http_method = self.format_http_method(api_version, api_call, data)
266-
logger.debug("http_method =\n%s" % http_method)
265+
logger.debug("http_method =\n%s", http_method)
267266
#
268267
# Format API call.
269268
api_call = self.format_call(api_version, api_call)
270-
logger.debug("api_call =\n%s" % (api_call))
269+
logger.debug("api_call =\n%s", api_call)
271270
# Append api_call to url.
272271
url += api_call
273272
#
274273
# Format data, if applicable.
275274
if data is not None:
276275
data = self.format_payload(api_version, data)
277276

278-
logger.debug("url =\n%s" % (str(url)))
279-
logger.debug("data =\n%s" % (str(data)))
280-
logger.debug("headers =\n%s" % (str(headers)))
277+
logger.debug("url =\n%s", str(url))
278+
logger.debug("data =\n%s", str(data))
279+
logger.debug("headers =\n%s", str(headers))
281280

282281
return url, data, headers
283282

@@ -313,19 +312,18 @@ def request_streaming(
313312
stream=True,
314313
verify=verify,
315314
)
316-
logger.debug("response headers =\n%s" % (str(request.headers)))
315+
logger.debug("response headers =\n%s", str(request.headers))
317316
#
318317
# Remember how many times left user can make against api_call.
319318
try:
320319
self.rate_limit_remaining[api_call] = int(request.headers["x-ratelimit-remaining"])
321320
logger.debug(
322-
"rate limit for api_call, %s = %s"
323-
% (api_call, self.rate_limit_remaining[api_call])
321+
"rate limit for api_call, %s = %s", api_call, self.rate_limit_remaining[api_call]
324322
)
325323
if self.rate_limit_remaining[api_call] <= 0:
326324
logger.critical(
327-
"ATTENTION! RATE LIMIT HAS BEEN REACHED (remaining api calls = %s)!"
328-
% self.rate_limit_remaining[api_call]
325+
"ATTENTION! RATE LIMIT HAS BEEN REACHED (remaining api calls = %s)!",
326+
self.rate_limit_remaining[api_call],
329327
)
330328
except KeyError as e:
331329
# Likely a bad api_call.
@@ -353,8 +351,8 @@ def request(
353351
354352
"""
355353

356-
logger.debug("concurrent_scans_retries =\n%s" % str(concurrent_scans_retries))
357-
logger.debug("concurrent_scans_retry_delay =\n%s" % str(concurrent_scans_retry_delay))
354+
logger.debug("concurrent_scans_retries =\n%s", str(concurrent_scans_retries))
355+
logger.debug("concurrent_scans_retry_delay =\n%s", str(concurrent_scans_retry_delay))
358356
concurrent_scans_retries = int(concurrent_scans_retries)
359357
concurrent_scans_retry_delay = int(concurrent_scans_retry_delay)
360358

@@ -367,9 +365,9 @@ def request(
367365
rate_warn_threshold = 10
368366
while retries <= concurrent_scans_retries:
369367
# Make request.
370-
logger.debug("url =\n%s" % (str(url)))
371-
logger.debug("data =\n%s" % (str(data)))
372-
logger.debug("headers =\n%s" % (str(headers)))
368+
logger.debug("url =\n%s", str(url))
369+
logger.debug("data =\n%s", str(data))
370+
logger.debug("headers =\n%s", str(headers))
373371
if http_method == "get":
374372
# GET
375373
logger.debug("GET request.")
@@ -393,7 +391,7 @@ def request(
393391
proxies=self.proxies,
394392
verify=verify,
395393
)
396-
logger.debug("response headers =\n%s" % (str(request.headers)))
394+
logger.debug("response headers =\n%s", str(request.headers))
397395
# Force request encoding value, the automatic detection is very long for large files (report for example)
398396
# And sometimes with MemoryError
399397
if request.encoding is None:
@@ -405,25 +403,27 @@ def request(
405403
request.headers["x-ratelimit-remaining"]
406404
)
407405
logger.debug(
408-
"rate limit for api_call, %s = %s"
409-
% (api_call, self.rate_limit_remaining[api_call])
406+
"rate limit for api_call, %s = %s",
407+
api_call,
408+
self.rate_limit_remaining[api_call],
410409
)
411410
if self.rate_limit_remaining[api_call] > rate_warn_threshold:
412411
logger.debug(
413-
"rate limit for api_call, %s = %s"
414-
% (api_call, self.rate_limit_remaining[api_call])
412+
"rate limit for api_call, %s = %s",
413+
api_call,
414+
self.rate_limit_remaining[api_call],
415415
)
416416
elif (self.rate_limit_remaining[api_call] <= rate_warn_threshold) and (
417417
self.rate_limit_remaining[api_call] > 0
418418
):
419419
logger.warning(
420-
"Rate limit is about to being reached (remaining api calls = %s)"
421-
% self.rate_limit_remaining[api_call]
420+
"Rate limit is about to being reached (remaining api calls = %s)",
421+
self.rate_limit_remaining[api_call],
422422
)
423423
elif self.rate_limit_remaining[api_call] <= 0:
424424
logger.critical(
425-
"ATTENTION! RATE LIMIT HAS BEEN REACHED (remaining api calls = %s)!"
426-
% self.rate_limit_remaining[api_call]
425+
"ATTENTION! RATE LIMIT HAS BEEN REACHED (remaining api calls = %s)!",
426+
self.rate_limit_remaining[api_call],
427427
)
428428
except KeyError as e:
429429
# Likely a bad api_call.
@@ -435,7 +435,7 @@ def request(
435435
pass
436436
# Response received.
437437
response = request.text
438-
logger.debug("response text =\n%s" % (response))
438+
logger.debug("response text =\n%s", response)
439439
# Keep track of how many retries.
440440
retries += 1
441441
# Check for concurrent scans limit.
@@ -454,11 +454,11 @@ def request(
454454
# If trying again, delay next try by concurrent_scans_retry_delay.
455455
if retries <= concurrent_scans_retries:
456456
logger.warning(
457-
"Waiting %d seconds until next try." % concurrent_scans_retry_delay
457+
"Waiting %d seconds until next try.", concurrent_scans_retry_delay
458458
)
459459
time.sleep(concurrent_scans_retry_delay)
460460
# Inform user of how many retries.
461-
logger.critical("Retry #%d" % retries)
461+
logger.critical("Retry #%d", retries)
462462
else:
463463
# Ran out of retries. Let user know.
464464
print("Alert! Ran out of concurrent_scans_retries!")
@@ -471,17 +471,17 @@ def request(
471471
# Error
472472
print("Error! Received a 4XX client error or 5XX server error response.")
473473
print("Content = \n", response)
474-
logger.error("Content = \n%s" % response)
474+
logger.error("Content = \n%s", response)
475475
print("Headers = \n", request.headers)
476-
logger.error("Headers = \n%s" % str(request.headers))
476+
logger.error("Headers = \n%s", str(request.headers))
477477
request.raise_for_status()
478478
if '<RETURN status="FAILED" number="2007">' in response:
479479
print(
480480
"Error! Your IP address is not in the list of secure IPs. Manager must include this IP (QualysGuard VM > Users > Security)."
481481
)
482482
print("Content = \n", response)
483-
logger.error("Content = \n%s" % response)
483+
logger.error("Content = \n%s", response)
484484
print("Headers = \n", request.headers)
485-
logger.error("Headers = \n%s" % str(request.headers))
485+
logger.error("Headers = \n%s", str(request.headers))
486486
return False
487487
return response

setup.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99
SETUPTOOLS_VER = "30.5.0" # Minimum version that supports pyproject.toml
1010

1111
try:
12-
require("setuptools>=" + SETUPTOOLS_VER)
12+
require(f"setuptools>={SETUPTOOLS_VER}")
1313
except VersionConflict:
14-
sys.exit("Error: version of setuptools is too old (<{})!".format(SETUPTOOLS_VER))
14+
sys.exit(f"Error: version of setuptools is too old (<{SETUPTOOLS_VER})!")
1515

1616
__author__ = "Parag Baxi <[email protected]>"
1717
__copyright__ = "Copyright 2011-2018, Parag Baxi"

0 commit comments

Comments
 (0)