Browse Source

HUE-8737 [core] Futurize apps/useradmin for Python 3.5

Ying Chen 6 years ago
parent
commit
ef0f9e1a97

+ 2 - 2
apps/useradmin/src/useradmin/api.py

@@ -32,7 +32,7 @@ def error_handler(view_fn):
     response = {}
     response = {}
     try:
     try:
       return view_fn(*args, **kwargs)
       return view_fn(*args, **kwargs)
-    except Exception, e:
+    except Exception as e:
       LOG.exception('Error running %s' % view_fn)
       LOG.exception('Error running %s' % view_fn)
       response['status'] = -1
       response['status'] = -1
       response['message'] = smart_unicode(e)
       response['message'] = smart_unicode(e)
@@ -73,7 +73,7 @@ def get_users(request):
       try:
       try:
         group = Group.objects.get(name=groupname)
         group = Group.objects.get(name=groupname)
         group_ids.append(group.id)
         group_ids.append(group.id)
-      except Group.DoesNotExist, e:
+      except Group.DoesNotExist as e:
         LOG.exception("Failed to filter by group, group with name %s not found." % groupname)
         LOG.exception("Failed to filter by group, group with name %s not found." % groupname)
     users = users.filter(groups__in=group_ids)
     users = users.filter(groups__in=group_ids)
 
 

+ 5 - 4
apps/useradmin/src/useradmin/forms.py

@@ -15,6 +15,7 @@
 # See the License for the specific language governing permissions and
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+from builtins import object
 import logging
 import logging
 import re
 import re
 
 
@@ -252,7 +253,7 @@ class AddLdapUsersForm(forms.Form):
         validate_dn(username_pattern)
         validate_dn(username_pattern)
       else:
       else:
         validate_username(username_pattern)
         validate_username(username_pattern)
-    except ValidationError, e:
+    except ValidationError as e:
       errors = self._errors.setdefault('username_pattern', ErrorList())
       errors = self._errors.setdefault('username_pattern', ErrorList())
       errors.append(e.message)
       errors.append(e.message)
       raise forms.ValidationError(e.message)
       raise forms.ValidationError(e.message)
@@ -299,7 +300,7 @@ class AddLdapGroupsForm(forms.Form):
         validate_dn(groupname_pattern)
         validate_dn(groupname_pattern)
       else:
       else:
         validate_groupname(groupname_pattern)
         validate_groupname(groupname_pattern)
-    except ValidationError, e:
+    except ValidationError as e:
       errors = self._errors.setdefault('groupname_pattern', ErrorList())
       errors = self._errors.setdefault('groupname_pattern', ErrorList())
       errors.append(e.message)
       errors.append(e.message)
       raise forms.ValidationError(e.message)
       raise forms.ValidationError(e.message)
@@ -313,7 +314,7 @@ class GroupEditForm(forms.ModelForm):
   """
   """
   GROUPNAME = re.compile('^%s$' % get_groupname_re_rule())
   GROUPNAME = re.compile('^%s$' % get_groupname_re_rule())
 
 
-  class Meta:
+  class Meta(object):
     model = Group
     model = Group
     fields = ("name",)
     fields = ("name",)
 
 
@@ -373,7 +374,7 @@ class PermissionsEditForm(forms.ModelForm):
   Form to manage the set of groups that have a particular permission.
   Form to manage the set of groups that have a particular permission.
   """
   """
 
 
-  class Meta:
+  class Meta(object):
     model = Group
     model = Group
     fields = ()
     fields = ()
 
 

+ 1 - 0
apps/useradmin/src/useradmin/hue_password_policy.py

@@ -16,6 +16,7 @@
 # limitations under the License.
 # limitations under the License.
 
 
 
 
+from builtins import object
 from django.core.exceptions import ValidationError
 from django.core.exceptions import ValidationError
 from django.utils.translation import ugettext_lazy as _
 from django.utils.translation import ugettext_lazy as _
 from useradmin.conf import PASSWORD_POLICY
 from useradmin.conf import PASSWORD_POLICY

+ 5 - 3
apps/useradmin/src/useradmin/ldap_access.py

@@ -18,6 +18,8 @@
 This module provides access to LDAP servers, along with some basic functionality required for Hue and
 This module provides access to LDAP servers, along with some basic functionality required for Hue and
 User Admin to work seamlessly with LDAP.
 User Admin to work seamlessly with LDAP.
 """
 """
+from builtins import str
+from builtins import object
 import ldap
 import ldap
 import ldap.filter
 import ldap.filter
 import logging
 import logging
@@ -163,13 +165,13 @@ class LdapConnection(object):
     if bind_user:
     if bind_user:
       try:
       try:
         self.ldap_handle.simple_bind_s(bind_user, bind_password)
         self.ldap_handle.simple_bind_s(bind_user, bind_password)
-      except Exception, e:
+      except Exception as e:
         self.handle_bind_exception(e, bind_user)
         self.handle_bind_exception(e, bind_user)
     else:
     else:
       try:
       try:
         # Do anonymous bind
         # Do anonymous bind
         self.ldap_handle.simple_bind_s('','')
         self.ldap_handle.simple_bind_s('','')
-      except Exception, e:
+      except Exception as e:
         self.handle_bind_exception(e)
         self.handle_bind_exception(e)
 
 
   def handle_bind_exception(self, exception, bind_user=None):
   def handle_bind_exception(self, exception, bind_user=None):
