Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

F-Strings - hardware / image / lb #1982

Merged
merged 12 commits into from Jun 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion SoftLayer/CLI/hardware/create.py
Expand Up @@ -104,7 +104,7 @@ def cli(env, **args):
if do_create:
for pod in pods:
if args.get('datacenter') in pod['name']:
click.secho('Warning: Closed soon: {}'.format(pod['name']), fg='yellow')
click.secho(f"Warning: Closed soon: {pod['name']}", fg='yellow')
if not (env.skip_confirmations or formatting.confirm(
"This action will incur charges on your account. Continue?")):
raise exceptions.CLIAbort('Aborting dedicated server order.')
Expand Down
4 changes: 2 additions & 2 deletions SoftLayer/CLI/hardware/detail.py
Expand Up @@ -66,8 +66,8 @@ def cli(env, identifier, passwords, price, components):
table.add_row(['created', result['provisionDate'] or formatting.blank()])
table.add_row(['owner', owner or formatting.blank()])

last_transaction = "{} ({})".format(utils.lookup(result, 'lastTransaction', 'transactionGroup', 'name'),
utils.clean_time(utils.lookup(result, 'lastTransaction', 'modifyDate')))
last_transaction = f"{utils.lookup(result, 'lastTransaction', 'transactionGroup', 'name')} \
({utils.clean_time(utils.lookup(result, 'lastTransaction', 'modifyDate'))})"

table.add_row(['last_transaction', last_transaction])
table.add_row(['billing', 'Hourly' if result['hourlyBillingFlag'] else 'Monthly'])
Expand Down
2 changes: 1 addition & 1 deletion SoftLayer/CLI/hardware/dns.py
Expand Up @@ -61,5 +61,5 @@ def cli(env, identifier, a_record, aaaa_record, ptr, ttl):
ipv6 = instance['primaryNetworkComponent']['primaryVersion6IpAddressRecord']['ipAddress']
dns.sync_host_record(zone_id, instance['hostname'], ipv6, 'aaaa', ttl)
except KeyError as ex:
message = "{} does not have an ipv6 address".format(instance['fullyQualifiedDomainName'])
message = f"{instance['fullyQualifiedDomainName']} does not have an ipv6 address"
raise exceptions.CLIAbort(message) from ex
2 changes: 1 addition & 1 deletion SoftLayer/CLI/hardware/notification_add.py
Expand Up @@ -30,5 +30,5 @@ def cli(env, identifier, users):
notification['user']['username'], notification['user']['email'],
notification['user']['firstName'], notification['user']['lastName']])
else:
raise exceptions.CLIAbort("User not found: {}.".format(user))
raise exceptions.CLIAbort(f"User not found: {user}.")
env.fout(table)
2 changes: 1 addition & 1 deletion SoftLayer/CLI/hardware/notification_delete.py
Expand Up @@ -18,4 +18,4 @@ def cli(env, identifier):
result = hardware.remove_notification(identifier)

if result:
env.fout("The hardware notification instance: {} was deleted.".format(identifier))
env.fout(f"The hardware notification instance: {identifier} was deleted.")
2 changes: 1 addition & 1 deletion SoftLayer/CLI/image/share.py
Expand Up @@ -20,4 +20,4 @@ def cli(env, identifier, account_id):
shared_image = image_mgr.share_image(image_id, account_id)

if shared_image:
env.fout("Image template {} was shared to account {}.".format(identifier, account_id))
env.fout(f"Image template {identifier} was shared to account {account_id}.")
2 changes: 1 addition & 1 deletion SoftLayer/CLI/image/share_deny.py
Expand Up @@ -20,4 +20,4 @@ def cli(env, identifier, account_id):
shared_image = image_mgr.deny_share_image(image_id, account_id)

if shared_image:
env.fout("Image template {} was deny shared to account {}.".format(identifier, account_id))
env.fout(f"Image template {identifier} was deny shared to account {account_id}.")
2 changes: 1 addition & 1 deletion SoftLayer/CLI/licenses/cancel.py
Expand Up @@ -19,4 +19,4 @@ def cli(env, key, immediate):
item = licenses.cancel_item(key, immediate)

