Skip to content

Commit

Permalink
[Code Quality] Replacing str concat with f{str}
Browse files Browse the repository at this point in the history
  • Loading branch information
afabiani committed Apr 30, 2021
1 parent b59a498 commit 567c72d
Show file tree
Hide file tree
Showing 172 changed files with 1,555 additions and 2,013 deletions.
2 changes: 1 addition & 1 deletion geonode/api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ def dehydrate(self, bundle):
documents_count=bundle.data.get('documents_count', 0),
maps_count=bundle.data.get('maps_count', 0),
layers_count=bundle.data.get('layers_count', 0),
)
)
return bundle

def prepend_urls(self):
Expand Down
9 changes: 4 additions & 5 deletions geonode/api/resourcebase_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,12 +363,11 @@ def build_haystack_filters(self, parameters):

if len(subtypes) > 0:
types.append("layer")
sqs = SearchQuerySet().narrow("subtype:%s" %
','.join(map(str, subtypes)))
sqs = SearchQuerySet().narrow(f"subtype:{','.join(map(str, subtypes))}")

if len(types) > 0:
sqs = (SearchQuerySet() if sqs is None else sqs).narrow(
"type:%s" % ','.join(map(str, types)))
f"type:{','.join(map(str, types))}")

# Filter by Query Params
# haystack bug? if boosted fields aren't included in the
Expand Down Expand Up @@ -414,7 +413,7 @@ def build_haystack_filters(self, parameters):
# filter by category
if category:
sqs = (SearchQuerySet() if sqs is None else sqs).narrow(
'category:%s' % ','.join(map(str, category)))
f"category:{','.join(map(str, category))}")

# filter by keyword: use filter_or with keywords_exact
# not using exact leads to fuzzy matching and too many results
Expand All @@ -440,7 +439,7 @@ def build_haystack_filters(self, parameters):
if owner:
sqs = (
SearchQuerySet() if sqs is None else sqs).narrow(
"owner__username:%s" % ','.join(map(str, owner)))
f"owner__username:{','.join(map(str, owner))}")

# filter by date
if date_start:
Expand Down
3 changes: 2 additions & 1 deletion geonode/api/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,8 @@ def to_date(val):

def test_extended_text_filter(self):
"""Test that the extended text filter works as expected"""
filter_url = f"{self.list_url}?title__icontains=layer2&abstract__icontains=layer2&purpose__icontains=layer2&f_method=or"
filter_url = (f"{self.list_url}?title__icontains=layer2&abstract__icontains=layer2"
f"&purpose__icontains=layer2&f_method=or")

