Skip to content

Commit

Permalink
feat: replaced format with f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
jLebioda committed Feb 2, 2021
1 parent 167e092 commit a1e433c
Show file tree
Hide file tree
Showing 29 changed files with 67 additions and 65 deletions.
3 changes: 2 additions & 1 deletion core/forms/dataset.py
Expand Up @@ -46,7 +46,8 @@ def clean(self):
if contract.project:
if str(contract.project.id) != proj:
project_inconsistency = True
self.add_error('project', "Dataset has existing link to Project {} via {}. Please remove link before updating this field.".format(contract.project.acronym, obj))
error_msg = f"Dataset has existing link to Project {contract.project.acronym} via {obj}. Please remove link before updating this field."
self.add_error('project', error_msg)
if project_inconsistency:
errors.append("Unable to update project information.")

Expand Down
7 changes: 4 additions & 3 deletions core/importer/datasets_exporter.py
Expand Up @@ -34,7 +34,7 @@ def export_to_file(self, file_handle, stop_on_error=False, verbose=False):
logger.error('Dataset export failed')
logger.error(str(e))
result = False
logger.info('Dataset export complete see file: {}'.format(file_handle))
logger.info(f'Dataset export complete see file: {file_handle}')
return result

def export_to_buffer(self, buffer, stop_on_error=False, verbose=False):
Expand All @@ -44,13 +44,14 @@ def export_to_buffer(self, buffer, stop_on_error=False, verbose=False):
else:
objects = Dataset.objects.all()
for dataset in objects:
logger.debug(' * Exporting dataset: "{}"...'.format(dataset.__str__()))
dataset_repr = str(dataset)
logger.debug(f' * Exporting dataset: "{dataset_repr}"...')
try:
pd = dataset.to_dict()
pd["source"] = settings.SERVER_URL
dataset_dicts.append(pd)
except Exception as e:
logger.error('Export failed for dataset {}'.format(dataset.title))
logger.error(f'Export failed for dataset {dataset.title}')
logger.error(str(e))
if verbose:
import traceback
Expand Down
29 changes: 18 additions & 11 deletions core/importer/datasets_importer.py
Expand Up @@ -32,7 +32,7 @@ def process_json(self, dataset_dict):

if dataset:
title_to_show = title.encode('utf8')
self.logger.warning("Dataset with title '{}' already found. It will be updated.".format(title_to_show))
self.logger.warning(f"Dataset with title '{title_to_show}' already found. It will be updated.")
else:
dataset = Dataset.objects.create(title=title)

Expand Down Expand Up @@ -77,6 +77,8 @@ def process_json(self, dataset_dict):

dataset.save()

return True

# @staticmethod
# def process_local_custodians(dataset_dict):
# result = []
Expand Down Expand Up @@ -108,19 +110,22 @@ def process_json(self, dataset_dict):

def process_project(self, project_acronym):
try:
project = Project.objects.get(acronym=project_acronym.strip())
acronym = project_acronym.strip()
project = Project.objects.get(acronym=acronym)
return project
except Project.DoesNotExist:
self.logger.warning("Tried to find project with acronym ='{}'; it was not found. Will try to look for the acronym...".format(project_acronym))
msg = f"Tried to find project with acronym ='{acronym}'; it was not found. Will try to look for the acronym..."
self.logger.warning(msg)

try:
project = Project.objects.get(title=project_acronym.strip())
project = Project.objects.get(title=acronym)
return project
except Project.DoesNotExist:
self.logger.warning("Tried to find project with title ='{}'; it was not found. Will create a new one.".format(project_acronym.strip()))
msg = f"Tried to find project with title ='{acronym}'; it was not found. Will create a new one."
self.logger.warning(msg)
project = Project.objects.create(
acronym=project_acronym.strip(),
title=project_acronym.strip()
acronym=acronym,
title=acronym
)
return project

Expand Down Expand Up @@ -247,7 +252,8 @@ def process_datadeclaration(self, datadec_dict, dataset):
datadec = None

if datadec:
self.logger.warning("Data declaration with title '{}' already found. It will be updated.".format(title_to_show))
msg = f"Data declaration with title '{title_to_show}' already found. It will be updated."
self.logger.warning(msg)
else:
datadec = DataDeclaration.objects.create(title=title, dataset=dataset)

Expand Down Expand Up @@ -503,7 +509,8 @@ def _process_study(study):
cohort.owners.set(external_contacts)

cohort.save()
self.logger.info("Cohort '{}' imported successfully. Will try to link it to the data declaration...".format(safe_name))
msg = f"Cohort '{safe_name}' imported successfully. Will try to link it to the data declaration..."
self.logger.info(msg)

