Skip to content

Commit

Permalink
Use f-Strings instead of formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
ygalblum committed Sep 22, 2021
1 parent 243346b commit 8e506a9
Show file tree
Hide file tree
Showing 45 changed files with 108 additions and 113 deletions.
2 changes: 1 addition & 1 deletion cterasdk/common/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def find_attr(obj, path):
for part in parts:
attr = get_attr(attr, part)
if attr is None:
logging.getLogger().warning('Could not find attribute. %s', {'path': '/{}'.format('/'.join(parts))})
logging.getLogger().warning('Could not find attribute. %s', {'path': f'/{"/".join(parts)}'})
return attr
return attr

Expand Down
2 changes: 1 addition & 1 deletion cterasdk/common/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ def build(self):
"""
errors = [k for k, v in self.param.__dict__.items() if v is None]
if errors:
raise ValueError('No value for required field: %s' % errors)
raise ValueError(f'No value for required field: {errors}')
return self.param


Expand Down
8 changes: 4 additions & 4 deletions cterasdk/common/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ def convert_size(numeric, u1, u2):
"""
data_units = [DataUnit.B, DataUnit.KB, DataUnit.MB, DataUnit.GB, DataUnit.TB, DataUnit.PB]
if u1 not in data_units:
raise ValueError("Invalid current unit type %s" % u1)
raise ValueError(f"Invalid current unit type {u1}")
if u2 not in data_units:
raise ValueError("Invalid target unit type %s" % u2)
raise ValueError(f"Invalid target unit type {u2}")
offset = (data_units.index(u1) - data_units.index(u2)) * 10
if offset > 0:
return numeric * (1 << offset)
Expand All @@ -77,7 +77,7 @@ def df_military_time(time):
:rtype: str
"""
if not isinstance(time, datetime):
raise ValueError("Invalid type '%s', expected 'datetime'" % type(time))
raise ValueError(f"Invalid type '{type(time)}', expected 'datetime'")
return time.strftime('%H:%M:%S')


Expand All @@ -91,7 +91,7 @@ def day_of_week(day):
"""
name = {v: k for k, v in DayOfWeek.__dict__.items() if isinstance(v, int)}.get(day)
if not name:
raise ValueError('Invalid day of week: %s' % day)
raise ValueError(f'Invalid day of week: {day}')
return name


Expand Down
8 changes: 4 additions & 4 deletions cterasdk/core/antivirus.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def get(self, name):
:param str name: Server name
"""
return self._portal.get('/antiviruses/%s' % name)
return self._portal.get(f'/antiviruses/{name}')

def add(self, name, vendor, url, connection_timeout=5):
"""
Expand All @@ -96,20 +96,20 @@ def delete(self, name):
"""
Remove an antivirus server
"""
return self._portal.delete('/antiviruses/%s' % name)
return self._portal.delete(f'/antiviruses/{name}')

def suspend(self, name):
"""
Suspend an antivirus server
"""
logging.getLogger().info("Suspending antivirus server. %s", {'name': name})
self._portal.put('/antiviruses/%s/enabled' % name, False)
self._portal.put(f'/antiviruses/{name}/enabled', False)
logging.getLogger().info("Suspended antivirus server. %s", {'name': name})

def unsuspend(self, name):
"""
Unsuspend antivirus scanning
"""
logging.getLogger().info("Unsuspending antivirus server. %s", {'name': name})
self._portal.put('/antiviruses/%s/enabled' % name, True)
self._portal.put(f'/antiviruses/{name}/enabled', True)
logging.getLogger().info("Unsuspended antivirus server. %s", {'name': name})
10 changes: 5 additions & 5 deletions cterasdk/core/buckets.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Buckets(BaseCommand):

def _get_entire_object(self, name):
try:
return self._portal.get('/locations/%s' % name)
return self._portal.get(f'/locations/{name}')
except CTERAException as error:
raise CTERAException('Failed to get bucket', error)