if item:
env.fout("License key: {} was cancelled.".format(key))
env.fout(f"License key: {key} was cancelled.")
6 changes: 3 additions & 3 deletions SoftLayer/CLI/loadbal/detail.py
Expand Up @@ -34,7 +34,7 @@ def lbaas_table(this_lb):
table.add_row(['Type', SoftLayer.LoadBalancerManager.TYPE.get(this_lb.get('type'))])
table.add_row(['Location', utils.lookup(this_lb, 'datacenter', 'longName')])
table.add_row(['Description', this_lb.get('description')])
table.add_row(['Status', "{} / {}".format(this_lb.get('provisioningStatus'), this_lb.get('operatingStatus'))])
table.add_row(['Status', f"{this_lb.get('provisioningStatus')} / {this_lb.get('operatingStatus')}"])

listener_table, pools = get_listener_table(this_lb)
table.add_row(['Protocols', listener_table])
Expand Down Expand Up @@ -122,9 +122,9 @@ def get_listener_table(this_lb):
listener_table = formatting.Table(['UUID', 'Max Connection', 'Mapping', 'Balancer', 'Modify', 'Active'])
for listener in this_lb.get('listeners', []):
pool = listener.get('defaultPool')
priv_map = "{}:{}".format(pool['protocol'], pool['protocolPort'])
priv_map = f"{pool['protocol']}:{pool['protocolPort']}"
pools[pool['uuid']] = priv_map
mapping = "{}:{} -> {}".format(listener.get('protocol'), listener.get('protocolPort'), priv_map)
mapping = f"{listener.get('protocol')}:{listener.get('protocolPort')} -> {priv_map}"
listener_table.add_row([
listener.get('uuid'),
listener.get('connectionLimit', 'None'),
Expand Down
8 changes: 4 additions & 4 deletions SoftLayer/CLI/loadbal/health.py
Expand Up @@ -31,7 +31,7 @@ def cli(env, identifier, uuid, interval, retry, timeout, url):
mgr = SoftLayer.LoadBalancerManager(env.client)
# Need to get the LBaaS uuid if it wasn't supplied
lb_uuid, lb_id = mgr.get_lbaas_uuid_id(identifier)
print("UUID: {}, ID: {}".format(lb_uuid, lb_id))
print(f"UUID: {lb_uuid}, ID: {lb_id}")

# Get the current health checks, and find the one we are updating.
mask = "mask[healthMonitors, listeners[uuid,defaultPool[healthMonitor]]]"
Expand All @@ -58,7 +58,7 @@ def cli(env, identifier, uuid, interval, retry, timeout, url):

try:
mgr.update_lb_health_monitors(lb_uuid, [check])
click.secho('Health Check {} updated successfully'.format(uuid), fg='green')
click.secho(f'Health Check {uuid} updated successfully', fg='green')
except SoftLayerAPIError as exception:
click.secho('Failed to update {}'.format(uuid), fg='red')
click.secho("ERROR: {}".format(exception.faultString), fg='red')
click.secho(f'Failed to update {uuid}', fg='red')
click.secho(f"ERROR: {exception.faultString}", fg='red')
8 changes: 4 additions & 4 deletions SoftLayer/CLI/loadbal/members.py
Expand Up @@ -23,9 +23,9 @@ def remove(env, identifier, member):

try:
mgr.delete_lb_member(uuid, member)
click.secho("Member {} removed".format(member), fg='green')
click.secho(f"Member {member} removed", fg='green')
except SoftLayerAPIError as exception:
click.secho("ERROR: {}".format(exception.faultString), fg='red')
click.secho(f"ERROR: {exception.faultString}", fg='red')


@click.command(cls=SoftLayer.CLI.command.SLCommand, )
Expand All @@ -48,10 +48,10 @@ def add(env, identifier, private, member, weight):

try:
mgr.add_lb_member(uuid, to_add)
click.secho("Member {} added".format(member), fg='green')
click.secho(f"Member {member} added", fg='green')
except SoftLayerAPIError as exception:
if 'publicIpAddress must be a string' in exception.faultString:
click.secho("This LB requires a Public IP address for its members and none was supplied", fg='red')
elif 'privateIpAddress must be a string' in exception.faultString:
click.secho("This LB requires a Private IP address for its members and none was supplied", fg='red')
click.secho("ERROR: {}".format(exception.faultString), fg='red')
click.secho(f"ERROR: {exception.faultString}", fg='red')
2 changes: 1 addition & 1 deletion SoftLayer/CLI/loadbal/ns_detail.py
Expand Up @@ -36,7 +36,7 @@ def netscaler_table(this_lb):
for subnet in this_lb.get('subnets', []):
subnet_table.add_row([
subnet.get('id'),
"{}/{}".format(subnet.get('networkIdentifier'), subnet.get('cidr')),
f"{subnet.get('networkIdentifier')}/{subnet.get('cidr')}",
subnet.get('subnetType'),
subnet.get('addressSpace')
])
Expand Down
14 changes: 7 additions & 7 deletions SoftLayer/CLI/loadbal/order.py
Expand Up @@ -15,7 +15,7 @@ def parse_proto(ctx, param, value):
proto = {'protocol': 'HTTP', 'port': 80}
splitout = value.split(':')
if len(splitout) != 2:
raise exceptions.ArgumentError("{}={} is not properly formatted.".format(param, value))
raise exceptions.ArgumentError(f"{param}={value} is not properly formatted.")
proto['protocol'] = splitout[0]
proto['port'] = int(splitout[1])
return proto
Expand Down Expand Up @@ -47,7 +47,7 @@ def order(env, **args):
if datacenter:
location = {'id': datacenter[0]['id']}
else:
raise exceptions.CLIHalt('Datacenter {} was not found'.format(datacenter))
raise exceptions.CLIHalt(f'Datacenter {datacenter} was not found')

name = args.get('name')
description = args.get('label', None)
Expand All @@ -74,7 +74,7 @@ def order(env, **args):

def parse_receipt(receipt):
"""Takes an order receipt and nicely formats it for cli output"""
table = formatting.KeyValueTable(['Item', 'Cost'], title="Order: {}".format(receipt.get('orderId', 'Quote')))
table = formatting.KeyValueTable(['Item', 'Cost'], title=f"Order: {receipt.get('orderId', 'Quote')}")
if receipt.get('prices'):
for price in receipt.get('prices'):
table.add_row([price['item']['description'], price['hourlyRecurringFee']])
Expand Down Expand Up @@ -143,8 +143,8 @@ def order_options(env, datacenter):
if subnet.get('subnetType') != 'PRIMARY' and \
subnet.get('subnetType') != 'ADDITIONAL_PRIMARY':
continue
space = "{}/{}".format(subnet.get('networkIdentifier'), subnet.get('cidr'))
vlan = "{}.{}".format(subnet['podName'], subnet['networkVlan']['vlanNumber'])
space = f"{subnet.get('networkIdentifier')}/{subnet.get('cidr')}"
vlan = f"{subnet['podName']}.{subnet['networkVlan']['vlanNumber']}"
subnet_table.add_row([subnet.get('id'), space, vlan])

env.fout(price_table)
Expand All @@ -162,6 +162,6 @@ def cancel(env, identifier):

try:
mgr.cancel_lbaas(uuid)
click.secho("LB {} canceled succesfully.".format(identifier), fg='green')
click.secho(f"LB {identifier} canceled succesfully.", fg='green')
except SoftLayerAPIError as exception:
click.secho("ERROR: {}".format(exception.faultString), fg='red')
click.secho(f"ERROR: {exception.faultString}", fg='red')
12 changes: 6 additions & 6 deletions SoftLayer/CLI/loadbal/pools.py
Expand Up @@ -23,7 +23,7 @@ def parse_server(ctx, param, values):
splitout = server.split(':')
if len(splitout) != 3:
raise exceptions.ArgumentError(
"--server needs a port and a weight. {} improperly formatted".format(server))
f"--server needs a port and a weight. {server} improperly formatted")
server = {
'address': splitout[0],
'port': splitout[1],
Expand Down Expand Up @@ -69,7 +69,7 @@ def add(env, identifier, **args):
mgr.add_lb_listener(uuid, new_listener)
click.secho("Success", fg='green')
except SoftLayerAPIError as exception:
click.secho("ERROR: {}".format(exception.faultString), fg='red')
click.secho(f"ERROR: {exception.faultString}", fg='red')


@click.command(cls=SoftLayer.CLI.command.SLCommand, )
Expand Down Expand Up @@ -122,7 +122,7 @@ def edit(env, identifier, listener, **args):
mgr.add_lb_listener(uuid, new_listener)
click.secho("Success", fg='green')
except SoftLayerAPIError as exception:
click.secho("ERROR: {}".format(exception.faultString), fg='red')
click.secho(f"ERROR: {exception.faultString}", fg='red')


@click.command(cls=SoftLayer.CLI.command.SLCommand, )
Expand All @@ -141,7 +141,7 @@ def delete(env, identifier, listener):
mgr.remove_lb_listener(uuid, listener)
click.secho("Success", fg='green')
except SoftLayerAPIError as exception:
click.secho("ERROR: {}".format(exception.faultString), fg='red')
click.secho(f"ERROR: {exception.faultString}", fg='red')


@click.command(cls=SoftLayer.CLI.command.SLCommand, )
Expand Down Expand Up @@ -197,7 +197,7 @@ def l7pool_add(env, identifier, **args):
mgr.add_lb_l7_pool(uuid, pool_main, pool_members, pool_health, pool_sticky)
click.secho("Success", fg='green')
except SoftLayerAPIError as exception:
click.secho("ERROR: {}".format(exception.faultString), fg='red')
click.secho(f"ERROR: {exception.faultString}", fg='red')


@click.command(cls=SoftLayer.CLI.command.SLCommand, )
Expand All @@ -213,4 +213,4 @@ def l7pool_del(env, identifier):
mgr.del_lb_l7_pool(identifier)
click.secho("Success", fg='green')
except SoftLayerAPIError as exception:
click.secho("ERROR: {}".format(exception.faultString), fg='red')
click.secho(f"ERROR: {exception.faultString}", fg='red')
7 changes: 4 additions & 3 deletions SoftLayer/CLI/metadata.py
Expand Up @@ -28,13 +28,14 @@
'ip': 'primary_ip',
}

HELP = """Find details about the machine making these API calls.
NL = "\n "
HELP = f"""Find details about the machine making these API calls.

.. csv-table:: Choices

{choices}
{NL.join(META_CHOICES)}

""".format(choices="\n ".join(META_CHOICES))
"""


@click.command(cls=SoftLayer.CLI.command.SLCommand, help=HELP,
Expand Down
6 changes: 3 additions & 3 deletions SoftLayer/CLI/order/lookup.py
Expand Up @@ -51,9 +51,9 @@ def get_order_table(order):
table.add_row(['Modify Date', utils.clean_time(order.get('modifyDate'), date_format, date_format)])
table.add_row(['Order Approval Date', utils.clean_time(order.get('orderApprovalDate'), date_format, date_format)])
table.add_row(['Status', order.get('status')])
table.add_row(['Order Total Amount', f'{float(order.get("orderTotalAmount","0")):.2f}'])
table.add_row(['Invoice Total Amount', "{price:.2f}".
format(price=float(order.get('initialInvoice', {}).get('invoiceTotalAmount', '0')))])
table.add_row(['Order Total Amount', f"{float(order.get('orderTotalAmount', '0')):.2f}"])
table.add_row(['Invoice Total Amount',
f"{float(order.get('initialInvoice', {}).get('invoiceTotalAmount', '0')):.2f}"])

items = order.get('items', [])
item_table = formatting.Table(["Item Description"])
Expand Down