@@ -356,7 +358,7 @@ class LdapConnection(object):
         return self._transform_find_user_results(result_data, user_name_attr)
         return self._transform_find_user_results(result_data, user_name_attr)
       else:
       else:
         return []
         return []
-    except ldap.LDAPError, e:
+    except ldap.LDAPError as e:
        LOG.warn("LDAP Error: %s" % e)
        LOG.warn("LDAP Error: %s" % e)
 
 
     return None
     return None

+ 9 - 4
apps/useradmin/src/useradmin/middleware.py

@@ -15,6 +15,11 @@
 # See the License for the specific language governing permissions and
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+from __future__ import division
+from __future__ import absolute_import
+from builtins import next
+from past.utils import old_div
+from builtins import object
 import logging
 import logging
 from datetime import datetime
 from datetime import datetime
 
 
@@ -28,10 +33,10 @@ from django.utils.translation import ugettext as _
 from desktop.auth.views import dt_logout
 from desktop.auth.views import dt_logout
 from desktop.conf import AUTH, LDAP, SESSION
 from desktop.conf import AUTH, LDAP, SESSION
 
 
-from models import UserProfile, get_profile
-from views import import_ldap_users
+from useradmin.models import UserProfile, get_profile
+from useradmin.views import import_ldap_users
 
 
-import ldap_access
+from useradmin import ldap_access
 
 
 
 
 LOG = logging.getLogger(__name__)
 LOG = logging.getLogger(__name__)
@@ -111,7 +116,7 @@ class LastActivityMiddleware(object):
     if hasattr(dt, 'total_seconds'):
     if hasattr(dt, 'total_seconds'):
       return dt.total_seconds()
       return dt.total_seconds()
     else:
     else:
-      return (dt.microseconds + (dt.seconds + dt.days * 24 * 3600) * 10**6) / 10**6
+      return old_div((dt.microseconds + (dt.seconds + dt.days * 24 * 3600) * 10**6), 10**6)
 
 
 class ConcurrentUserSessionMiddleware(object):
 class ConcurrentUserSessionMiddleware(object):
   """
   """

+ 3 - 3
apps/useradmin/src/useradmin/models.py

@@ -145,7 +145,7 @@ def get_profile(user):
     # Lazily create profile.
     # Lazily create profile.
     try:
     try:
       profile = UserProfile.objects.get(user=user)
       profile = UserProfile.objects.get(user=user)
-    except UserProfile.DoesNotExist, e:
+    except UserProfile.DoesNotExist as e:
       profile = create_profile_for_user(user)
       profile = create_profile_for_user(user)
     user._cached_userman_profile = profile
     user._cached_userman_profile = profile
     return profile
     return profile
@@ -330,7 +330,7 @@ def install_sample_user():
         user = auth_models.User.objects.get(id=SAMPLE_USER_ID)
         user = auth_models.User.objects.get(id=SAMPLE_USER_ID)
         user.username = SAMPLE_USER_INSTALL
         user.username = SAMPLE_USER_INSTALL
         user.save()
         user.save()
-  except Exception, ex:
+  except Exception as ex:
     LOG.exception('Failed to get or create sample user')
     LOG.exception('Failed to get or create sample user')
 
 
   # If sample user doesn't belong to default group, add to default group
   # If sample user doesn't belong to default group, add to default group
@@ -347,7 +347,7 @@ def install_sample_user():
       LOG.info('Created home directory for user: %s' % SAMPLE_USER_INSTALL)
       LOG.info('Created home directory for user: %s' % SAMPLE_USER_INSTALL)
     else:
     else:
       LOG.info('Home directory already exists for user: %s' % SAMPLE_USER_INSTALL)
       LOG.info('Home directory already exists for user: %s' % SAMPLE_USER_INSTALL)
-  except Exception, ex:
+  except Exception as ex:
     LOG.exception('Failed to create home directory for user %s: %s' % (SAMPLE_USER_INSTALL, str(ex)))
     LOG.exception('Failed to create home directory for user %s: %s' % (SAMPLE_USER_INSTALL, str(ex)))
 
 
   return user
   return user

+ 1 - 1
apps/useradmin/src/useradmin/old_migrations/0007_remove_s3_access.py

@@ -20,7 +20,7 @@ class Migration(SchemaMigration):
           if get_default_user_group():
           if get_default_user_group():
               revoked = revoke_permission(get_default_user_group(), 'filebrowser', 's3_access')
               revoked = revoke_permission(get_default_user_group(), 'filebrowser', 's3_access')
               LOG.info('Revoked s3 permissions: %s' % revoked)
               LOG.info('Revoked s3 permissions: %s' % revoked)
-        except Exception, e:
+        except Exception as e:
           LOG.error(e)
           LOG.error(e)
 
 
     def backwards(self, orm):
     def backwards(self, orm):

+ 4 - 3
apps/useradmin/src/useradmin/test_ldap.py

@@ -16,6 +16,7 @@
 # See the License for the specific language governing permissions and
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+from __future__ import absolute_import
 import ldap
 import ldap
 
 
 from nose.plugins.attrib import attr
 from nose.plugins.attrib import attr