Expand All @@ -33,7 +33,7 @@ def get(self, name, include=None):
include = ['/' + attr for attr in include]
bucket = self._portal.get_multi('/locations/' + name, include)
if bucket.name is None:
raise ObjectNotFoundException('Could not find bucket', '/locations/%s' % name, name=name)
raise ObjectNotFoundException('Could not find bucket', f'/locations/{name}', name=name)
return bucket

def add(self, name, bucket, read_only=False, dedicated_to=None):
Expand Down Expand Up @@ -82,7 +82,7 @@ def modify(self, current_name, new_name=None, read_only=None, dedicated_to=None)
param.dedicated = True
param.dedicatedPortal = self._get_tenant_base_object_ref(dedicated_to) if dedicated_to else None
logging.getLogger().info("Modifying bucket. %s", {'name': current_name})
response = self._portal.put('/locations/%s' % current_name, param)
response = self._portal.put(f'/locations/{current_name}', param)
logging.getLogger().info("Bucket modified. %s", {'name': current_name})
return response

Expand All @@ -104,7 +104,7 @@ def delete(self, name):
:param str name: Name of the bucket
"""
logging.getLogger().info('Deleting bucket. %s', {'name': name})
response = self._portal.delete('/locations/%s' % name)
response = self._portal.delete(f'/locations/{name}')
logging.getLogger().info('Bucket deleted. %s', {'name': name})
return response

Expand All @@ -127,4 +127,4 @@ def read_only(self, name):
return self._read_only(name, True)

def _read_only(self, name, enabled):
return self._portal.put('/locations/%s/readOnly' % name, enabled)
return self._portal.put(f'/locations/{name}/readOnly', enabled)
2 changes: 1 addition & 1 deletion cterasdk/core/cloudfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def get(self, name, include=None):
include = ['/' + attr for attr in include]
folder_group = self._portal.get_multi('/foldersGroups/' + name, include)
if folder_group.name is None:
raise ObjectNotFoundException('Could not find folder group', '/foldersGroups/%s' % name, name=name)
raise ObjectNotFoundException('Could not find folder group', f'/foldersGroups/{name}', name=name)
return folder_group

def list_folder_groups(self, include=None, user=None):
Expand Down
2 changes: 1 addition & 1 deletion cterasdk/core/devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def device(self, device_name, tenant=None, include=None):
if session.is_local_auth():
url = '/devices/' + device_name # local auth: auto appends /portals/{tenant_name}
else:
url = '/portals/%s/devices/%s' % (tenant, device_name) # regular auth: support both tenant and Administration context
url = f'/portals/{tenant}/devices/{device_name}' # regular auth: support both tenant and Administration context

dev = self._portal.get_multi(url, include)
if dev.name is None:
Expand Down
4 changes: 2 additions & 2 deletions cterasdk/core/files/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,8 +237,8 @@ def device_config(self, device, destination=None):
File destination, if it is a directory, the original filename will be kept, defaults to the default directory
"""
try:
destination = destination if destination is not None else '{}/{}.xml'.format(config.filesystem['dl'], device)
return self.download('{}/Device Configuration/db.xml'.format(device), destination)
destination = destination if destination is not None else f'{config.filesystem["dl"]}/{device}.xml'
return self.download(f'{device}/Device Configuration/db.xml', destination)
except CTERAException as error:
logging.getLogger().error('Failed downloading configuration file. %s', {'device': device, 'error': error.response.reason})
raise error
4 changes: 2 additions & 2 deletions cterasdk/core/files/file_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def _get_single_file_url(self, path):

def _get_multi_file_url(self, cloud_directory, files):
folder_uid = self._get_cloud_folder_uid(cloud_directory)
return '%s/folders/folders/%s' % (self._ctera_host.context, folder_uid)
return f'{self._ctera_host.context}/folders/folders/{folder_uid}'

@property
def _use_file_url_for_multi_file_url(self):
Expand All @@ -31,7 +31,7 @@ def _get_multi_file_object(self, cloud_directory, files):