resp = self.api_client.get(filter_url)
self.assertValidJSONResponse(resp)
Expand Down
2 changes: 1 addition & 1 deletion geonode/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def verify_token(request):
token_info,
content_type="application/json"
)
response["Authorization"] = ("Bearer %s" % access_token)
response["Authorization"] = f"Bearer {access_token}"
return response
else:
return HttpResponse(
Expand Down
14 changes: 7 additions & 7 deletions geonode/base/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def rectree(parent, path):
children_list_of_tuples.append(
tuple((path + parent.name, tuple((child.id, child.name))))
)
childrens = rectree(child, parent.name + '/')
childrens = rectree(child, f"{parent.name}/")
if childrens:
children_list_of_tuples.extend(childrens)

Expand Down Expand Up @@ -112,10 +112,10 @@ def _get_choices(self):

def label_from_instance(self, obj):
return '<i class="fa ' + obj.fa_class + ' fa-2x unchecked"></i>' \
'<i class="fa ' + obj.fa_class + ' fa-2x checked"></i>' \
'<span class="has-popover" data-container="body" data-toggle="popover" data-placement="top" ' \
'data-content="' + obj.description + '" trigger="hover">' \
'<br/><strong>' + obj.gn_description + '</strong></span>'
'<i class="fa ' + obj.fa_class + ' fa-2x checked"></i>' \
'<span class="has-popover" data-container="body" data-toggle="popover" data-placement="top" ' \
'data-content="' + obj.description + '" trigger="hover">' \
'<br/><strong>' + obj.gn_description + '</strong></span>'


# NOTE: This is commented as it needs updating to work with select2 and autocomlete light.
Expand Down Expand Up @@ -283,7 +283,7 @@ def _region_id_from_choice(choice):
class CategoryForm(forms.Form):
category_choice_field = CategoryChoiceField(
required=False,
label='*' + _('Category'),
label=f"*{_('Category')}",
empty_label=None,
queryset=TopicCategory.objects.filter(
is_choice=True).extra(
Expand Down Expand Up @@ -448,7 +448,7 @@ def clean_keywords(self):
_kk = _kk.replace('%u', r'\u').encode('unicode-escape').replace(
b'\\\\u',
b'\\u').decode('unicode-escape') if '%u' in _kk else _kk
_hk = HierarchicalKeyword.objects.filter(name__iexact='%s' % _kk.strip())
_hk = HierarchicalKeyword.objects.filter(name__iexact=f'{_kk.strip()}')
if _hk and len(_hk) > 0:
_unsescaped_kwds.append(str(_hk[0]))
else:
Expand Down
2 changes: 1 addition & 1 deletion geonode/base/management/commands/fixoauthuri.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,4 @@ def handle(self, *args, **options):
client_secret=client_secret,
user=get_user_model().objects.filter(is_superuser=True)[0]
)
return '%s,%s' % (client_id, client_secret)
return f'{client_id},{client_secret}'
4 changes: 2 additions & 2 deletions geonode/base/management/commands/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ def confirm(prompt=None, resp=False):
prompt = 'Confirm'

if resp:
prompt = '%s [%s]|%s: ' % (prompt, 'y', 'n')
prompt = f"{prompt} [{'y'}]|{'n'}: "
else:
prompt = '%s [%s]|%s: ' % (prompt, 'n', 'y')
prompt = f"{prompt} [{'n'}]|{'y'}: "

while True:
ans = six.moves.input(prompt)
Expand Down
18 changes: 9 additions & 9 deletions geonode/base/management/commands/load_thesaurus.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ def load_thesaurus(self, input_file, name, store):
RDF_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
XML_URI = 'http://www.w3.org/XML/1998/namespace'

ABOUT_ATTRIB = '{' + RDF_URI + '}about'
LANG_ATTRIB = '{' + XML_URI + '}lang'
ABOUT_ATTRIB = f"{{{RDF_URI}}}about"
LANG_ATTRIB = f"{{{XML_URI}}}lang"

ns = {
'rdf': RDF_URI,
Expand All @@ -94,7 +94,7 @@ def load_thesaurus(self, input_file, name, store):
descr = scheme.find('dc:description', ns).text if scheme.find('dc:description', ns) else title
date_issued = scheme.find('dcterms:issued', ns).text

print('Thesaurus "{}" issued on {}'.format(title, date_issued))
print(f'Thesaurus "{title}" issued on {date_issued}')

thesaurus = Thesaurus()
thesaurus.identifier = name
Expand All @@ -110,7 +110,7 @@ def load_thesaurus(self, input_file, name, store):
about = concept.attrib.get(ABOUT_ATTRIB)
alt_label = concept.find('skos:altLabel', ns).text

print('Concept {} ({})'.format(alt_label, about))
print(f'Concept {alt_label} ({about})')

tk = ThesaurusKeyword()
tk.thesaurus = thesaurus
Expand All @@ -124,7 +124,7 @@ def load_thesaurus(self, input_file, name, store):
lang = pref_label.attrib.get(LANG_ATTRIB)
label = pref_label.text

print(' Label {}: {}'.format(lang, label))
print(f' Label {lang}: {label}')

tkl = ThesaurusKeywordLabel()
tkl.keyword = tk
Expand All @@ -138,7 +138,7 @@ def create_fake_thesaurus(self, name):
thesaurus = Thesaurus()
thesaurus.identifier = name

thesaurus.title = "Title: " + name
thesaurus.title = f"Title: {name}"
thesaurus.description = "SAMPLE FAKE THESAURUS USED FOR TESTING"
thesaurus.date = "2016-10-01"

Expand All @@ -147,13 +147,13 @@ def create_fake_thesaurus(self, name):
for keyword in ['aaa', 'bbb', 'ccc']:
tk = ThesaurusKeyword()
tk.thesaurus = thesaurus
tk.about = keyword + '_about'
tk.alt_label = keyword + '_alt'
tk.about = f"{keyword}_about"
tk.alt_label = f"{keyword}_alt"
tk.save()

for l in ['it', 'en', 'es']:
tkl = ThesaurusKeywordLabel()
tkl.keyword = tk
tkl.lang = l
tkl.label = keyword + "_l_" + l + "_t_" + name
tkl.label = f"{keyword}_l_{l}_t_{name}"
tkl.save()
17 changes: 8 additions & 9 deletions geonode/base/management/commands/migrate_baseurl.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ def handle(self, **options):
if not target_address or len(target_address) == 0:
raise CommandError("Target Address '--target-address' is mandatory")

print("This will change all Maps, Layers, \
Styles and Links Base URLs from [%s] to [%s]." % (source_address, target_address))
print(f"This will change all Maps, Layers, Styles and Links Base URLs from [{source_address}] to [{target_address}].")
print("The operation may take some time, depending on the amount of Layer on GeoNode.")
message = 'You want to proceed?'

Expand All @@ -84,30 +83,30 @@ def handle(self, **options):
_cnt = Map.objects.filter(thumbnail_url__icontains=source_address).update(
thumbnail_url=Func(
F('thumbnail_url'),Value(source_address),Value(target_address),function='replace'))
logger.info("Updated %s Maps" % _cnt)
logger.info(f"Updated {_cnt} Maps")

_cnt = MapLayer.objects.filter(ows_url__icontains=source_address).update(
ows_url=Func(
F('ows_url'),Value(source_address),Value(target_address),function='replace'))
MapLayer.objects.filter(layer_params__icontains=source_address).update(
layer_params=Func(
F('layer_params'),Value(source_address),Value(target_address),function='replace'))
logger.info("Updated %s MapLayers" % _cnt)
logger.info(f"Updated {_cnt} MapLayers")

_cnt = Layer.objects.filter(thumbnail_url__icontains=source_address).update(
thumbnail_url=Func(
F('thumbnail_url'),Value(source_address),Value(target_address),function='replace'))
logger.info("Updated %s Layers" % _cnt)
logger.info(f"Updated {_cnt} Layers")

_cnt = Style.objects.filter(sld_url__icontains=source_address).update(
sld_url=Func(
F('sld_url'),Value(source_address),Value(target_address),function='replace'))
logger.info("Updated %s Styles" % _cnt)
logger.info(f"Updated {_cnt} Styles")

_cnt = Link.objects.filter(url__icontains=source_address).update(
url=Func(
F('url'),Value(source_address),Value(target_address),function='replace'))
logger.info("Updated %s Links" % _cnt)
logger.info(f"Updated {_cnt} Links")

_cnt = ResourceBase.objects.filter(thumbnail_url__icontains=source_address).update(
thumbnail_url=Func(
Expand All @@ -118,7 +117,7 @@ def handle(self, **options):
_cnt += ResourceBase.objects.filter(metadata_xml__icontains=source_address).update(
metadata_xml=Func(
F('metadata_xml'), Value(source_address), Value(target_address), function='replace'))
logger.info("Updated %s ResourceBases" % _cnt)
logger.info(f"Updated {_cnt} ResourceBases")

site = Site.objects.get_current()
if site:
Expand All @@ -132,7 +131,7 @@ def handle(self, **options):
_cnt = Application.objects.filter(name='GeoServer').update(
redirect_uris=Func(
F('redirect_uris'), Value(source_address), Value(target_address), function='replace'))
logger.info("Updated %s OAUth2 Redirect URIs" % _cnt)
logger.info(f"Updated {_cnt} OAUth2 Redirect URIs")

finally:
print("...done!")
4 changes: 2 additions & 2 deletions geonode/base/management/commands/set_all_layers_alternate.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def handle(self, *args, **options):
all_layers = all_layers.filter(owner__username=username)

for index, layer in enumerate(all_layers):
logger.info("[%s / %s] Checking 'alternate' of Layer [%s] ..." % ((index + 1), len(all_layers), layer.name))
logger.info(f"[{index + 1} / {len(all_layers)}] Checking 'alternate' of Layer [{layer.name}] ...")
try:
if not layer.alternate:
layer.alternate = layer.typename
Expand All @@ -75,6 +75,6 @@ def handle(self, *args, **options):
# import traceback
# traceback.print_exc()
if ignore_errors:
logger.error("[ERROR] Layer [%s] couldn't be updated" % (layer.name))
logger.error(f"[ERROR] Layer [{layer.name}] couldn't be updated")
else:
raise e
4 changes: 2 additions & 2 deletions geonode/base/management/commands/set_all_layers_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def handle(self, *args, **options):
all_layers = all_layers.filter(owner__username=username)

for index, layer in enumerate(all_layers):
print("[%s / %s] Updating Layer [%s] ..." % ((index + 1), len(all_layers), layer.name))
print(f"[{index + 1} / {len(all_layers)}] Updating Layer [{layer.name}] ...")
try:
# recalculate the layer statistics
set_attributes(layer, overwrite=True)
Expand All @@ -128,7 +128,7 @@ def handle(self, *args, **options):
import traceback
traceback.print_exc()
if ignore_errors:
logger.error("[ERROR] Layer [%s] couldn't be updated" % (layer.name))
logger.error(f"[ERROR] Layer [{layer.name}] couldn't be updated")
else:
raise e

Expand Down
4 changes: 2 additions & 2 deletions geonode/base/management/commands/set_all_layers_public.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def handle(self, *args, **options):
all_layers = Layer.objects.all()

for index, layer in enumerate(all_layers):
print("[%s / %s] Setting public permissions to Layer [%s] ..." % ((index + 1), len(all_layers), layer.name))
print(f"[{index + 1} / {len(all_layers)}] Setting public permissions to Layer [{layer.name}] ...")
try:
use_geofence = settings.OGC_SERVER['default'].get(
"GEOFENCE_SECURITY_ENABLED", False)
Expand All @@ -53,4 +53,4 @@ def handle(self, *args, **options):
perm_spec["users"]["AnonymousUser"] = ['view_resourcebase', 'download_resourcebase']
layer.set_permissions(perm_spec)
except Exception:
logger.error("[ERROR] Layer [%s] couldn't be updated" % (layer.name))
logger.error(f"[ERROR] Layer [{layer.name}] couldn't be updated")
Loading

0 comments on commit 567c72d

Please sign in to comment.