@@ -34,11 +35,11 @@ from useradmin.models import get_profile
 
 
 from hadoop import pseudo_hdfs4
 from hadoop import pseudo_hdfs4
 from hadoop.pseudo_hdfs4 import is_live_cluster
 from hadoop.pseudo_hdfs4 import is_live_cluster
-from views import sync_ldap_users, sync_ldap_groups, import_ldap_users, import_ldap_groups, \
+from useradmin.views import sync_ldap_users, sync_ldap_groups, import_ldap_users, import_ldap_groups, \
                   add_ldap_users, add_ldap_groups, sync_ldap_users_groups
                   add_ldap_users, add_ldap_groups, sync_ldap_users_groups
 
 
-import ldap_access
-from tests import BaseUserAdminTests, LdapTestConnection, reset_all_groups, reset_all_users
+from useradmin import ldap_access
+from useradmin.tests import BaseUserAdminTests, LdapTestConnection, reset_all_groups, reset_all_users
 
 
 
 
 def get_multi_ldap_config():
 def get_multi_ldap_config():

+ 4 - 3
apps/useradmin/src/useradmin/test_ldap_deprecated.py

@@ -16,6 +16,7 @@
 # See the License for the specific language governing permissions and
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+from __future__ import absolute_import
 import ldap
 import ldap
 
 
 from nose.plugins.attrib import attr
 from nose.plugins.attrib import attr
@@ -33,11 +34,11 @@ from useradmin.models import LdapGroup, UserProfile, get_profile
 
 
 from hadoop import pseudo_hdfs4
 from hadoop import pseudo_hdfs4
 from hadoop.pseudo_hdfs4 import is_live_cluster
 from hadoop.pseudo_hdfs4 import is_live_cluster
-from views import sync_ldap_users, sync_ldap_groups, import_ldap_users, import_ldap_groups, \
+from useradmin.views import sync_ldap_users, sync_ldap_groups, import_ldap_users, import_ldap_groups, \
                   add_ldap_users, add_ldap_groups, sync_ldap_users_groups
                   add_ldap_users, add_ldap_groups, sync_ldap_users_groups
 
 
-import ldap_access
-from tests import BaseUserAdminTests, LdapTestConnection, reset_all_groups, reset_all_users
+from useradmin import ldap_access
+from useradmin.tests import BaseUserAdminTests, LdapTestConnection, reset_all_groups, reset_all_users
 
 
 class TestUserAdminLdapDeprecated(BaseUserAdminTests):
 class TestUserAdminLdapDeprecated(BaseUserAdminTests):
   def test_useradmin_ldap_user_group_membership_sync(self):
   def test_useradmin_ldap_user_group_membership_sync(self):

+ 16 - 12
apps/useradmin/src/useradmin/tests.py

@@ -16,12 +16,16 @@
 # See the License for the specific language governing permissions and
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+from future import standard_library
+standard_library.install_aliases()
+from builtins import str
+from builtins import object
 import json
 import json
 import ldap
 import ldap
 import re
 import re
 import sys
 import sys
 import time
 import time
-import urllib
+import urllib.request, urllib.parse, urllib.error
 
 
 from nose.plugins.skip import SkipTest
 from nose.plugins.skip import SkipTest
 from nose.tools import assert_true, assert_equal, assert_false, assert_not_equal
 from nose.tools import assert_true, assert_equal, assert_false, assert_not_equal
@@ -91,25 +95,25 @@ class LdapTestConnection(object):
   def find_users(self, username_pattern, search_attr=None, user_name_attr=None, find_by_dn=False, scope=ldap.SCOPE_SUBTREE):
   def find_users(self, username_pattern, search_attr=None, user_name_attr=None, find_by_dn=False, scope=ldap.SCOPE_SUBTREE):
     """ Returns info for a particular user via a case insensitive search """
     """ Returns info for a particular user via a case insensitive search """
     if find_by_dn:
     if find_by_dn:
-      data = filter(lambda attrs: attrs['dn'] == username_pattern, self._instance.users.values())
+      data = [attrs for attrs in list(self._instance.users.values()) if attrs['dn'] == username_pattern]
     else:
     else:
       username_pattern = "^%s$" % username_pattern.replace('.','\\.').replace('*', '.*')
       username_pattern = "^%s$" % username_pattern.replace('.','\\.').replace('*', '.*')
       username_fsm = re.compile(username_pattern, flags=re.I)
       username_fsm = re.compile(username_pattern, flags=re.I)
-      usernames = filter(lambda username: username_fsm.match(username), self._instance.users.keys())
+      usernames = [username for username in list(self._instance.users.keys()) if username_fsm.match(username)]
       data = [self._instance.users.get(username) for username in usernames]
       data = [self._instance.users.get(username) for username in usernames]
     return data
     return data
 
 
   def find_groups(self, groupname_pattern, search_attr=None, group_name_attr=None, group_member_attr=None, group_filter=None, find_by_dn=False, scope=ldap.SCOPE_SUBTREE):
   def find_groups(self, groupname_pattern, search_attr=None, group_name_attr=None, group_member_attr=None, group_filter=None, find_by_dn=False, scope=ldap.SCOPE_SUBTREE):
     """ Return all groups in the system with parents and children """
     """ Return all groups in the system with parents and children """
     if find_by_dn:
     if find_by_dn:
-      data = filter(lambda attrs: attrs['dn'] == groupname_pattern, self._instance.groups.values())
+      data = [attrs for attrs in list(self._instance.groups.values()) if attrs['dn'] == groupname_pattern]
       # SCOPE_SUBTREE means we return all sub-entries of the desired entry along with the desired entry.
       # SCOPE_SUBTREE means we return all sub-entries of the desired entry along with the desired entry.
       if data and scope == ldap.SCOPE_SUBTREE:
       if data and scope == ldap.SCOPE_SUBTREE:
-        sub_data = filter(lambda attrs: attrs['dn'].endswith(data[0]['dn']), self._instance.groups.values())
+        sub_data = [attrs for attrs in list(self._instance.groups.values()) if attrs['dn'].endswith(data[0]['dn'])]
         data.extend(sub_data)
         data.extend(sub_data)
     else:
     else:
       groupname_pattern = "^%s$" % groupname_pattern.replace('.','\\.').replace('*', '.*')
       groupname_pattern = "^%s$" % groupname_pattern.replace('.','\\.').replace('*', '.*')
-      groupnames = filter(lambda username: re.match(groupname_pattern, username), self._instance.groups.keys())
+      groupnames = [username for username in list(self._instance.groups.keys()) if re.match(groupname_pattern, username)]
       data = [self._instance.groups.get(groupname) for groupname in groupnames]
       data = [self._instance.groups.get(groupname) for groupname in groupnames]
     return data
     return data
 
 
@@ -134,13 +138,13 @@ class LdapTestConnection(object):
 
 
   def find_users_of_group(self, dn):
   def find_users_of_group(self, dn):
     members = []
     members = []
-    for group_info in self._instance.groups.values():
+    for group_info in list(self._instance.groups.values()):
       if group_info['dn'] == dn:
       if group_info['dn'] == dn:
         members.extend(group_info['members'])
         members.extend(group_info['members'])
 
 
     members = set(members)
     members = set(members)
     users = []
     users = []
-    for user_info in self._instance.users.values():
+    for user_info in list(self._instance.users.values()):
       if user_info['dn'] in members:
       if user_info['dn'] in members:
         users.append(user_info)
         users.append(user_info)
 
 
@@ -148,18 +152,18 @@ class LdapTestConnection(object):
 
 
   def find_groups_of_group(self, dn):
   def find_groups_of_group(self, dn):
     members = []
     members = []
-    for group_info in self._instance.groups.values():
+    for group_info in list(self._instance.groups.values()):
       if group_info['dn'] == dn:
       if group_info['dn'] == dn:
         members.extend(group_info['members'])
         members.extend(group_info['members'])
 
 
     groups = []
     groups = []
-    for group_info in self._instance.groups.values():
+    for group_info in list(self._instance.groups.values()):
       if group_info['dn'] in members:
       if group_info['dn'] in members:
         groups.append(group_info)
         groups.append(group_info)
 
 
     return groups
     return groups
 
 
-  class Data:
+  class Data(object):
     def __init__(self):
     def __init__(self):
       self.users = {'moe': {'dn': 'uid=moe,ou=People,dc=example,dc=com', 'username':'moe', 'first':'Moe', 'email':'moe@stooges.com', 'groups': ['cn=TestUsers,ou=Groups,dc=example,dc=com']},
       self.users = {'moe': {'dn': 'uid=moe,ou=People,dc=example,dc=com', 'username':'moe', 'first':'Moe', 'email':'moe@stooges.com', 'groups': ['cn=TestUsers,ou=Groups,dc=example,dc=com']},
                     'lårry': {'dn': 'uid=lårry,ou=People,dc=example,dc=com', 'username':'lårry', 'first':'Larry', 'last':'Stooge', 'email':'larry@stooges.com', 'groups': ['cn=TestUsers,ou=Groups,dc=example,dc=com', 'cn=Test Administrators,cn=TestUsers,ou=Groups,dc=example,dc=com']},
                     'lårry': {'dn': 'uid=lårry,ou=People,dc=example,dc=com', 'username':'lårry', 'first':'Larry', 'last':'Stooge', 'email':'larry@stooges.com', 'groups': ['cn=TestUsers,ou=Groups,dc=example,dc=com', 'cn=Test Administrators,cn=TestUsers,ou=Groups,dc=example,dc=com']},
@@ -574,7 +578,7 @@ class TestUserAdmin(BaseUserAdminTests):
 
 
   def test_user_admin(self):
   def test_user_admin(self):
     FUNNY_NAME = 'أحمد@cloudera.com'
     FUNNY_NAME = 'أحمد@cloudera.com'
-    FUNNY_NAME_QUOTED = urllib.quote(FUNNY_NAME)
+    FUNNY_NAME_QUOTED = urllib.parse.quote(FUNNY_NAME)
 
 
     resets = [
     resets = [
       useradmin.conf.DEFAULT_USER_GROUP.set_for_testing('test_default'),
       useradmin.conf.DEFAULT_USER_GROUP.set_for_testing('test_default'),

+ 1 - 0
apps/useradmin/src/useradmin/tests_api.py

@@ -16,6 +16,7 @@
 # See the License for the specific language governing permissions and
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+from builtins import object
 import json
 import json
 
 
 from nose.tools import assert_equal, assert_false, assert_true
 from nose.tools import assert_equal, assert_false, assert_true

+ 37 - 35
apps/useradmin/src/useradmin/views.py

@@ -15,6 +15,8 @@
 # See the License for the specific language governing permissions and
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # limitations under the License.
 
 
+from __future__ import absolute_import
+from builtins import map
 import pwd
 import pwd
 import grp
 import grp
 import logging
 import logging
@@ -27,8 +29,8 @@ from axes.models import AccessAttempt
 from axes.utils import reset
 from axes.utils import reset
 
 
 import ldap
 import ldap
-import ldap_access
-from ldap_access import LdapBindException, LdapSearchException
+from useradmin import ldap_access
+from useradmin.ldap_access import LdapBindException, LdapSearchException
 
 
 from django.contrib.auth.models import User, Group
 from django.contrib.auth.models import User, Group
 from django.urls import reverse
 from django.urls import reverse
@@ -326,7 +328,7 @@ def edit_user(request, username=None):
             try:
             try:
               reset(username=username)
               reset(username=username)
               request.info(_('Successfully unlocked account for user: %s') % username)
               request.info(_('Successfully unlocked account for user: %s') % username)
-            except Exception, e:
+            except Exception as e:
               raise PopupException(_('Failed to reset login attempts for %s: %s') % (username, str(e)))
               raise PopupException(_('Failed to reset login attempts for %s: %s') % (username, str(e)))
         finally:
         finally:
           __users_lock.release()
           __users_lock.release()
@@ -335,7 +337,7 @@ def edit_user(request, username=None):
       if form.cleaned_data.get('ensure_home_directory'):
       if form.cleaned_data.get('ensure_home_directory'):
         try:
         try:
           ensure_home_directory(request.fs, instance)
           ensure_home_directory(request.fs, instance)
-        except (IOError, WebHdfsException), e:
+        except (IOError, WebHdfsException) as e:
           request.error(_('Cannot make home directory for user %s.') % instance.username)
           request.error(_('Cannot make home directory for user %s.') % instance.username)
         else:
         else:
           updated = True
           updated = True
@@ -399,7 +401,7 @@ def edit_user(request, username=None):
     })
     })
   else:
   else:
     if request.method == 'POST' and is_embeddable:
     if request.method == 'POST' and is_embeddable:
-      return JsonResponse({'status': -1, 'errors': [{'id': f.id_for_label, 'message': map(antixss, f.errors)} for f in form if f.errors]})
+      return JsonResponse({'status': -1, 'errors': [{'id': f.id_for_label, 'message': list(map(antixss, f.errors))} for f in form if f.errors]})
     else:
     else:
       return render('edit_user.mako', request, {
       return render('edit_user.mako', request, {
         'form': form,
         'form': form,
@@ -559,10 +561,10 @@ def add_ldap_users(request):
         failed_ldap_users = []
         failed_ldap_users = []
         connection = ldap_access.get_connection_from_server(server)
         connection = ldap_access.get_connection_from_server(server)
         users = import_ldap_users(connection, username_pattern, False, import_by_dn, failed_users=failed_ldap_users)
         users = import_ldap_users(connection, username_pattern, False, import_by_dn, failed_users=failed_ldap_users)
-      except (ldap.LDAPError, LdapBindException), e:
+      except (ldap.LDAPError, LdapBindException) as e:
         LOG.error("LDAP Exception: %s" % smart_str(e))
         LOG.error("LDAP Exception: %s" % smart_str(e))
         raise PopupException(smart_str(_('There was an error when communicating with LDAP: %s')) % str(e))
         raise PopupException(smart_str(_('There was an error when communicating with LDAP: %s')) % str(e))
-      except ValidationError, e:
+      except ValidationError as e:
         LOG.error("LDAP Exception: %s" % smart_str(e))
         LOG.error("LDAP Exception: %s" % smart_str(e))
         raise PopupException(smart_str(_('There was a problem with some of the LDAP information: %s')) % str(e))
         raise PopupException(smart_str(_('There was a problem with some of the LDAP information: %s')) % str(e))
 
 
@@ -570,7 +572,7 @@ def add_ldap_users(request):
         for user in users:
         for user in users:
           try:
           try:
             ensure_home_directory(request.fs, user)
             ensure_home_directory(request.fs, user)
-          except (IOError, WebHdfsException), e:
+          except (IOError, WebHdfsException) as e:
             request.error(_("Cannot make home directory for user %s.") % user.username)
             request.error(_("Cannot make home directory for user %s.") % user.username)
 
 
       if not users:
       if not users:
@@ -636,10 +638,10 @@ def add_ldap_groups(request):
         groups = import_ldap_groups(connection, groupname_pattern, import_members=import_members,
         groups = import_ldap_groups(connection, groupname_pattern, import_members=import_members,
                                     import_members_recursive=import_members_recursive, sync_users=True,
                                     import_members_recursive=import_members_recursive, sync_users=True,
                                     import_by_dn=import_by_dn, failed_users=failed_ldap_users)
                                     import_by_dn=import_by_dn, failed_users=failed_ldap_users)
-      except (ldap.LDAPError, LdapBindException), e:
+      except (ldap.LDAPError, LdapBindException) as e:
         LOG.error("LDAP Exception: %s" % smart_str(e))
         LOG.error("LDAP Exception: %s" % smart_str(e))
         raise PopupException(smart_str(_('There was an error when communicating with LDAP: %s')) % str(e))
         raise PopupException(smart_str(_('There was an error when communicating with LDAP: %s')) % str(e))
-      except ValidationError, e:
+      except ValidationError as e:
         LOG.error("LDAP Exception: %s" % smart_str(e))
         LOG.error("LDAP Exception: %s" % smart_str(e))
         raise PopupException(smart_str(_('There was a problem with some of the LDAP information: %s')) % str(e))
         raise PopupException(smart_str(_('There was a problem with some of the LDAP information: %s')) % str(e))
 
 
@@ -651,7 +653,7 @@ def add_ldap_groups(request):
         for user in unique_users:
         for user in unique_users:
           try:
           try:
             ensure_home_directory(request.fs, user)
             ensure_home_directory(request.fs, user)
-          except (IOError, WebHdfsException), e:
+          except (IOError, WebHdfsException) as e:
             raise PopupException(_("Exception creating home directory for LDAP user %s in group %s.") % (user, group), detail=e)
             raise PopupException(_("Exception creating home directory for LDAP user %s in group %s.") % (user, group), detail=e)
 
 
       if groups:
       if groups:
@@ -708,7 +710,7 @@ def sync_ldap_users_groups(request):
       server = form.cleaned_data.get('server')
       server = form.cleaned_data.get('server')
       try:
       try:
         connection = ldap_access.get_connection_from_server(server)
         connection = ldap_access.get_connection_from_server(server)
-      except (ldap.LDAPError, LdapBindException), e:
+      except (ldap.LDAPError, LdapBindException) as e:
         LOG.error("LDAP Exception: %s" % smart_str(e))
         LOG.error("LDAP Exception: %s" % smart_str(e))
         raise PopupException(smart_str(_('There was an error when communicating with LDAP: %s')) % str(e))
         raise PopupException(smart_str(_('There was an error when communicating with LDAP: %s')) % str(e))
 
 
@@ -744,7 +746,7 @@ def sync_ldap_users_and_groups(connection, is_ensuring_home_directory=False, fs=
   try:
   try:
     users = sync_ldap_users(connection, failed_users=failed_users)
     users = sync_ldap_users(connection, failed_users=failed_users)
     groups = sync_ldap_groups(connection, failed_users=failed_users)
     groups = sync_ldap_groups(connection, failed_users=failed_users)
-  except (ldap.LDAPError, LdapBindException), e:
+  except (ldap.LDAPError, LdapBindException) as e:
     LOG.error("LDAP Exception: %s" % smart_str(e))
     LOG.error("LDAP Exception: %s" % smart_str(e))
     raise PopupException(smart_str(_('There was an error when communicating with LDAP: %s')) % str(e))
     raise PopupException(smart_str(_('There was an error when communicating with LDAP: %s')) % str(e))
 
 
@@ -753,7 +755,7 @@ def sync_ldap_users_and_groups(connection, is_ensuring_home_directory=False, fs=
     for user in users:
     for user in users:
       try:
       try:
         ensure_home_directory(fs, user)
         ensure_home_directory(fs, user)
-      except (IOError, WebHdfsException), e:
+      except (IOError, WebHdfsException) as e:
         raise PopupException(_("The import may not be complete, sync again."), detail=e)
         raise PopupException(_("The import may not be complete, sync again."), detail=e)
 
 
 
 
@@ -813,7 +815,7 @@ def ensure_home_directory(fs, user):
     home_directory = userprofile.home_directory.split('@')[0]
     home_directory = userprofile.home_directory.split('@')[0]
 
 
   if userprofile is not None and userprofile.home_directory:
   if userprofile is not None and userprofile.home_directory:
-    if not isinstance(home_directory, unicode):
+    if not isinstance(home_directory, str):
       home_directory = home_directory.decode("utf-8")
       home_directory = home_directory.decode("utf-8")
     fs.do_as_user(username, fs.create_home_dir, home_directory)
     fs.do_as_user(username, fs.create_home_dir, home_directory)
   else:
   else:
@@ -834,7 +836,7 @@ def sync_unix_users_and_groups(min_uid, max_uid, min_gid, max_gid, check_shell):
   __users_lock.acquire()
   __users_lock.acquire()
   __groups_lock.acquire()
   __groups_lock.acquire()
   # Import groups
   # Import groups
-  for name, group in hadoop_groups.iteritems():
+  for name, group in hadoop_groups.items():
     try:
     try:
       if len(group.gr_mem) != 0:
       if len(group.gr_mem) != 0:
         hue_group = Group.objects.get(name=name)
         hue_group = Group.objects.get(name=name)
@@ -854,7 +856,7 @@ def sync_unix_users_and_groups(min_uid, max_uid, min_gid, max_gid, check_shell):
   # Now let's import the users
   # Now let's import the users
   hadoop_users = dict((user.pw_name, user) for user in pwd.getpwall() \
   hadoop_users = dict((user.pw_name, user) for user in pwd.getpwall() \
       if (user.pw_uid >= min_uid and user.pw_uid < max_uid) or user.pw_name in grp.getgrnam('hadoop').gr_mem)
       if (user.pw_uid >= min_uid and user.pw_uid < max_uid) or user.pw_name in grp.getgrnam('hadoop').gr_mem)
-  for username, user in hadoop_users.iteritems():
+  for username, user in hadoop_users.items():
     try:
     try:
       if check_shell:
       if check_shell:
         pw_shell = user.pw_shell
         pw_shell = user.pw_shell
@@ -904,7 +906,7 @@ def _import_ldap_users(connection, username_pattern, sync_groups=False, import_b
   user_info = None
   user_info = None
   try:
   try:
     user_info = connection.find_users(username_pattern, find_by_dn=import_by_dn)
     user_info = connection.find_users(username_pattern, find_by_dn=import_by_dn)
-  except LdapSearchException, e:
+  except LdapSearchException as e:
     LOG.warn("Failed to find LDAP user: %s" % e)
     LOG.warn("Failed to find LDAP user: %s" % e)
 
 
   if not user_info:
   if not user_info:
@@ -1020,12 +1022,12 @@ def _import_ldap_members(connection, group, ldap_info, count=0, max_count=1, fai
 
 
   try:
   try:
     users_info = connection.find_users_of_group(ldap_info['dn'])
     users_info = connection.find_users_of_group(ldap_info['dn'])
-  except LdapSearchException, e:
+  except LdapSearchException as e:
     LOG.warn("Failed to find LDAP users of group: %s" % e)
     LOG.warn("Failed to find LDAP users of group: %s" % e)
 
 
   try:
   try:
     groups_info = connection.find_groups_of_group(ldap_info['dn'])
     groups_info = connection.find_groups_of_group(ldap_info['dn'])
-  except LdapSearchException, e:
+  except LdapSearchException as e:
     LOG.warn("Failed to find LDAP groups of group: %s" % e)
     LOG.warn("Failed to find LDAP groups of group: %s" % e)
 
 
   posix_members = ldap_info['posix_members']
   posix_members = ldap_info['posix_members']
@@ -1051,13 +1053,13 @@ def _import_ldap_members(connection, group, ldap_info, count=0, max_count=1, fai
     user_info = None
     user_info = None
     try:
     try:
       user_info = connection.find_users(posix_member, search_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), user_name_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), find_by_dn=False)
       user_info = connection.find_users(posix_member, search_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), user_name_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), find_by_dn=False)
-    except LdapSearchException, e:
+    except LdapSearchException as e:
       LOG.warn("Failed to find LDAP users: %s" % e)
       LOG.warn("Failed to find LDAP users: %s" % e)
 
 
     if user_info:
     if user_info:
       users = _import_ldap_users_info(connection, user_info, failed_users=failed_users)
       users = _import_ldap_users_info(connection, user_info, failed_users=failed_users)
       if users:
       if users:
-        LOG.debug("Adding member %s represented as users (should be a single user) %s to group %s" % (str(posix_member), str(users), str(group.name)))
+        LOG.debug("Adding member %s represented as users (should be a single user) %s to group %s" % (smart_str(posix_member), smart_str(users), smart_str(group.name)))
         group.user_set.add(*users)
         group.user_set.add(*users)
 
 
 
 
@@ -1070,12 +1072,12 @@ def _sync_ldap_members(connection, group, ldap_info, count=0, max_count=1, faile
 
 
   try:
   try:
     users_info = connection.find_users_of_group(ldap_info['dn'])
     users_info = connection.find_users_of_group(ldap_info['dn'])
-  except LdapSearchException, e:
+  except LdapSearchException as e:
     LOG.warn("Failed to find LDAP users of group: %s" % e)
     LOG.warn("Failed to find LDAP users of group: %s" % e)
 
 
   try:
   try:
     groups_info = connection.find_groups_of_group(ldap_info['dn'])
     groups_info = connection.find_groups_of_group(ldap_info['dn'])
-  except LdapSearchException, e:
+  except LdapSearchException as e:
     LOG.warn("Failed to find LDAP groups of group: %s" % e)
     LOG.warn("Failed to find LDAP groups of group: %s" % e)
 
 
   posix_members = ldap_info['posix_members']
   posix_members = ldap_info['posix_members']
@@ -1102,7 +1104,7 @@ def _sync_ldap_members(connection, group, ldap_info, count=0, max_count=1, faile
     users_info = []
     users_info = []
     try:
     try:
       users_info = connection.find_users(posix_member, search_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), user_name_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), find_by_dn=False)
       users_info = connection.find_users(posix_member, search_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), user_name_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), find_by_dn=False)
-    except LdapSearchException, e:
+    except LdapSearchException as e:
       LOG.warn("Failed to find LDAP users: %s" % e)
       LOG.warn("Failed to find LDAP users: %s" % e)
 
 
     for user_info in users_info:
     for user_info in users_info:
@@ -1130,7 +1132,7 @@ def _import_ldap_nested_groups(connection, groupname_pattern, import_members=Fal
   group_info = None
   group_info = None
   try:
   try:
     group_info = connection.find_groups(groupname_pattern, find_by_dn=import_by_dn, scope=scope)
     group_info = connection.find_groups(groupname_pattern, find_by_dn=import_by_dn, scope=scope)
-  except LdapSearchException, e:
+  except LdapSearchException as e:
     LOG.warn("Failed to find LDAP group: %s" % e)
     LOG.warn("Failed to find LDAP group: %s" % e)
 
 
   if not group_info:
   if not group_info:
@@ -1185,7 +1187,7 @@ def _import_ldap_suboordinate_groups(connection, groupname_pattern, import_membe
   group_info = None
   group_info = None
   try:
   try:
     group_info = connection.find_groups(groupname_pattern, find_by_dn=import_by_dn, scope=scope)
     group_info = connection.find_groups(groupname_pattern, find_by_dn=import_by_dn, scope=scope)
-  except LdapSearchException, e:
+  except LdapSearchException as e:
     LOG.warn("Could not find LDAP group: %s" % e)
     LOG.warn("Could not find LDAP group: %s" % e)
 
 
   if not group_info:
   if not group_info:
@@ -1216,7 +1218,7 @@ def _import_ldap_suboordinate_groups(connection, groupname_pattern, import_membe
         group_info = []
         group_info = []
         try:
         try:
           group_info = connection.find_groups(ldap_info['dn'], find_by_dn=True)
           group_info = connection.find_groups(ldap_info['dn'], find_by_dn=True)
-        except LdapSearchException, e:
+        except LdapSearchException as e:
           LOG.warn("Failed to find LDAP group: %s" % e)
           LOG.warn("Failed to find LDAP group: %s" % e)
 
 
         for sub_ldap_info in group_info:
         for sub_ldap_info in group_info:
@@ -1233,7 +1235,7 @@ def _import_ldap_suboordinate_groups(connection, groupname_pattern, import_membe
         user_info = []
         user_info = []
         try:
         try:
           user_info = connection.find_users(member, find_by_dn=True)
           user_info = connection.find_users(member, find_by_dn=True)
-        except LdapSearchException, e:
+        except LdapSearchException as e:
           LOG.warn("Failed to find LDAP user: %s" % e)
           LOG.warn("Failed to find LDAP user: %s" % e)
 
 
         if user_info is None:
         if user_info is None:
@@ -1247,7 +1249,7 @@ def _import_ldap_suboordinate_groups(connection, groupname_pattern, import_membe
               validate_username(ldap_info['username'])
               validate_username(ldap_info['username'])
               user = ldap_access.get_ldap_user(username=ldap_info['username'])
               user = ldap_access.get_ldap_user(username=ldap_info['username'])
               group.user_set.add(user)
               group.user_set.add(user)
-            except ValidationError, e:
+            except ValidationError as e:
               if failed_users is None:
               if failed_users is None:
                 failed_users = []
                 failed_users = []
               failed_users.append(ldap_info['username'])
               failed_users.append(ldap_info['username'])
@@ -1260,19 +1262,19 @@ def _import_ldap_suboordinate_groups(connection, groupname_pattern, import_membe
     if posix_members:
     if posix_members:
       if import_members:
       if import_members:
         for posix_member in posix_members:
         for posix_member in posix_members:
-          LOG.debug("Importing user %s" % str(posix_member))
+          LOG.debug("Importing user %s" % smart_str(posix_member))
           # posixGroup class defines 'memberUid' to be login names,
           # posixGroup class defines 'memberUid' to be login names,
           # which are defined by 'uid'.
           # which are defined by 'uid'.
           user_info = None
           user_info = None
           try:
           try:
             user_info = connection.find_users(posix_member, search_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), user_name_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), find_by_dn=False)
             user_info = connection.find_users(posix_member, search_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), user_name_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), find_by_dn=False)
-          except LdapSearchException, e:
+          except LdapSearchException as e:
             LOG.warn("Failed to find LDAP user: %s" % e)
             LOG.warn("Failed to find LDAP user: %s" % e)
 
 
           if user_info:
           if user_info:
             users = _import_ldap_users_info(connection, user_info, import_by_dn=False, failed_users=failed_users)
             users = _import_ldap_users_info(connection, user_info, import_by_dn=False, failed_users=failed_users)
             if users:
             if users:
-              LOG.debug("Adding member %s represented as users (should be a single user) %s to group %s" % (str(posix_member), str(users), str(group.name)))
+              LOG.debug("Adding member %s represented as users (should be a single user) %s to group %s" % (smart_str(posix_member), smart_str(users), smart_str(group.name)))
               group.user_set.add(*users)
               group.user_set.add(*users)
 
 
       if sync_users:
       if sync_users:
@@ -1280,7 +1282,7 @@ def _import_ldap_suboordinate_groups(connection, groupname_pattern, import_membe
           user_info = []
           user_info = []
           try:
           try:
             user_info = connection.find_users(posix_member, search_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), user_name_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), find_by_dn=False)
             user_info = connection.find_users(posix_member, search_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), user_name_attr=desktop.conf.LDAP.USERS.USER_NAME_ATTR.get(), find_by_dn=False)
-          except LdapSearchException, e:
+          except LdapSearchException as e:
             LOG.warn("Failed to find LDAP user: %s" % e)
             LOG.warn("Failed to find LDAP user: %s" % e)
 
 
           if len(user_info) > 1:
           if len(user_info) > 1:
@@ -1291,7 +1293,7 @@ def _import_ldap_suboordinate_groups(connection, groupname_pattern, import_membe
                 validate_username(ldap_info['username'])
                 validate_username(ldap_info['username'])
                 user = ldap_access.get_ldap_user(username=ldap_info['username'])
                 user = ldap_access.get_ldap_user(username=ldap_info['username'])
                 group.user_set.add(user)
                 group.user_set.add(user)
-              except ValidationError, e:
+              except ValidationError as e:
                 if failed_users is None:
                 if failed_users is None:
                   failed_users = []
                   failed_users = []
                 failed_users.append(ldap_info['username'])
                 failed_users.append(ldap_info['username'])