def _get_upload_url(self, dest_path):
folder_uid = self._get_cloud_folder_uid(dest_path)
return '%s/upload/folders/%s' % (self._ctera_host.context, folder_uid)
return f'{self._ctera_host.context}/upload/folders/{folder_uid}'

def _get_upload_form(self, local_file_info, fd, dest_path):
return dict(
Expand Down
2 changes: 1 addition & 1 deletion cterasdk/core/plans.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def get(self, name, include=None):
include = ['/' + attr for attr in include]
plan = self._portal.get_multi('/plans/' + name, include)
if plan.name is None:
raise ObjectNotFoundException('Could not find subscription plan', '/plans/%s' % name, name=name)
raise ObjectNotFoundException('Could not find subscription plan', f'/plans/{name}', name=name)
return plan

def add(self, name, retention=None, quotas=None):
Expand Down
2 changes: 1 addition & 1 deletion cterasdk/core/portals.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def get(self, name, include=None):
include = ['/' + attr for attr in include]
tenant = self._portal.get_multi('/portals/' + name, include)
if tenant.name is None:
raise ObjectNotFoundException('Could not find tenant', '/portals/%s' % name, name=name)
raise ObjectNotFoundException('Could not find tenant', f'/portals/{name}', name=name)
return tenant

def list_tenants(self, include=None, portal_type=None):
Expand Down
2 changes: 1 addition & 1 deletion cterasdk/core/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,4 @@ def folder_groups(self):
return self._get_report('folderGroupsStatisticsReport')

def _get_report(self, report_name):
return self._portal.get('/reports/%s' % report_name)
return self._portal.get(f'/reports/{report_name}')
8 changes: 4 additions & 4 deletions cterasdk/core/servers.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Servers(BaseCommand):

def _get_entire_object(self, server):
try:
return self._portal.get('/servers/%s' % server)
return self._portal.get(f'/servers/{server}')
except CTERAException as error:
raise CTERAException('Failed to retreive server', error)

Expand All @@ -29,9 +29,9 @@ def get(self, name, include=None):
"""
include = union(include or [], Servers.default)
include = ['/' + attr for attr in include]
server = self._portal.get_multi('/servers/%s' % name, include)
server = self._portal.get_multi(f'/servers/{name}', include)
if server.name is None:
raise ObjectNotFoundException('Could not find server', '/servers/%s' % name, name=name)
raise ObjectNotFoundException('Could not find server', f'/servers/{name}', name=name)
return server

def list_servers(self, include=None):
Expand Down Expand Up @@ -83,7 +83,7 @@ def modify(self, name, server_name=None, app=None, preview=None, enable_public_i
server.allowUserLogin = allow_user_login

try:
response = self._portal.put('/servers/%s' % name, server)
response = self._portal.put(f'/servers/{name}', server)
logging.getLogger().info("Server modified. %s", {'server': name})
return response
except CTERAException as error:
Expand Down
12 changes: 6 additions & 6 deletions cterasdk/core/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def init_master(self, name, email, first_name, last_name, password, domain):
params.settings = Setup.default_settings()
params.settings.dnsSuffix = domain
logging.getLogger().info('Initializing Portal. %s', {'domain': domain, 'user': name})
self._portal.execute('/%s/public' % (self._portal.context), 'init', params, use_file_url=True)
self._portal.execute(f'/{self._portal.context}/public', 'init', params, use_file_url=True)
SetupWizardStatusMonitor(self._portal).wait(SetupWizardStage.Portal)
logging.getLogger().info('Portal initialized.')
elif self.stage == SetupWizardStage.Finish:
Expand All @@ -64,7 +64,7 @@ def init_master(self, name, email, first_name, last_name, password, domain):
def _init_slave(self, ipaddr, secret):
self._get_current_stage()

response = self._portal.execute('/%s/setup/authenticaionMethod' % (self._portal.context),
response = self._portal.execute(f'/{self._portal.context}/setup/authenticaionMethod',
'askMasterForSlaveAuthenticaionMethod', ipaddr, use_file_url=True)

params = Setup._init_server_params(ServerMode.Slave)
Expand All @@ -80,7 +80,7 @@ def _init_slave(self, ipaddr, secret):

def _init_server(self, params, wait=False):
if self.stage == SetupWizardStage.Server:
ref = '/%s/setup' % (self._portal.context)
ref = f'/{self._portal.context}/setup'
form_data = {'inputXml': toxmlstr(params).decode('utf-8'), 'serverMode': params.serverMode}

if params.serverMode == ServerMode.Slave:
Expand Down Expand Up @@ -143,13 +143,13 @@ def init_replication_server(self, ipaddr, secret, replicate_from=None):
self._portal.startup.wait()

def _init_role(self, params):
response = self._portal.execute('/%s/public/servers' % (self._portal.context), 'setReplication', params, use_file_url=True)
response = self._portal.execute(f'/{self._portal.context}/public/servers', 'setReplication', params, use_file_url=True)
status = SetupWizardStatusMonitor(self._portal).wait(SetupWizardStage.Replication)
self.stage = status.wizard
return response

def get_replication_candidates(self):
return self._portal.execute('/%s/public/servers' % (self._portal.context), 'getReplicaitonCandidates', None, use_file_url=True)
return self._portal.execute(f'/{self._portal.context}/public/servers', 'getReplicaitonCandidates', None, use_file_url=True)

@staticmethod
def _init_replication_param(replicate_from=None):
Expand All @@ -173,7 +173,7 @@ def _init_server_params(mode):
return params

def get_setup_status(self):
return self._portal.get('/%s/setup/status' % (self._portal.context), use_file_url=True)
return self._portal.get(f'/{self._portal.context}/setup/status', use_file_url=True)

@staticmethod
def default_settings():
Expand Down
4 changes: 2 additions & 2 deletions cterasdk/core/ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,11 @@ def create_zip_archive(self, private_key, *certificates):

certificate_chain_zip_archive = None
if certificate_chain:
certificate_chain_zip_archive = FileSystem.join(tempdir, '{}.zip'.format(cert_basename))
certificate_chain_zip_archive = FileSystem.join(tempdir, f'{cert_basename}.zip')
with ZipFile(certificate_chain_zip_archive, 'w') as zip_archive:
zip_archive.write(key_filepath, key_basename)
for idx, certificate in enumerate(certificate_chain):
filename = '{}{}.crt'.format(cert_basename, idx if idx > 0 else '')
filename = f'{cert_basename}{idx if idx > 0 else ""}.crt'
filepath = FileSystem.join(tempdir, filename)
self._filesystem.write(filepath, certificate.pem_data)
zip_archive.write(filepath, filename)
Expand Down
2 changes: 1 addition & 1 deletion cterasdk/core/startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def status(self):
"""
response = None
try:
response = self._portal.get('/%s/startup' % (self._portal.context), use_file_url=True)
response = self._portal.get(f'/{self._portal.context}/startup', use_file_url=True)
except CTERAClientException as error:
return error.response.body.status
return response.status
Expand Down
10 changes: 5 additions & 5 deletions cterasdk/core/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __init__(self, portal):

def _get_entire_object(self, name):
try:
return self._portal.get('/deviceTemplates/%s' % name)
return self._portal.get(f'/deviceTemplates/{name}')
except CTERAException as error:
raise CTERAException('Failed to get template', error)

Expand All @@ -35,7 +35,7 @@ def get(self, name, include=None):
include = ['/' + attr for attr in include]
template = self._portal.get_multi('/deviceTemplates/' + name, include)
if template.name is None:
raise ObjectNotFoundException('Could not find server', '/deviceTemplates/%s' % name, name=name)
raise ObjectNotFoundException('Could not find server', f'/deviceTemplates/{name}', name=name)
return template

def add(self, name, description=None, include_sets=None, exclude_sets=None,
Expand Down Expand Up @@ -132,7 +132,7 @@ def _convert_to_template_firmwares(self, versions):

template_firmwares = []
for platform, version in versions:
base_object_ref = firmwares.get('%s-%s' % (platform, version))
base_object_ref = firmwares.get(f'{platform}-{version}')
if base_object_ref is None:
raise CTERAException('Could not find firmware version', None, platform=platform, version=version)
template_firmwares.append(Templates._create_template_firmware(platform, str(base_object_ref)))
Expand Down Expand Up @@ -185,7 +185,7 @@ def delete(self, name):
:param str name: Name of the template
"""
logging.getLogger().info('Deleting template. %s', {'name': name})
response = self._portal.delete('/deviceTemplates/%s' % name)
response = self._portal.delete(f'/deviceTemplates/{name}')
logging.getLogger().info('Template deleted. %s', {'name': name})
return response

Expand All @@ -197,7 +197,7 @@ def set_default(self, name, wait=False):
:param bool,optional wait: Wait for all changes to apply, defaults to `False`
"""
logging.getLogger().info('Setting default template. %s', {'name': name})
response = self._portal.execute('/deviceTemplates/%s' % name, 'setAsDefault')
response = self._portal.execute(f'/deviceTemplates/{name}', 'setAsDefault')
self.auto_assign.apply_changes(wait=wait)
logging.getLogger().info('Set default template. %s', {'name': name})
return response
Expand Down
10 changes: 5 additions & 5 deletions cterasdk/core/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ class Users(BaseCommand):
default = ['name']

def _get_entire_object(self, user_account):
ref = '/users/%s' % user_account.name if user_account.is_local \
else '/domains/%s/adUsers/%s' % (user_account.directory, user_account.name)
ref = f'/users/{user_account.name}' if user_account.is_local \
else f'/domains/{user_account.directory}/adUsers/{user_account.name}'
try:
return self._portal.get(ref)
except CTERAException as error:
Expand All @@ -31,8 +31,8 @@ def get(self, user_account, include=None):
:param list[str] include: List of fields to retrieve, defaults to ['name']
:return: The user account, including the requested fields
"""
baseurl = '/users/%s' % user_account.name if user_account.is_local \
else '/domains/%s/adUsers/%s' % (user_account.directory, user_account.name)
baseurl = f'/users/{user_account.name}' if user_account.is_local \
else f'/domains/{user_account.directory}/adUsers/{user_account.name}'
include = union(include or [], Users.default)
include = ['/' + attr for attr in include]
user_object = self._portal.get_multi(baseurl, include)
Expand Down Expand Up @@ -171,7 +171,7 @@ def delete(self, user):
:param cterasdk.core.types.UserAccount user: the user account
"""
logging.getLogger().info('Deleting user. %s', {'user': str(user)})
baseurl = '/users/%s' % user.name if user.is_local else '/domains/%s/adUsers/%s' % (user.directory, user.name)
baseurl = f'/users/{user.name}' if user.is_local else f'/domains/{user.directory}/adUsers/{user.name}'
response = self._portal.execute(baseurl, 'delete', True)
logging.getLogger().info('User deleted. %s', {'user': str(user)})

Expand Down
2 changes: 1 addition & 1 deletion cterasdk/edge/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,4 +257,4 @@ def _fetch_backup_config(self, name=None):
return backup_configs

def _update_backup_config(self, backup_config):
return self._gateway.put('/config/backup/backupPolicy/includeSets/%s' % backup_config._uuid, backup_config) # pylint: disable=W0212
return self._gateway.put(f'/config/backup/backupPolicy/includeSets/{backup_config._uuid}', backup_config) # pylint: disable=W0212
2 changes: 1 addition & 1 deletion cterasdk/edge/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def import_config(self, config, exclude=None):
if exclude:
delete_attrs(database, exclude)

path = self._filesystem.join(TempfileServices.mkdir(), '{}.xml'.format(self._gateway.session().host))
path = self._filesystem.join(TempfileServices.mkdir(), f'{self._gateway.session().host}.xml')
self._filesystem.write(path, toxmlstr(database, True).encode('utf-8'))

return self._import_configuration(path)
Expand Down

0 comments on commit 8e506a9

Please sign in to comment.