try:
data_declaration = studies_map.get(name)
Expand All @@ -514,9 +521,9 @@ def _process_study(study):
data_declaration.cohorts.add(cohort)
data_declaration.save()
safe_title = data_declaration.title.encode('utf8')
self.logger.info("Cohort '{}' linked successfully to data declaration '{}'".format(safe_name, safe_title))
self.logger.info(f"Cohort '{safe_name}' linked successfully to data declaration '{safe_title}'")
except:
self.logger.warning("The data declaration for the study '{}' not found: ".format(safe_name))
self.logger.warning(f"The data declaration for the study '{safe_name}' not found. ")

if 'studies' not in dataset_dict:
return
Expand Down
4 changes: 2 additions & 2 deletions core/importer/partners_exporter.py
Expand Up @@ -21,7 +21,7 @@ def export_to_file(self, file_handle, stop_on_error=False, verbose=False):
logger.error(str(e))
result = False

logger.info('Partner export complete see file: {}'.format(file_handle))
logger.info(f'Partner export complete see file: {file_handle}')
return result


Expand All @@ -30,7 +30,7 @@ def export_to_buffer(self, buffer, stop_on_error=False, verbose=False):
partner_dicts = []
partners = Partner.objects.all()
for partner in partners:
logger.debug(' * Exporting partner: "{}"...'.format(partner.name))
logger.debug(f' * Exporting partner: "{partner.name}"...')
try:
pd = partner.to_dict()
pd["source"] = settings.SERVER_URL
Expand Down
7 changes: 3 additions & 4 deletions core/importer/partners_importer.py
Expand Up @@ -10,10 +10,9 @@ class PartnersImporter(BaseImporter):
https://git-r3lab.uni.lu/pinar.alper/metadata-tools/blob/master/metadata_tools/resources/elu-institution.json
Usage example:
def import_partner():
with open("partners.json", "r") as file_with_partners:
importer = PartnersImporter()
importer.import_json(file_with_partners.read())
def import_partners():
importer = PartnersImporter()
importer.import_json_file("partners.json")
"""

json_schema_validator = InstitutionJSONSchemaValidator()
Expand Down
7 changes: 4 additions & 3 deletions core/importer/projects_exporter.py
Expand Up @@ -35,7 +35,7 @@ def export_to_file(self, file_handle, stop_on_error=False, verbose=False):
logger.error('Project export failed')
logger.error(str(e))
result = False
logger.info('Project export complete see file: {}'.format(file_handle))
logger.info(f'Project export complete see file: {file_handle}')
return result


Expand All @@ -48,13 +48,14 @@ def export_to_buffer(self, buffer, stop_on_error=False, verbose=False):
objects = Project.objects.all()

for project in objects:
logger.debug(' * Exporting project: "{}"...'.format(project.acronym))
logger.debug(f' * Exporting project: "{project.acronym}"...')
try:
pd = project.to_dict()
pd["source"] = settings.SERVER_URL
project_dicts.append(pd)
except Exception as e:
logger.error('Export failed for project {}'.format(project.__str__()))
project_repr = str(project)
logger.error(f'Export failed for project f{project_repr}')
logger.error(str(e))
if verbose:
import traceback
Expand Down
13 changes: 7 additions & 6 deletions core/importer/projects_importer.py
Expand Up @@ -11,9 +11,8 @@ class ProjectsImporter(BaseImporter):
Usage example:
def import_projects():
with open("projects.json", "r") as file_with_projects:
importer = ProjectsImporter()
importer.import_json(file_with_projects.read())
importer = ProjectsImporter()
importer.import_json_file("projects.json")
"""

json_schema_validator = ProjectJSONSchemaValidator()
Expand Down Expand Up @@ -49,7 +48,7 @@ def process_json(self, project_dict):
)
else:
acronym_to_show = acronym.encode('utf8')
self.logger.warning("Project with acronym '{}' already found. It will be updated.".format(acronym_to_show))
self.logger.warning(f"Project with acronym '{acronym_to_show}' already found. It will be updated.")
project.title = name
project.description = description
project.has_cner = has_cner
Expand All @@ -63,7 +62,7 @@ def process_json(self, project_dict):
project.start_date = self.process_date(project_dict.get('start_date'))
except self.DateImportException:
message = "\tCouldn't import the 'start_date'. Does it follow the '%Y-%m-%d' format?\n\t"
message = message + 'Was: "{}". '.format(project_dict.get('start_date'))
message = message + f'Was: "{project_dict.get('start_date')}". '
message = message + "Continuing with empty value."
self.logger.warning(message)

