mirror of
https://github.com/mail-in-a-box/mailinabox.git
synced 2024-11-24 02:37:05 +00:00
Fixed UP032 (f-string): Use f-string instead of format
call
This commit is contained in:
parent
b7f70b17ac
commit
2b426851f9
@ -482,16 +482,16 @@ def list_target_files(config):
|
|||||||
if 'Permission denied (publickey).' in listing:
|
if 'Permission denied (publickey).' in listing:
|
||||||
reason = "Invalid user or check you correctly copied the SSH key."
|
reason = "Invalid user or check you correctly copied the SSH key."
|
||||||
elif 'No such file or directory' in listing:
|
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:
|
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:
|
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:
|
else:
|
||||||
reason = "Unknown error." \
|
reason = "Unknown error." \
|
||||||
"Please check running 'management/backup.py --verify'" \
|
"Please check running 'management/backup.py --verify'" \
|
||||||
"from mailinabox sources to debug the issue."
|
"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":
|
elif target.scheme == "s3":
|
||||||
import boto3.s3
|
import boto3.s3
|
||||||
@ -625,7 +625,7 @@ if __name__ == "__main__":
|
|||||||
elif sys.argv[-1] == "--list":
|
elif sys.argv[-1] == "--list":
|
||||||
# List the saved backup files.
|
# List the saved backup files.
|
||||||
for fn, size in list_target_files(get_backup_config(load_environment())):
|
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":
|
elif sys.argv[-1] == "--status":
|
||||||
# Show backup status.
|
# Show backup status.
|
||||||
|
@ -80,7 +80,7 @@ def authorized_personnel_only(viewfunc):
|
|||||||
# Not authorized. Return a 401 (send auth) and a prompt to authorize by default.
|
# Not authorized. Return a 401 (send auth) and a prompt to authorize by default.
|
||||||
status = 401
|
status = 401
|
||||||
headers = {
|
headers = {
|
||||||
'WWW-Authenticate': 'Basic realm="{0}"'.format(auth_service.auth_realm),
|
'WWW-Authenticate': f'Basic realm="{auth_service.auth_realm}"',
|
||||||
'X-Reason': error,
|
'X-Reason': error,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -164,7 +164,7 @@ def login():
|
|||||||
"api_key": auth_service.create_session_key(email, env, type='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.
|
||||||
return json_response(resp)
|
return json_response(resp)
|
||||||
@ -173,7 +173,7 @@ def login():
|
|||||||
def logout():
|
def logout():
|
||||||
try:
|
try:
|
||||||
email, _ = auth_service.authenticate(request, env, logout=True)
|
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:
|
except ValueError as e:
|
||||||
pass
|
pass
|
||||||
finally:
|
finally:
|
||||||
|
@ -534,7 +534,7 @@ $TTL 86400 ; default time to live
|
|||||||
zone += value + "\n"
|
zone += value + "\n"
|
||||||
|
|
||||||
# Append a stable hash of DNSSEC signing keys in a comment.
|
# 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
|
# DNSSEC requires re-signing a zone periodically. That requires
|
||||||
# bumping the serial number even if no other records have changed.
|
# 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.
|
# So we must have a separate KeyTable entry for each domain.
|
||||||
"SigningTable":
|
"SigningTable":
|
||||||
"".join(
|
"".join(
|
||||||
"*@{domain} {domain}\n".format(domain=domain)
|
f"*@{domain} {domain}\n"
|
||||||
for domain in domains
|
for domain in domains
|
||||||
),
|
),
|
||||||
|
|
||||||
@ -789,7 +789,7 @@ def write_opendkim_tables(domains, env):
|
|||||||
# signing domain must match the sender's From: domain.
|
# signing domain must match the sender's From: domain.
|
||||||
"KeyTable":
|
"KeyTable":
|
||||||
"".join(
|
"".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
|
for domain in domains
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
|
@ -41,7 +41,7 @@ msg['From'] = "\"%s\" <%s>" % (env['PRIMARY_HOSTNAME'], admin_addr)
|
|||||||
msg['To'] = admin_addr
|
msg['To'] = admin_addr
|
||||||
msg['Subject'] = "[%s] %s" % (env['PRIMARY_HOSTNAME'], subject)
|
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, 'plain'))
|
||||||
msg.attach(MIMEText(content_html, 'html'))
|
msg.attach(MIMEText(content_html, 'html'))
|
||||||
|
@ -120,8 +120,7 @@ def scan_mail_log(env):
|
|||||||
except ImportError:
|
except ImportError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
print("Scanning logs from {:%Y-%m-%d %H:%M:%S} to {:%Y-%m-%d %H:%M:%S}".format(
|
print(f"Scanning logs from {START_DATE:%Y-%m-%d %H:%M:%S} to {END_DATE:%Y-%m-%d %H:%M:%S}"
|
||||||
START_DATE, END_DATE)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Scan the lines in the log files until the date goes out of range
|
# 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=[
|
sub_data=[
|
||||||
("Protocol and Source", [[
|
("Protocol and Source", [[
|
||||||
"{} {}: {} times".format(protocol_name, host, count)
|
f"{protocol_name} {host}: {count} times"
|
||||||
for (protocol_name, host), count
|
for (protocol_name, host), count
|
||||||
in sorted(u["totals_by_protocol_and_host"].items(), key=lambda kv:-kv[1])
|
in sorted(u["totals_by_protocol_and_host"].items(), key=lambda kv:-kv[1])
|
||||||
] for u in data.values()])
|
] 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_str = str_temp.format(d[row][:31] + "…" if len(d[row]) > 32 else d[row])
|
||||||
col_left[col] = True
|
col_left[col] = True
|
||||||
elif isinstance(d[row], datetime.datetime):
|
elif isinstance(d[row], datetime.datetime):
|
||||||
col_str = "{:<20}".format(str(d[row]))
|
col_str = f"{str(d[row]):<20}"
|
||||||
col_left[col] = True
|
col_left[col] = True
|
||||||
else:
|
else:
|
||||||
temp = "{:>%s}" % max(5, len(l) + 1, len(str(d[row])) + 1)
|
temp = "{:>%s}" % max(5, len(l) + 1, len(str(d[row])) + 1)
|
||||||
@ -844,7 +843,7 @@ if __name__ == "__main__":
|
|||||||
END_DATE = args.enddate
|
END_DATE = args.enddate
|
||||||
if args.timespan == 'today':
|
if args.timespan == 'today':
|
||||||
args.timespan = 'day'
|
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]
|
START_DATE = END_DATE - TIME_DELTAS[args.timespan]
|
||||||
|
|
||||||
|
@ -268,8 +268,7 @@ def check_free_disk_space(rounded_values, env, output):
|
|||||||
except:
|
except:
|
||||||
backup_cache_count = 0
|
backup_cache_count = 0
|
||||||
if backup_cache_count > 1:
|
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."
|
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.")
|
||||||
.format(backup_cache_path))
|
|
||||||
|
|
||||||
def check_free_memory(rounded_values, env, output):
|
def check_free_memory(rounded_values, env, output):
|
||||||
# Check free memory.
|
# 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
|
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.")
|
output.print_ok("MTA-STS policy is present.")
|
||||||
else:
|
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:
|
else:
|
||||||
output.print_error("MTA-STS policy is missing: {}".format(valid))
|
output.print_error(f"MTA-STS policy is missing: {valid}")
|
||||||
|
|
||||||
else:
|
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
|
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:
|
if dbl is None:
|
||||||
output.print_ok("Domain is not blacklisted by dbl.spamhaus.org.")
|
output.print_ok("Domain is not blacklisted by dbl.spamhaus.org.")
|
||||||
elif dbl == "[timeout]":
|
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]":
|
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:
|
else:
|
||||||
output.print_error("""This domain is listed in the Spamhaus Domain Block List (code %s),
|
output.print_error("""This domain is listed in the Spamhaus Domain Block List (code %s),
|
||||||
which may prevent recipients from receiving your mail.
|
which may prevent recipients from receiving your mail.
|
||||||
|
@ -30,15 +30,11 @@ print("IMAP login is OK.")
|
|||||||
# Attempt to send a mail to ourself.
|
# Attempt to send a mail to ourself.
|
||||||
mailsubject = "Mail-in-a-Box Automated Test Message " + uuid.uuid4().hex
|
mailsubject = "Mail-in-a-Box Automated Test Message " + uuid.uuid4().hex
|
||||||
emailto = emailaddress
|
emailto = emailaddress
|
||||||
msg = """From: {emailaddress}
|
msg = f"""From: {emailaddress}
|
||||||
To: {emailto}
|
To: {emailto}
|
||||||
Subject: {subject}
|
Subject: {mailsubject}
|
||||||
|
|
||||||
This is a test message. It should be automatically deleted by the test script.""".format(
|
This is a test message. It should be automatically deleted by the test script."""
|
||||||
emailaddress=emailaddress,
|
|
||||||
emailto=emailto,
|
|
||||||
subject=mailsubject,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Connect to the server on the SMTP submission TLS port.
|
# Connect to the server on the SMTP submission TLS port.
|
||||||
server = smtplib.SMTP_SSL(host)
|
server = smtplib.SMTP_SSL(host)
|
||||||
|
Loading…
Reference in New Issue
Block a user