Fixed UP032 (f-string): Use f-string instead of `format` call

This commit is contained in:
Teal Dulcet 2023-12-22 07:14:00 -08:00 committed by Joshua Tauberer
parent b7f70b17ac
commit 2b426851f9
7 changed files with 24 additions and 30 deletions

View File

@ -482,16 +482,16 @@ def list_target_files(config):
if 'Permission denied (publickey).' in listing:
reason = "Invalid user or check you correctly copied the SSH key."
elif 'No such file or directory' in listing:
reason = "Provided path {} is invalid.".format(target_path)
reason = f"Provided path {target_path} is invalid."
elif 'Network is unreachable' in listing:
reason = "The IP address {} is unreachable.".format(target.hostname)
reason = f"The IP address {target.hostname} is unreachable."
elif 'Could not resolve hostname' in listing:
reason = "The hostname {} cannot be resolved.".format(target.hostname)
reason = f"The hostname {target.hostname} cannot be resolved."
else:
reason = "Unknown error." \
"Please check running 'management/backup.py --verify'" \
"from mailinabox sources to debug the issue."
raise ValueError("Connection to rsync host failed: {}".format(reason))
raise ValueError(f"Connection to rsync host failed: {reason}")
elif target.scheme == "s3":
import boto3.s3
@ -625,7 +625,7 @@ if __name__ == "__main__":
elif sys.argv[-1] == "--list":
# List the saved backup files.
for fn, size in list_target_files(get_backup_config(load_environment())):
print("{}\t{}".format(fn, size))
print(f"{fn}\t{size}")
elif sys.argv[-1] == "--status":
# Show backup status.

View File

@ -80,7 +80,7 @@ def authorized_personnel_only(viewfunc):
# Not authorized. Return a 401 (send auth) and a prompt to authorize by default.
status = 401
headers = {
'WWW-Authenticate': 'Basic realm="{0}"'.format(auth_service.auth_realm),
'WWW-Authenticate': f'Basic realm="{auth_service.auth_realm}"',
'X-Reason': error,
}
@ -164,7 +164,7 @@ def login():
"api_key": auth_service.create_session_key(email, env, type='login'),
}
app.logger.info("New login session created for {}".format(email))
app.logger.info(f"New login session created for {email}")
# Return.
return json_response(resp)
@ -173,7 +173,7 @@ def login():
def logout():
try:
email, _ = auth_service.authenticate(request, env, logout=True)
app.logger.info("{} logged out".format(email))
app.logger.info(f"{email} logged out")
except ValueError as e:
pass
finally:

View File

@ -534,7 +534,7 @@ $TTL 86400 ; default time to live
zone += value + "\n"
# Append a stable hash of DNSSEC signing keys in a comment.
zone += "\n; DNSSEC signing keys hash: {}\n".format(hash_dnssec_keys(domain, env))
zone += f"\n; DNSSEC signing keys hash: {hash_dnssec_keys(domain, env)}\n"
# DNSSEC requires re-signing a zone periodically. That requires
# bumping the serial number even if no other records have changed.
@ -780,7 +780,7 @@ def write_opendkim_tables(domains, env):
# So we must have a separate KeyTable entry for each domain.
"SigningTable":
"".join(
"*@{domain} {domain}\n".format(domain=domain)
f"*@{domain} {domain}\n"
for domain in domains
),
@ -789,7 +789,7 @@ def write_opendkim_tables(domains, env):
# signing domain must match the sender's From: domain.
"KeyTable":
"".join(
"{domain} {domain}:mail:{key_file}\n".format(domain=domain, key_file=opendkim_key_file)
f"{domain} {domain}:mail:{opendkim_key_file}\n"
for domain in domains
),
}

View File

@ -41,7 +41,7 @@ msg['From'] = "\"%s\" <%s>" % (env['PRIMARY_HOSTNAME'], admin_addr)
msg['To'] = admin_addr
msg['Subject'] = "[%s] %s" % (env['PRIMARY_HOSTNAME'], subject)
content_html = '<html><body><pre style="overflow-x: scroll; white-space: pre;">{}</pre></body></html>'.format(html.escape(content))
content_html = f'<html><body><pre style="overflow-x: scroll; white-space: pre;">{html.escape(content)}</pre></body></html>'
msg.attach(MIMEText(content, 'plain'))
msg.attach(MIMEText(content_html, 'html'))

View File

