The 'str' object never has attribute decode in Python3, so remove the dead code.

This commit is contained in:
Cyril Jouve 2020-08-12 18:55:35 +05:30 committed by Akshay Joshi
parent 26506a9727
commit 36574b25b6
9 changed files with 20 additions and 148 deletions

View File

@ -568,9 +568,6 @@ def create_app(app_name=None):
svr_discovery_id = section svr_discovery_id = section
description = registry.get(section, 'Description') description = registry.get(section, 'Description')
data_directory = registry.get(section, 'DataDirectory') data_directory = registry.get(section, 'DataDirectory')
if hasattr(str, 'decode'):
description = description.decode('utf-8')
data_directory = data_directory.decode('utf-8')
svr_comment = gettext(u"Auto-detected {0} installation " svr_comment = gettext(u"Auto-detected {0} installation "
u"with the data directory at {1}" u"with the data directory at {1}"
).format(description, data_directory) ).format(description, data_directory)

View File

@ -24,9 +24,6 @@ class AboutModule(PgAdminModule):
def get_own_menuitems(self): def get_own_menuitems(self):
appname = config.APP_NAME appname = config.APP_NAME
if hasattr(str, 'decode'):
appname = appname.decode('utf-8')
return { return {
'help_items': [ 'help_items': [
MenuItem( MenuItem(

View File

@ -841,8 +841,6 @@ class ServerNode(PGChildNodeView):
tunnel_password=tunnel_password, tunnel_password=tunnel_password,
server_types=ServerType.types() server_types=ServerType.types()
) )
if hasattr(str, 'decode') and errmsg is not None:
errmsg = errmsg.decode('utf-8')
if not status: if not status:
db.session.delete(server) db.session.delete(server)
db.session.commit() db.session.commit()
@ -1109,8 +1107,6 @@ class ServerNode(PGChildNodeView):
server, 401, True, True, getattr(e, 'message', str(e))) server, 401, True, True, getattr(e, 'message', str(e)))
if not status: if not status:
if hasattr(str, 'decode'):
errmsg = errmsg.decode('utf-8')
current_app.logger.error( current_app.logger.error(
"Could not connect to server(#{0}) - '{1}'.\nError: {2}" "Could not connect to server(#{0}) - '{1}'.\nError: {2}"

View File

@ -552,8 +552,6 @@ class Filemanager(object):
is_show_hidden_files = show_hidden is_show_hidden_files = show_hidden
path = unquote(path) path = unquote(path)
if hasattr(str, 'decode'):
path = unquote(path).encode('utf-8').decode('utf-8')
try: try:
Filemanager.check_access_permission(in_dir, path) Filemanager.check_access_permission(in_dir, path)
@ -743,8 +741,6 @@ class Filemanager(object):
about the given file. about the given file.
""" """
path = unquote(path) path = unquote(path)
if hasattr(str, 'decode'):
path = unquote(path).encode('utf-8').decode('utf-8')
if self.dir is None: if self.dir is None:
self.dir = "" self.dir = ""
orig_path = u"{0}{1}".format(self.dir, path) orig_path = u"{0}{1}".format(self.dir, path)
@ -851,8 +847,6 @@ class Filemanager(object):
# extract filename # extract filename
oldname = split_path(old)[-1] oldname = split_path(old)[-1]
if hasattr(str, 'decode'):
old = old.encode('utf-8').decode('utf-8')
path = old path = old
path = split_path(path)[0] # extract path path = split_path(path)[0] # extract path
@ -860,8 +854,6 @@ class Filemanager(object):
path += u'/' path += u'/'
newname = new newname = new
if hasattr(str, 'decode'):
newname = new.encode('utf-8').decode('utf-8')
newpath = path + newname newpath = path + newname
# make system old path # make system old path
@ -899,8 +891,6 @@ class Filemanager(object):
} }
the_dir = self.dir if self.dir is not None else '' the_dir = self.dir if self.dir is not None else ''
path = path.encode(
'utf-8').decode('utf-8') if hasattr(str, 'decode') else path
orig_path = u"{0}{1}".format(the_dir, path) orig_path = u"{0}{1}".format(the_dir, path)
try: try:
@ -949,10 +939,6 @@ class Filemanager(object):
file_obj = req.files['newfile'] file_obj = req.files['newfile']
file_name = file_obj.filename file_name = file_obj.filename
if hasattr(str, 'decode'):
path = req.form.get('currentpath').encode(
'utf-8').decode('utf-8')
file_name = file_obj.filename.encode('utf-8').decode('utf-8')
orig_path = u"{0}{1}".format(the_dir, path) orig_path = u"{0}{1}".format(the_dir, path)
new_name = u"{0}{1}".format(orig_path, file_name) new_name = u"{0}{1}".format(orig_path, file_name)
@ -995,9 +981,6 @@ class Filemanager(object):
name = unquote(name) name = unquote(name)
path = unquote(path) path = unquote(path)
if hasattr(str, 'decode'):
name = name.encode('utf-8').decode('utf-8')
path = path.encode('utf-8').decode('utf-8')
try: try:
orig_path = u"{0}{1}".format(the_dir, path) orig_path = u"{0}{1}".format(the_dir, path)
Filemanager.check_access_permission( Filemanager.check_access_permission(
@ -1182,11 +1165,6 @@ class Filemanager(object):
} }
the_dir = self.dir if self.dir is not None else '' the_dir = self.dir if self.dir is not None else ''
if hasattr(str, 'decode'):
path = path.encode('utf-8')
orig_path = u"{0}{1}".format(the_dir, path.decode('utf-8'))
else:
orig_path = u"{0}{1}".format(the_dir, path) orig_path = u"{0}{1}".format(the_dir, path)
try: try:

View File

@ -1187,10 +1187,6 @@ def load_file():
file_data = json.loads(request.data, encoding='utf-8') file_data = json.loads(request.data, encoding='utf-8')
file_path = unquote(file_data['file_name']) file_path = unquote(file_data['file_name'])
if hasattr(str, 'decode'):
file_path = unquote(
file_data['file_name']
).encode('utf-8').decode('utf-8')
# retrieve storage directory path # retrieve storage directory path
storage_manager_path = get_storage_directory() storage_manager_path = get_storage_directory()
@ -1234,10 +1230,6 @@ def save_file():
# generate full path of file # generate full path of file
file_path = unquote(file_data['file_name']) file_path = unquote(file_data['file_name'])
if hasattr(str, 'decode'):
file_path = unquote(
file_data['file_name']
).encode('utf-8').decode('utf-8')
try: try:
Filemanager.check_access_permission(storage_manager_path, file_path) Filemanager.check_access_permission(storage_manager_path, file_path)
@ -1260,17 +1252,11 @@ def save_file():
enc = get_file_encoding_of_loaded_file(os.path.basename(file_path)) enc = get_file_encoding_of_loaded_file(os.path.basename(file_path))
if hasattr(str, 'decode'):
file_content = file_data['file_content']
else:
file_content = file_data['file_content'].encode(enc) file_content = file_data['file_content'].encode(enc)
# write to file # write to file
try: try:
with open(file_path, 'wb+') as output_file: with open(file_path, 'wb+') as output_file:
if hasattr(str, 'decode'):
output_file.write(file_content.encode('utf-8'))
else:
output_file.write(file_content) output_file.write(file_content)
except IOError as e: except IOError as e:
err_msg = gettext("Error: {0}").format(e.strerror) err_msg = gettext("Error: {0}").format(e.strerror)

View File

@ -106,15 +106,8 @@ def pqencryptpassword(password, user):
# Place salt at the end because it may be known by users trying to crack # Place salt at the end because it may be known by users trying to crack
# the MD5 output. # the MD5 output.
# Handling of non-ascii password (Python2)
if hasattr(str, 'decode'):
password = password.encode('utf-8')
user = user.encode('utf-8')
else:
password = password.encode()
user = user.encode()
m.update(password) m.update(password.encode())
m.update(user) m.update(user.encode())
return "md5" + m.hexdigest() return "md5" + m.hexdigest()

View File

@ -249,11 +249,8 @@ class Connection(BaseConnection):
try: try:
password = decrypt(encpass, crypt_key) password = decrypt(encpass, crypt_key)
# Handling of non ascii password (Python2)
if hasattr(str, 'decode'):
password = password.decode('utf-8').encode('utf-8')
# password is in bytes, for python3 we need it in string # password is in bytes, for python3 we need it in string
elif isinstance(password, bytes): if isinstance(password, bytes):
password = password.decode() password = password.decode()
except Exception as e: except Exception as e:
manager.stop_ssh_tunnel() manager.stop_ssh_tunnel()
@ -271,11 +268,6 @@ class Connection(BaseConnection):
passfile = manager.passfile if manager.passfile else None passfile = manager.passfile if manager.passfile else None
try: try:
if hasattr(str, 'decode'):
database = self.db.encode('utf-8')
user = manager.user.encode('utf-8')
conn_id = self.conn_id.encode('utf-8')
else:
database = self.db database = self.db
user = manager.user user = manager.user
conn_id = self.conn_id conn_id = self.conn_id
@ -325,7 +317,7 @@ class Connection(BaseConnection):
u":{msg}".format( u":{msg}".format(
server_id=self.manager.sid, server_id=self.manager.sid,
conn_id=conn_id, conn_id=conn_id,
msg=msg.decode('utf-8') if hasattr(str, 'decode') else msg msg=msg
) )
) )
return False, msg return False, msg
@ -761,19 +753,6 @@ WHERE
else: else:
quote = csv.QUOTE_NONE quote = csv.QUOTE_NONE
if hasattr(str, 'decode'):
# Decode the field_separator
try:
field_separator = field_separator.decode('utf-8')
except Exception as e:
current_app.logger.error(e)
# Decode the quote_char
try:
quote_char = quote_char.decode('utf-8')
except Exception as e:
current_app.logger.error(e)
csv_writer = csv.DictWriter( csv_writer = csv.DictWriter(
res_io, fieldnames=header, delimiter=field_separator, res_io, fieldnames=header, delimiter=field_separator,
quoting=quote, quoting=quote,
@ -1621,40 +1600,6 @@ Failed to reset the connection to the server due to following error:
return resp return resp
def decode_to_utf8(self, value):
"""
This method will decode values to utf-8
Args:
value: String to be decode
Returns:
Decoded string
"""
is_error = False
if hasattr(str, 'decode'):
try:
value = value.decode('utf-8')
except UnicodeDecodeError:
# Let's try with python's preferred encoding
# On Windows lc_messages mostly has environment dependent
# encoding like 'French_France.1252'
try:
import locale
pref_encoding = locale.getpreferredencoding()
value = value.decode(pref_encoding)\
.encode('utf-8')\
.decode('utf-8')
except Exception:
is_error = True
except Exception:
is_error = True
# If still not able to decode then
if is_error:
value = value.decode('ascii', 'ignore')
return value
def _formatted_exception_msg(self, exception_obj, formatted_msg): def _formatted_exception_msg(self, exception_obj, formatted_msg):
""" """
This method is used to parse the psycopg2.Error object and returns the This method is used to parse the psycopg2.Error object and returns the
@ -1673,8 +1618,6 @@ Failed to reset the connection to the server due to following error:
errmsg = exception_obj.diag.message_detail errmsg = exception_obj.diag.message_detail
else: else:
errmsg = str(exception_obj) errmsg = str(exception_obj)
# errmsg might contains encoded value, lets decode it
errmsg = self.decode_to_utf8(errmsg)
# if formatted_msg is false then return from the function # if formatted_msg is false then return from the function
if not formatted_msg: if not formatted_msg:
@ -1689,8 +1632,8 @@ Failed to reset the connection to the server due to following error:
if exception_obj.diag.severity is not None \ if exception_obj.diag.severity is not None \
and exception_obj.diag.message_primary is not None: and exception_obj.diag.message_primary is not None:
ex_diag_message = u"{0}: {1}".format( ex_diag_message = u"{0}: {1}".format(
self.decode_to_utf8(exception_obj.diag.severity), exception_obj.diag.severity,
self.decode_to_utf8(exception_obj.diag.message_primary) exception_obj.diag.message_primary
) )
# If both errors are different then only append it # If both errors are different then only append it
if errmsg and ex_diag_message and \ if errmsg and ex_diag_message and \
@ -1698,9 +1641,7 @@ Failed to reset the connection to the server due to following error:
errmsg.strip().strip('\n').lower(): errmsg.strip().strip('\n').lower():
errmsg += ex_diag_message errmsg += ex_diag_message
elif exception_obj.diag.message_primary is not None: elif exception_obj.diag.message_primary is not None:
message_primary = self.decode_to_utf8( message_primary = exception_obj.diag.message_primary
exception_obj.diag.message_primary
)
if message_primary.lower() not in errmsg.lower(): if message_primary.lower() not in errmsg.lower():
errmsg += message_primary errmsg += message_primary
@ -1708,39 +1649,35 @@ Failed to reset the connection to the server due to following error:
if not errmsg.endswith('\n'): if not errmsg.endswith('\n'):
errmsg += '\n' errmsg += '\n'
errmsg += gettext('SQL state: ') errmsg += gettext('SQL state: ')
errmsg += self.decode_to_utf8(exception_obj.diag.sqlstate) errmsg += exception_obj.diag.sqlstate
if exception_obj.diag.message_detail is not None and \ if exception_obj.diag.message_detail is not None and \
'Detail:'.lower() not in errmsg.lower(): 'Detail:'.lower() not in errmsg.lower():
if not errmsg.endswith('\n'): if not errmsg.endswith('\n'):
errmsg += '\n' errmsg += '\n'
errmsg += gettext('Detail: ') errmsg += gettext('Detail: ')
errmsg += self.decode_to_utf8( errmsg += exception_obj.diag.message_detail
exception_obj.diag.message_detail
)
if exception_obj.diag.message_hint is not None and \ if exception_obj.diag.message_hint is not None and \
'Hint:'.lower() not in errmsg.lower(): 'Hint:'.lower() not in errmsg.lower():
if not errmsg.endswith('\n'): if not errmsg.endswith('\n'):
errmsg += '\n' errmsg += '\n'
errmsg += gettext('Hint: ') errmsg += gettext('Hint: ')
errmsg += self.decode_to_utf8(exception_obj.diag.message_hint) errmsg += exception_obj.diag.message_hint
if exception_obj.diag.statement_position is not None and \ if exception_obj.diag.statement_position is not None and \
'Character:'.lower() not in errmsg.lower(): 'Character:'.lower() not in errmsg.lower():
if not errmsg.endswith('\n'): if not errmsg.endswith('\n'):
errmsg += '\n' errmsg += '\n'
errmsg += gettext('Character: ') errmsg += gettext('Character: ')
errmsg += self.decode_to_utf8( errmsg += exception_obj.diag.statement_position
exception_obj.diag.statement_position
)
if exception_obj.diag.context is not None and \ if exception_obj.diag.context is not None and \
'Context:'.lower() not in errmsg.lower(): 'Context:'.lower() not in errmsg.lower():
if not errmsg.endswith('\n'): if not errmsg.endswith('\n'):
errmsg += '\n' errmsg += '\n'
errmsg += gettext('Context: ') errmsg += gettext('Context: ')
errmsg += self.decode_to_utf8(exception_obj.diag.context) errmsg += exception_obj.diag.context
notices = self.get_notices() notices = self.get_notices()
return errmsg if notices == '' else notices + '\n' + errmsg return errmsg if notices == '' else notices + '\n' + errmsg

View File

@ -366,9 +366,6 @@ WHERE db.oid = {0}""".format(did))
if did is not None: if did is not None:
if did in self.db_info and 'datname' in self.db_info[did]: if did in self.db_info and 'datname' in self.db_info[did]:
database = self.db_info[did]['datname'] database = self.db_info[did]['datname']
if hasattr(str, 'decode') and \
not isinstance(database, unicode):
database = database.decode('utf-8')
if database is None: if database is None:
return False return False
else: else:
@ -479,12 +476,8 @@ WHERE db.oid = {0}""".format(did))
try: try:
tunnel_password = decrypt(tunnel_password, crypt_key) tunnel_password = decrypt(tunnel_password, crypt_key)
# Handling of non ascii password (Python2)
if hasattr(str, 'decode'):
tunnel_password = \
tunnel_password.decode('utf-8').encode('utf-8')
# password is in bytes, for python3 we need it in string # password is in bytes, for python3 we need it in string
elif isinstance(tunnel_password, bytes): if isinstance(tunnel_password, bytes):
tunnel_password = tunnel_password.decode() tunnel_password = tunnel_password.decode()
except Exception as e: except Exception as e:

View File

@ -68,12 +68,7 @@ class ManagedSession(CallbackDict, SessionMixin):
def sign(self, secret): def sign(self, secret):
if not self.hmac_digest: if not self.hmac_digest:
if hasattr(string, 'lowercase'): population = string.ascii_lowercase + string.digits
population = string.lowercase
# If script is running under python3
elif hasattr(string, 'ascii_lowercase'):
population = string.ascii_lowercase
population += string.digits
self.randval = ''.join(random.sample(population, 20)) self.randval = ''.join(random.sample(population, 20))
self.hmac_digest = _calc_hmac( self.hmac_digest = _calc_hmac(