Expand All @@ -72,7 +71,7 @@ def process_json(self, project_dict):
project.end_date = self.process_date(project_dict.get('end_date'))
except self.DateImportException:
message = "\tCouldn't import the 'end_date'. Does it follow the '%Y-%m-%d' format?\n\t"
message = message + 'Was: "{}". '.format(project_dict.get('end_date'))
message = message + f'Was: "{project_dict.get('end_date')}". '
message = message + "Continuing with empty value."
self.logger.warning(message)

Expand All @@ -97,6 +96,8 @@ def process_json(self, project_dict):
for local_custodian in local_custodians:
local_custodian.assign_permissions_to_dataset(project)

return True

@staticmethod
def process_publication(publication_dict):
# First, try to find if the publication is already in our database
Expand Down
2 changes: 1 addition & 1 deletion core/management/commands/load_initial_data.py
Expand Up @@ -176,7 +176,7 @@ def create_elu_cohorts():
i = Partner.objects.get(elu_accession=ins)
institutes.append(i)
except Partner.DoesNotExist:
raise FixtureImportError(data="unknown partner institute {}".format(ins))
raise FixtureImportError(data=f"unknown partner institute {ins}")
c.institutes.set(institutes)
if 'owners' in cohort:
owners = []
Expand Down
2 changes: 1 addition & 1 deletion core/models/access.py
Expand Up @@ -48,7 +48,7 @@ class Meta:
)

def __str__(self):
return 'Access given to dataset {}: {}'.format(self.dataset.title, self.access_notes)
return f'Access given to dataset {self.dataset.title}: {self.access_notes}'

@property
def display_locations(self):
Expand Down
4 changes: 2 additions & 2 deletions core/models/contact.py
Expand Up @@ -51,10 +51,10 @@ class AppMeta:


def __str__(self):
return "{} {} ({})".format(self.first_name, self.last_name, self.type.name)
return f"{self.first_name} {self.last_name} ({self.type.name})"

def full_name(self):
return "{} {}".format(self.first_name, self.last_name)
return f"{self.first_name} {self.last_name}"

def to_dict(self):
partners_dict = []
Expand Down
2 changes: 1 addition & 1 deletion core/models/contact_type.py
Expand Up @@ -18,4 +18,4 @@ class Meta:
verbose_name='Name of the contact type', unique=True)

def __str__(self):
return "{}".format(self.name)
return f"{self.name}"
6 changes: 2 additions & 4 deletions core/models/document.py
Expand Up @@ -16,9 +16,7 @@ def get_file_name(instance, filename):
Return the path of the final path of the document on the filsystem.
"""
now = timezone.now().strftime('%Y/%m/%d')
return 'documents/{}/{}/{}_{}'.format(
instance.content_type.name, now, instance.object_id, filename
)
return f'documents/{instance.content_type.name}/{now}/{instance.object_id}_{filename}'


class Document(CoreModel):
Expand Down Expand Up @@ -59,7 +57,7 @@ class Meta:
null=True)

def __str__(self):
return "{} ({})".format(self.content.name, self.content_object)
return f"{self.content.name} ({self.content_object})"

@property
def shortname(self):
Expand Down
2 changes: 1 addition & 1 deletion core/models/document_type.py
Expand Up @@ -16,4 +16,4 @@ class Meta:
verbose_name='Name of the type of the document')

def __str__(self):
return "{}".format(self.name)
return f"{self.name}"
3 changes: 2 additions & 1 deletion core/models/legal_basis.py
Expand Up @@ -46,7 +46,8 @@ class Meta:


def __str__(self):
return 'Legal Bases for dataset {}: {}.'.format(self.dataset.title, ",".join(str(lbt.code) for lbt in self.legal_basis_types.all()))
legal_basis_types = ",".join(str(lbt.code) for lbt in self.legal_basis_types.all())
return f'Legal Basis for dataset {self.dataset.title}: {legal_basis_types}.'

def to_dict(self):
return {
Expand Down
2 changes: 1 addition & 1 deletion core/models/legal_basis_type.py
Expand Up @@ -20,7 +20,7 @@ class Meta:
verbose_name='Name', unique=True)

def __str__(self):
return "{} [{}]".format(self.name, self.code)
return f"{self.name} [{self.code}]"

def to_dict(self):
return {
Expand Down
2 changes: 1 addition & 1 deletion core/models/share.py
Expand Up @@ -63,4 +63,4 @@ class Meta:
)

def __str__(self):
return 'Share/Transfer of {} with {}.'.format(self.dataset.title, self.partner.name)
return f'Share/Transfer of {self.dataset.title} with {self.partner.name}'
2 changes: 1 addition & 1 deletion core/models/storage_location.py
Expand Up @@ -58,6 +58,6 @@ class Meta:
)

def __str__(self):
return '{} - {} - {}'.format(self.category, self.backend.name, self.location_description)
return f'{self.category} - {self.backend.name} - {self.location_description}'


2 changes: 1 addition & 1 deletion core/models/storage_resource.py
Expand Up @@ -38,4 +38,4 @@ class Meta:


def __str__(self):
return "{}".format(self.name)
return f"{self.name}"
2 changes: 1 addition & 1 deletion core/models/use_restriction.py
Expand Up @@ -63,7 +63,7 @@ def __str__(self):
title = '(no DataDeclaration coupled'
else:
title = self.data_declaration.title or '(DataDeclaration with no title)'
return "{} - on {} - {}".format(self.restriction_class, title, self.notes)
return f"{self.restriction_class} - on {title} - {self.notes}"

def to_dict(self):
"""
Expand Down
2 changes: 1 addition & 1 deletion core/models/user.py
Expand Up @@ -95,7 +95,7 @@ def __str__(self):
return fullname or self.username