@ -120,8 +120,7 @@ def scan_mail_log(env):
except ImportError:
pass
print("Scanning logs from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}".format(
START_DATE, END_DATE)
print(f"Scanning logs from {START_DATE:%Y-%m-%d %H:%M:%S} to {END_DATE:%Y-%m-%d %H:%M:%S}"
)
# Scan the lines in the log files until the date goes out of range
@ -227,7 +226,7 @@ def scan_mail_log(env):
],
sub_data=[
("Protocol and Source", [[
"{} {}: {} times".format(protocol_name, host, count)
f"{protocol_name} {host}: {count} times"
for (protocol_name, host), count
in sorted(u["totals_by_protocol_and_host"].items(), key=lambda kv:-kv[1])
] for u in data.values()])
@ -672,7 +671,7 @@ def print_user_table(users, data=None, sub_data=None, activity=None, latest=None
col_str = str_temp.format(d[row][:31] + "" if len(d[row]) > 32 else d[row])
col_left[col] = True
elif isinstance(d[row], datetime.datetime):
col_str = "{:<20}".format(str(d[row]))
col_str = f"{str(d[row]):<20}"
col_left[col] = True
else:
temp = "{:>%s}" % max(5, len(l) + 1, len(str(d[row])) + 1)
@ -844,7 +843,7 @@ if __name__ == "__main__":
END_DATE = args.enddate
if args.timespan == 'today':
args.timespan = 'day'
print("Setting end date to {}".format(END_DATE))
print(f"Setting end date to {END_DATE}")
START_DATE = END_DATE - TIME_DELTAS[args.timespan]

View File

@ -268,8 +268,7 @@ def check_free_disk_space(rounded_values, env, output):
except:
backup_cache_count = 0
if backup_cache_count > 1:
output.print_warning("The backup cache directory {} has more than one backup target cache. Consider clearing this directory to save disk space."
.format(backup_cache_path))
output.print_warning(f"The backup cache directory {backup_cache_path} has more than one backup target cache. Consider clearing this directory to save disk space.")
def check_free_memory(rounded_values, env, output):
# Check free memory.
@ -731,9 +730,9 @@ def check_mail_domain(domain, env, output):
if policy[1].get("mx") == [env['PRIMARY_HOSTNAME']] and policy[1].get("mode") == "enforce": # policy[0] is the policyid
output.print_ok("MTA-STS policy is present.")
else:
output.print_error("MTA-STS policy is present but has unexpected settings. [{}]".format(policy[1]))
output.print_error(f"MTA-STS policy is present but has unexpected settings. [{policy[1]}]")
else:
output.print_error("MTA-STS policy is missing: {}".format(valid))
output.print_error(f"MTA-STS policy is missing: {valid}")
else:
output.print_error("""This domain's DNS MX record is incorrect. It is currently set to '%s' but should be '%s'. Mail will not
@ -752,9 +751,9 @@ def check_mail_domain(domain, env, output):
if dbl is None:
output.print_ok("Domain is not blacklisted by dbl.spamhaus.org.")
elif dbl == "[timeout]":
output.print_warning("Connection to dbl.spamhaus.org timed out. We could not determine whether the domain {} is blacklisted. Please try again later.".format(domain))
output.print_warning(f"Connection to dbl.spamhaus.org timed out. We could not determine whether the domain {domain} is blacklisted. Please try again later.")
elif dbl == "[Not Set]":
output.print_warning("Could not connect to dbl.spamhaus.org. We could not determine whether the domain {} is blacklisted. Please try again later.".format(domain))
output.print_warning(f"Could not connect to dbl.spamhaus.org. We could not determine whether the domain {domain} is blacklisted. Please try again later.")
else:
output.print_error("""This domain is listed in the Spamhaus Domain Block List (code %s),
which may prevent recipients from receiving your mail.

View File

@ -30,15 +30,11 @@ print("IMAP login is OK.")
# Attempt to send a mail to ourself.
mailsubject = "Mail-in-a-Box Automated Test Message " + uuid.uuid4().hex
emailto = emailaddress
msg = """From: {emailaddress}
msg = f"""From: {emailaddress}
To: {emailto}
Subject: {subject}
Subject: {mailsubject}
This is a test message. It should be automatically deleted by the test script.""".format(
emailaddress=emailaddress,
emailto=emailto,
subject=mailsubject,
)
This is a test message. It should be automatically deleted by the test script."""
# Connect to the server on the SMTP submission TLS port.
server = smtplib.SMTP_SSL(host)