Skip to content

Commit

Permalink
removes use of six library
Browse files Browse the repository at this point in the history
  • Loading branch information
DanieSimonlLowe committed Jan 19, 2021
1 parent 4f780eb commit ec21baa
Show file tree
Hide file tree
Showing 32 changed files with 80 additions and 109 deletions.
13 changes: 6 additions & 7 deletions geonode/base/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
#
#########################################################################
import re
import six
import html
import logging

Expand Down Expand Up @@ -220,7 +219,7 @@ def render_options(self, selected_choices):
# Normalize to strings.
def _region_id_from_choice(choice):
if isinstance(choice, int) or \
(isinstance(choice, six.string_types) and choice.isdigit()):
(isinstance(choice, str) and choice.isdigit()):
return int(choice)
else:
return choice.id
Expand All @@ -232,7 +231,7 @@ def _region_id_from_choice(choice):
for option_value, option_label in self.choices:
if not isinstance(
option_label, (list, tuple)) and isinstance(
option_label, six.string_types):
option_label, str):
output.append(
self.render_option_value(
selected_choices,
Expand All @@ -243,18 +242,18 @@ def _region_id_from_choice(choice):
for option_value, option_label in self.choices:
if isinstance(
option_label, (list, tuple)) and not isinstance(
option_label, six.string_types):
option_label, str):
output.append(
format_html(
'<optgroup label="{}">',
force_text(option_value)))
for option in option_label:
if isinstance(
option, (list, tuple)) and not isinstance(
option, six.string_types):
option, str):
if isinstance(
option[1][0], (list, tuple)) and not isinstance(
option[1][0], six.string_types):
option[1][0], str):
for option_child in option[1][0]:
output.append(
self.render_option_value(
Expand Down Expand Up @@ -442,7 +441,7 @@ def clean_keywords(self):
_unsescaped_kwds = []
for k in keywords:
_k = ('%s' % re.sub(r'%([A-Z0-9]{2})', r'&#x\g<1>;', k.strip())).split(",")
if not isinstance(_k, six.string_types):
if not isinstance(_k, str):
for _kk in [html.unescape(x.strip()) for x in _k]:
# Simulate JS Unescape
_kk = _kk.replace('%u', r'\u').encode('unicode-escape').replace(
Expand Down
3 changes: 1 addition & 2 deletions geonode/base/management/commands/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
#########################################################################

import os
import six
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
Expand Down Expand Up @@ -52,7 +51,7 @@ def confirm(prompt=None, resp=False):
prompt = '%s [%s]|%s: ' % (prompt, 'n', 'y')

while True:
ans = six.moves.input(prompt)
ans = input(prompt)
if not ans:
return resp
if ans not in ['y', 'Y', 'n', 'N']:
Expand Down
2 changes: 1 addition & 1 deletion geonode/base/populate_test_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def it():
itinst = it()

def callable():
return six.next(itinst)
return next(itinst)
return callable

next_date = get_test_date()
Expand Down
3 changes: 1 addition & 2 deletions geonode/br/management/commands/backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import requests
import traceback
import re
import six

from .utils import utils

Expand Down Expand Up @@ -495,7 +494,7 @@ def find_external(tree, key=None):
for item in tree:
for found in find_external(item, key=key):
yield found
elif isinstance(tree, six.string_types):
elif isinstance(tree, str):
text = tree.encode('utf-8')
for find in (match_fileurl, match_filename):
found = find(key, text)
Expand Down
3 changes: 1 addition & 2 deletions geonode/br/management/commands/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@

import os
import re
import six
import sys
import hashlib
import psycopg2
Expand Down Expand Up @@ -345,7 +344,7 @@ def confirm(prompt=None, resp=False):
prompt = '%s [%s]|%s: ' % (prompt, 'n', 'y')

while True:
ans = six.moves.input(prompt)
ans = input(prompt)
if not ans:
return resp
if ans not in ['y', 'Y', 'n', 'N']:
Expand Down
3 changes: 1 addition & 2 deletions geonode/client/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,12 @@
#########################################################################
from .conf import settings

from six import string_types


class HookProxy(object):

def __getattr__(self, attr):
if not isinstance(settings.GEONODE_CLIENT_HOOKSET, string_types):
if not isinstance(settings.GEONODE_CLIENT_HOOKSET, str):
return getattr(settings.GEONODE_CLIENT_HOOKSET, attr)
else:
import importlib
Expand Down
4 changes: 1 addition & 3 deletions geonode/client/hooksets.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
#########################################################################
import json

from six import string_types


class BaseHookSet(object):

Expand Down Expand Up @@ -104,7 +102,7 @@ def geoapp_download_template(self, context=None):

# Map Persisting
def viewer_json(self, conf, context=None):
if isinstance(conf, string_types):
if isinstance(conf, str):
conf = json.loads(conf)
return conf

Expand Down
30 changes: 14 additions & 16 deletions geonode/geoserver/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@

from shutil import copyfile

from six import (
string_types,
reraise as raise_
)

from PIL import Image
from io import BytesIO
from resizeimage import resizeimage
Expand Down Expand Up @@ -197,12 +194,12 @@ def extract_name_from_sld(gs_catalog, sld, sld_file=None):
if sld:
if isfile(sld):
sld = open(sld, "rb").read()
if isinstance(sld, string_types):
if isinstance(sld, str):
sld = sld.encode('utf-8')
dom = etree.XML(sld)
elif sld_file and isfile(sld_file):
sld = open(sld_file, "rb").read()
if isinstance(sld, string_types):
if isinstance(sld, str):
sld = sld.encode('utf-8')
dom = dlxml.parse(sld)
except Exception:
Expand Down Expand Up @@ -356,8 +353,10 @@ def set_layer_style(saved_layer, title, sld, base_file=None):
try:
if sld:
if isfile(sld):
sld = open(sld, "rb").read()
elif isinstance(sld, string_types):
with open(sld, "rb") as sld_file:
sld = sld_file.read()

elif isinstance(sld, str):
sld = sld.strip('b\'\n')
sld = re.sub(r'(\\r)|(\\n)', '', sld).encode("UTF-8")
etree.XML(sld)
Expand Down Expand Up @@ -733,11 +732,10 @@ def gs_slurp(
if verbosity > 0:
msg = "Stopping process because --ignore-errors was not set and an error was found."
print(msg, file=sys.stderr)
raise_(
Exception,
Exception("Failed to process {}".format(resource.name), e),
sys.exc_info()[2]
)

raise Exception("Failed to process {}".format(resource.name)) from e


else:
if created:
if not permissions:
Expand Down Expand Up @@ -1398,7 +1396,7 @@ def create_geoserver_db_featurestore(
'Test while idle': 'true',
'host': db['HOST'],
'port': db['PORT'] if isinstance(
db['PORT'], string_types) else str(db['PORT']) or '5432',
db['PORT'], str) else str(db['PORT']) or '5432',
'database': db['NAME'],
'user': db['USER'],
'passwd': db['PASSWORD'],
Expand Down Expand Up @@ -1469,7 +1467,7 @@ def _create_db_featurestore(name, data, overwrite=False, charset="UTF-8", worksp
def get_store(cat, name, workspace=None):
# Make sure workspace is a workspace object and not a string.
# If the workspace does not exist, continue as if no workspace had been defined.
if isinstance(workspace, string_types):
if isinstance(workspace, str):
workspace = cat.get_workspace(workspace)

if workspace is None:
Expand Down Expand Up @@ -2133,7 +2131,7 @@ def _prepare_thumbnail_body_from_opts(request_body, request=None):
width = _default_thumb_size['width']
height = _default_thumb_size['height']

if isinstance(request_body, string_types):
if isinstance(request_body, str):
try:
request_body = json.loads(request_body)
except Exception as e:
Expand Down
3 changes: 1 addition & 2 deletions geonode/groups/templatetags/groups_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
from six import string_types
from django import template
from django.contrib.staticfiles.storage import staticfiles_storage

Expand All @@ -33,7 +32,7 @@ def group_profile_image(group_profile, css_classes="", size=None):
"""

if isinstance(css_classes, string_types):
if isinstance(css_classes, str):
class_attr = 'class="{}" '.format(css_classes)
else:
try:
Expand Down
7 changes: 3 additions & 4 deletions geonode/groups/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

import json
import logging
from six import string_types
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.files.uploadedfile import SimpleUploadedFile
Expand Down Expand Up @@ -436,7 +435,7 @@ def test_resource_permissions(self):
js = json.loads(content)
permissions = js.get('permissions', dict())

if isinstance(permissions, string_types):
if isinstance(permissions, str):
permissions = json.loads(permissions)

# Ensure the groups value is empty by default
Expand Down Expand Up @@ -481,7 +480,7 @@ def test_resource_permissions(self):
js = json.loads(content)
permissions = js.get('permissions', dict())

if isinstance(permissions, string_types):
if isinstance(permissions, str):
permissions = json.loads(permissions)

# Make sure the bar group now has write permissions
Expand Down Expand Up @@ -514,7 +513,7 @@ def test_resource_permissions(self):
js = json.loads(content)
permissions = js.get('permissions', dict())

if isinstance(permissions, string_types):
if isinstance(permissions, str):
permissions = json.loads(permissions)

# Assert the bar group no longer has permissions
Expand Down
9 changes: 5 additions & 4 deletions geonode/layers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
from osgeo import gdal, osr, ogr
from zipfile import ZipFile, is_zipfile
from random import choice
from six import string_types, reraise as raise_

# Django functionality
from django.conf import settings
Expand Down Expand Up @@ -325,7 +324,7 @@ def get_valid_layer_name(layer, overwrite):
# The first thing we do is get the layer name string
if isinstance(layer, Layer):
layer_name = layer.name
elif isinstance(layer, string_types):
elif isinstance(layer, str):
layer_name = str(layer)
else:
msg = ('You must pass either a filename or a GeoNode layer object')
Expand Down Expand Up @@ -933,7 +932,9 @@ def upload(incoming, user=None, overwrite=False,
'and an error was found.')
print(msg, file=sys.stderr)
msg = 'Failed to process %s' % filename
raise_(Exception, e, sys.exc_info()[2])

raise Exception from e


msg = "[%s] Layer for '%s' (%d/%d)" % (status, filename, i + 1, number)
info = {'file': filename, 'status': status}
Expand Down Expand Up @@ -1024,7 +1025,7 @@ def create_thumbnail(instance, thumbnail_remote_url, thumbnail_create_url=None,
params = urlparse(thumbnail_create_url).query.split('&')
request_body = {key: value for (key, value) in
[(lambda p: (p.split("=")[0], p.split("=")[1]))(p) for p in params]}
if 'bbox' in request_body and isinstance(request_body['bbox'], string_types):
if 'bbox' in request_body and isinstance(request_body['bbox'], str):
request_body['bbox'] = [str(coord) for coord in request_body['bbox'].split(",")]
if 'crs' in request_body and 'srid' not in request_body:
request_body['srid'] = request_body['crs']
Expand Down
10 changes: 4 additions & 6 deletions geonode/layers/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
from types import TracebackType
import decimal
import pickle
import six
from django.db.models import Q
from urllib.parse import quote

Expand All @@ -37,7 +36,6 @@
from django.template.response import TemplateResponse
from requests import Request
from itertools import chain
from six import string_types
from owslib.wfs import WebFeatureService

from guardian.shortcuts import get_perms, get_objects_for_user
Expand Down Expand Up @@ -378,7 +376,7 @@ def layer_upload(request, template='upload/layer_upload.html'):
_keys = ['info', 'errors']
for _k in _keys:
if _k in out:
if isinstance(out[_k], string_types):
if isinstance(out[_k], str):
out[_k] = out[_k].encode(layer_charset, 'surrogateescape').decode('utf-8', 'surrogateescape')
elif isinstance(out[_k], dict):
for key, value in out[_k].items():
Expand Down Expand Up @@ -774,7 +772,7 @@ def load_layer_data(request, template='layers/layer_detail.html'):
data_dict = json.loads(request.POST.get('json_data'))
layername = data_dict['layer_name']
filtered_attributes = ''
if not isinstance(data_dict['filtered_attributes'], string_types):
if not isinstance(data_dict['filtered_attributes'], str):
filtered_attributes = [x for x in data_dict['filtered_attributes'] if '/load_layer_data' not in x]
name = layername if ':' not in layername else layername.split(':')[1]
location = "{location}{service}".format(** {
Expand Down Expand Up @@ -809,7 +807,7 @@ def load_layer_data(request, template='layers/layer_detail.html'):
from collections.abc import Iterable
for i in range(len(decoded_features)):
for key, value in decoded_features[i]['properties'].items():
if value != '' and isinstance(value, (string_types, int, float)) and (
if value != '' and isinstance(value, (str, int, float)) and (
(isinstance(value, Iterable) and '/load_layer_data' not in value) or value):
properties[key].append(value)

Expand Down Expand Up @@ -1760,7 +1758,7 @@ def get_selected_result_label(self, result):

def get_result_label(self, result):
"""Return the label of a selected result."""
return six.text_type(result.title)
return str(result.title)

def get_queryset(self):
request = self.request
Expand Down
4 changes: 2 additions & 2 deletions geonode/maps/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ def map_edit(request, mapid, template='maps/map_edit.html'):


def clean_config(conf):
if isinstance(conf, six.string_types):
if isinstance(conf, str):
config = json.loads(conf)
config_extras = [
"tools",
Expand Down Expand Up @@ -1388,7 +1388,7 @@ def get_selected_result_label(self, result):

def get_result_label(self, result):
"""Return the label of a selected result."""
return six.text_type(result.title)
return str(result.title)

def get_queryset(self):
qs = Map.objects.all()
Expand Down
Loading

0 comments on commit ec21baa

Please sign in to comment.