def save(self, *args, **kw):
self.full_name = '{0} {1}'.format(self.first_name, self.last_name)
self.full_name = f'{self.first_name} {self.last_name}'
super(User, self).save(*args, **kw)

def is_part_of(self, *args):
Expand Down
2 changes: 1 addition & 1 deletion notification/email_sender.py
Expand Up @@ -23,7 +23,7 @@ def send_the_email(sender_email, recipients, subject, template, context):
context['profile_url'] = reverse('profile')

# prepare email
subject = "{p} {s}".format(p=SUBJECT_PREFIX, s=subject)
subject = f"{SUBJECT_PREFIX} {subject}"
text_message = render_to_string('%s.txt' % template, context)
html_message = render_to_string('%s.html' % template, context)
msg = EmailMultiAlternatives(
Expand Down
4 changes: 2 additions & 2 deletions test/factories.py
Expand Up @@ -47,8 +47,8 @@ class Meta:
first_name = factory.Faker('first_name')
last_name = factory.Faker('last_name')
last_name = factory.Faker('email')
full_name = factory.LazyAttribute(lambda x: '{0}.{1}'.format(x.first_name, x.last_name).lower())
username = factory.LazyAttribute(lambda x: '{0}.{1}@uni.lux'.format(x.first_name, x.last_name).lower())
full_name = factory.LazyAttribute(lambda x: f'{x.first_name}.{x.last_name}'.lower())
username = factory.LazyAttribute(lambda x: f'{x.first_name}.{x.last_name}@uni.lux'.lower())

@factory.post_generation
def groups(self, create, extracted, **kwargs):
Expand Down
9 changes: 1 addition & 8 deletions web/templatetags/daisy_utils.py
Expand Up @@ -117,14 +117,7 @@ def render(self, context):
icon = 'radio_button_checked'
clazz = 'active'

# return html
return """<li class="{clazz}"><a href="{url}"><i class="material-icons">{icon}</i><span>{facet_name} ({facet_count})</span></a></li>""".format(
url=url,
icon=icon,
clazz=clazz,
facet_name=current_facet[0],
facet_count=current_facet[1],
)
return f'<li class="{clazz}"><a href="{url}"><i class="material-icons">{icon}</i><span>{current_facet[0]} ({current_facet[1]})</span></a></li>'


@register.tag
Expand Down
2 changes: 1 addition & 1 deletion web/views/contact.py
Expand Up @@ -59,7 +59,7 @@ def add_contact_to_project(request, pk):
else:
error_messages = []
for field, error in form.errors.items():
error_message = "{}: {}".format(field, error[0])
error_message = f"{field}: {error[0]}"
error_messages.append(error_message)
add_message(request, messages.ERROR, "\n".join(error_messages))
return redirect(to='project', pk=pk)
Expand Down
2 changes: 1 addition & 1 deletion web/views/contracts.py
Expand Up @@ -165,7 +165,7 @@ def partner_role_delete(request, pk):
# else:
# error_messages = []
# for field, error in form.errors.items():
# error_message = "{}: {}".format(field, error[0])
# error_message = f"{field}: {error[0]}"
# error_messages.append(error_message)
# messages.add_message(request, messages.ERROR, "\n".join(error_messages))
# return redirect(to='contract', pk=pk)
Expand Down

0 comments on commit a1e433c

Please sign in to comment.