Fix up new Django 3.0 deprecations

Mostly text based: force/smart_text, ugettext_*
This commit is contained in:
Jeff Bradberry
2022-01-31 13:05:25 -05:00
parent efff85bc1f
commit a3a216f91f
91 changed files with 406 additions and 406 deletions

View File

@@ -6,7 +6,7 @@ import logging
# Django # Django
from django.conf import settings from django.conf import settings
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
# Django REST Framework # Django REST Framework
from rest_framework import authentication from rest_framework import authentication
@@ -24,7 +24,7 @@ class LoggedBasicAuthentication(authentication.BasicAuthentication):
ret = super(LoggedBasicAuthentication, self).authenticate(request) ret = super(LoggedBasicAuthentication, self).authenticate(request)
if ret: if ret:
username = ret[0].username if ret[0] else '<none>' username = ret[0].username if ret[0] else '<none>'
logger.info(smart_text(u"User {} performed a {} to {} through the API".format(username, request.method, request.path))) logger.info(smart_str(u"User {} performed a {} to {} through the API".format(username, request.method, request.path)))
return ret return ret
def authenticate_header(self, request): def authenticate_header(self, request):
@@ -45,7 +45,7 @@ class LoggedOAuth2Authentication(OAuth2Authentication):
user, token = ret user, token = ret
username = user.username if user else '<none>' username = user.username if user else '<none>'
logger.info( logger.info(
smart_text(u"User {} performed a {} to {} through the API using OAuth 2 token {}.".format(username, request.method, request.path, token.pk)) smart_str(u"User {} performed a {} to {} through the API using OAuth 2 token {}.".format(username, request.method, request.path, token.pk))
) )
setattr(user, 'oauth_scopes', [x for x in token.scope.split() if x]) setattr(user, 'oauth_scopes', [x for x in token.scope.split() if x])
return ret return ret

View File

@@ -1,6 +1,6 @@
# Django # Django
from django.conf import settings from django.conf import settings
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework import serializers from rest_framework import serializers

View File

@@ -2,7 +2,7 @@
# All Rights Reserved. # All Rights Reserved.
# Django # Django
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework.exceptions import ValidationError from rest_framework.exceptions import ValidationError
@@ -13,7 +13,7 @@ class ActiveJobConflict(ValidationError):
def __init__(self, active_jobs): def __init__(self, active_jobs):
# During APIException.__init__(), Django Rest Framework # During APIException.__init__(), Django Rest Framework
# turn everything in self.detail into string by using force_text. # turn everything in self.detail into string by using force_str.
# Declare detail afterwards circumvent this behavior. # Declare detail afterwards circumvent this behavior.
super(ActiveJobConflict, self).__init__() super(ActiveJobConflict, self).__init__()
self.detail = {"error": _("Resource is being used by running jobs."), "active_jobs": active_jobs} self.detail = {"error": _("Resource is being used by running jobs."), "active_jobs": active_jobs}

View File

@@ -2,7 +2,7 @@
# All Rights Reserved. # All Rights Reserved.
# Django # Django
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
# Django REST Framework # Django REST Framework

View File

@@ -14,8 +14,8 @@ from django.db.models.fields import FieldDoesNotExist
from django.db.models.fields.related import ForeignObjectRel, ManyToManyField, ForeignKey from django.db.models.fields.related import ForeignObjectRel, ManyToManyField, ForeignKey
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.fields import GenericForeignKey
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework.exceptions import ParseError, PermissionDenied from rest_framework.exceptions import ParseError, PermissionDenied
@@ -185,7 +185,7 @@ class FieldLookupBackend(BaseFilterBackend):
return (field_list[-1], new_lookup) return (field_list[-1], new_lookup)
def to_python_related(self, value): def to_python_related(self, value):
value = force_text(value) value = force_str(value)
if value.lower() in ('none', 'null'): if value.lower() in ('none', 'null'):
return None return None
else: else:
@@ -293,7 +293,7 @@ class FieldLookupBackend(BaseFilterBackend):
search_filter_relation = 'AND' search_filter_relation = 'AND'
values = reduce(lambda list1, list2: list1 + list2, [i.split(',') for i in values]) values = reduce(lambda list1, list2: list1 + list2, [i.split(',') for i in values])
for value in values: for value in values:
search_value, new_keys, _ = self.value_to_python(queryset.model, key, force_text(value)) search_value, new_keys, _ = self.value_to_python(queryset.model, key, force_str(value))
assert isinstance(new_keys, list) assert isinstance(new_keys, list)
search_filters[search_value] = new_keys search_filters[search_value] = new_keys
# by definition, search *only* joins across relations, # by definition, search *only* joins across relations,

View File

@@ -17,10 +17,10 @@ from django.db.models.fields.related import OneToOneRel
from django.http import QueryDict from django.http import QueryDict
from django.shortcuts import get_object_or_404 from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.contrib.auth import views as auth_views from django.contrib.auth import views as auth_views
# Django REST Framework # Django REST Framework
@@ -93,10 +93,10 @@ class LoggedLoginView(auth_views.LoginView):
ret = super(LoggedLoginView, self).post(request, *args, **kwargs) ret = super(LoggedLoginView, self).post(request, *args, **kwargs)
current_user = getattr(request, 'user', None) current_user = getattr(request, 'user', None)
if request.user.is_authenticated: if request.user.is_authenticated:
logger.info(smart_text(u"User {} logged in from {}".format(self.request.user.username, request.META.get('REMOTE_ADDR', None)))) logger.info(smart_str(u"User {} logged in from {}".format(self.request.user.username, request.META.get('REMOTE_ADDR', None))))
ret.set_cookie('userLoggedIn', 'true') ret.set_cookie('userLoggedIn', 'true')
current_user = UserSerializer(self.request.user) current_user = UserSerializer(self.request.user)
current_user = smart_text(JSONRenderer().render(current_user.data)) current_user = smart_str(JSONRenderer().render(current_user.data))
current_user = urllib.parse.quote('%s' % current_user, '') current_user = urllib.parse.quote('%s' % current_user, '')
ret.set_cookie('current_user', current_user, secure=settings.SESSION_COOKIE_SECURE or None) ret.set_cookie('current_user', current_user, secure=settings.SESSION_COOKIE_SECURE or None)
ret.setdefault('X-API-Session-Cookie-Name', getattr(settings, 'SESSION_COOKIE_NAME', 'awx_sessionid')) ret.setdefault('X-API-Session-Cookie-Name', getattr(settings, 'SESSION_COOKIE_NAME', 'awx_sessionid'))
@@ -104,7 +104,7 @@ class LoggedLoginView(auth_views.LoginView):
return ret return ret
else: else:
if 'username' in self.request.POST: if 'username' in self.request.POST:
logger.warn(smart_text(u"Login failed for user {} from {}".format(self.request.POST.get('username'), request.META.get('REMOTE_ADDR', None)))) logger.warn(smart_str(u"Login failed for user {} from {}".format(self.request.POST.get('username'), request.META.get('REMOTE_ADDR', None))))
ret.status_code = 401 ret.status_code = 401
return ret return ret
@@ -392,8 +392,8 @@ class GenericAPIView(generics.GenericAPIView, APIView):
if hasattr(self.model._meta, "verbose_name"): if hasattr(self.model._meta, "verbose_name"):
d.update( d.update(
{ {
'model_verbose_name': smart_text(self.model._meta.verbose_name), 'model_verbose_name': smart_str(self.model._meta.verbose_name),
'model_verbose_name_plural': smart_text(self.model._meta.verbose_name_plural), 'model_verbose_name_plural': smart_str(self.model._meta.verbose_name_plural),
} }
) )
serializer = self.get_serializer() serializer = self.get_serializer()
@@ -524,8 +524,8 @@ class SubListAPIView(ParentMixin, ListAPIView):
d = super(SubListAPIView, self).get_description_context() d = super(SubListAPIView, self).get_description_context()
d.update( d.update(
{ {
'parent_model_verbose_name': smart_text(self.parent_model._meta.verbose_name), 'parent_model_verbose_name': smart_str(self.parent_model._meta.verbose_name),
'parent_model_verbose_name_plural': smart_text(self.parent_model._meta.verbose_name_plural), 'parent_model_verbose_name_plural': smart_str(self.parent_model._meta.verbose_name_plural),
} }
) )
return d return d

View File

@@ -9,8 +9,8 @@ from django.core.exceptions import PermissionDenied
from django.db.models.fields import PositiveIntegerField, BooleanField from django.db.models.fields import PositiveIntegerField, BooleanField
from django.db.models.fields.related import ForeignKey from django.db.models.fields.related import ForeignKey
from django.http import Http404 from django.http import Http404
from django.utils.encoding import force_text, smart_text from django.utils.encoding import force_str, smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework import exceptions from rest_framework import exceptions
@@ -53,7 +53,7 @@ class Metadata(metadata.SimpleMetadata):
for attr in text_attrs: for attr in text_attrs:
value = getattr(field, attr, None) value = getattr(field, attr, None)
if value is not None and value != '': if value is not None and value != '':
field_info[attr] = force_text(value, strings_only=True) field_info[attr] = force_str(value, strings_only=True)
placeholder = getattr(field, 'placeholder', serializers.empty) placeholder = getattr(field, 'placeholder', serializers.empty)
if placeholder is not serializers.empty: if placeholder is not serializers.empty:
@@ -77,7 +77,7 @@ class Metadata(metadata.SimpleMetadata):
} }
if field.field_name in field_help_text: if field.field_name in field_help_text:
opts = serializer.Meta.model._meta.concrete_model._meta opts = serializer.Meta.model._meta.concrete_model._meta
verbose_name = smart_text(opts.verbose_name) verbose_name = smart_str(opts.verbose_name)
field_info['help_text'] = field_help_text[field.field_name].format(verbose_name) field_info['help_text'] = field_help_text[field.field_name].format(verbose_name)
if field.field_name == 'type': if field.field_name == 'type':

View File

@@ -5,7 +5,7 @@ import json
# Django # Django
from django.conf import settings from django.conf import settings
from django.utils.encoding import smart_str from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework import parsers from rest_framework import parsers

View File

@@ -25,8 +25,8 @@ from django.contrib.auth.password_validation import validate_password as django_
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist, ValidationError as DjangoValidationError from django.core.exceptions import ObjectDoesNotExist, ValidationError as DjangoValidationError
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.text import capfirst from django.utils.text import capfirst
from django.utils.timezone import now from django.utils.timezone import now
from django.utils.functional import cached_property from django.utils.functional import cached_property
@@ -357,7 +357,7 @@ class BaseSerializer(serializers.ModelSerializer, metaclass=BaseSerializerMetacl
} }
choices = [] choices = []
for t in self.get_types(): for t in self.get_types():
name = _(type_name_map.get(t, force_text(get_model_for_type(t)._meta.verbose_name).title())) name = _(type_name_map.get(t, force_str(get_model_for_type(t)._meta.verbose_name).title()))
choices.append((t, name)) choices.append((t, name))
return choices return choices
@@ -645,7 +645,7 @@ class BaseSerializer(serializers.ModelSerializer, metaclass=BaseSerializerMetacl
v2.extend(e) v2.extend(e)
else: else:
v2.append(e) v2.append(e)
d[k] = list(map(force_text, v2)) d[k] = list(map(force_str, v2))
raise ValidationError(d) raise ValidationError(d)
return attrs return attrs
@@ -1847,11 +1847,11 @@ class HostSerializer(BaseSerializerWithVariables):
if port < 1 or port > 65535: if port < 1 or port > 65535:
raise ValueError raise ValueError
except ValueError: except ValueError:
raise serializers.ValidationError(_(u'Invalid port specification: %s') % force_text(port)) raise serializers.ValidationError(_(u'Invalid port specification: %s') % force_str(port))
return name, port return name, port
def validate_name(self, value): def validate_name(self, value):
name = force_text(value or '') name = force_str(value or '')
# Validate here only, update in main validate method. # Validate here only, update in main validate method.
host, port = self._get_host_port_from_name(name) host, port = self._get_host_port_from_name(name)
return value return value
@@ -1865,13 +1865,13 @@ class HostSerializer(BaseSerializerWithVariables):
return vars_validate_or_raise(value) return vars_validate_or_raise(value)
def validate(self, attrs): def validate(self, attrs):
name = force_text(attrs.get('name', self.instance and self.instance.name or '')) name = force_str(attrs.get('name', self.instance and self.instance.name or ''))
inventory = attrs.get('inventory', self.instance and self.instance.inventory or '') inventory = attrs.get('inventory', self.instance and self.instance.inventory or '')
host, port = self._get_host_port_from_name(name) host, port = self._get_host_port_from_name(name)
if port: if port:
attrs['name'] = host attrs['name'] = host
variables = force_text(attrs.get('variables', self.instance and self.instance.variables or '')) variables = force_str(attrs.get('variables', self.instance and self.instance.variables or ''))
vars_dict = parse_yaml_or_json(variables) vars_dict = parse_yaml_or_json(variables)
vars_dict['ansible_ssh_port'] = port vars_dict['ansible_ssh_port'] = port
attrs['variables'] = json.dumps(vars_dict) attrs['variables'] = json.dumps(vars_dict)
@@ -1944,7 +1944,7 @@ class GroupSerializer(BaseSerializerWithVariables):
return res return res
def validate(self, attrs): def validate(self, attrs):
name = force_text(attrs.get('name', self.instance and self.instance.name or '')) name = force_str(attrs.get('name', self.instance and self.instance.name or ''))
inventory = attrs.get('inventory', self.instance and self.instance.inventory or '') inventory = attrs.get('inventory', self.instance and self.instance.inventory or '')
if Host.objects.filter(name=name, inventory=inventory).exists(): if Host.objects.filter(name=name, inventory=inventory).exists():
raise serializers.ValidationError(_('A Host with that name already exists.')) raise serializers.ValidationError(_('A Host with that name already exists.'))
@@ -2838,8 +2838,8 @@ class JobOptionsSerializer(LabelsListMixin, BaseSerializer):
if not project: if not project:
raise serializers.ValidationError({'project': _('This field is required.')}) raise serializers.ValidationError({'project': _('This field is required.')})
playbook_not_found = bool( playbook_not_found = bool(
(project and project.scm_type and (not project.allow_override) and playbook and force_text(playbook) not in project.playbook_files) (project and project.scm_type and (not project.allow_override) and playbook and force_str(playbook) not in project.playbook_files)
or (project and not project.scm_type and playbook and force_text(playbook) not in project.playbooks) # manual or (project and not project.scm_type and playbook and force_str(playbook) not in project.playbooks) # manual
) )
if playbook_not_found: if playbook_not_found:
raise serializers.ValidationError({'playbook': _('Playbook not found for project.')}) raise serializers.ValidationError({'playbook': _('Playbook not found for project.')})

View File

@@ -29,7 +29,7 @@ from django.views.decorators.csrf import csrf_exempt
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.http import HttpResponse from django.http import HttpResponse
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework

View File

@@ -8,7 +8,7 @@ import logging
from django.conf import settings from django.conf import settings
from django.db.models import Q from django.db.models import Q
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework.exceptions import PermissionDenied from rest_framework.exceptions import PermissionDenied

View File

@@ -1,7 +1,7 @@
# Copyright (c) 2018 Red Hat, Inc. # Copyright (c) 2018 Red Hat, Inc.
# All Rights Reserved. # All Rights Reserved.
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.api.generics import APIView, Response from awx.api.generics import APIView, Response
from awx.api.permissions import IsSystemAdminOrAuditor from awx.api.permissions import IsSystemAdminOrAuditor

View File

@@ -5,7 +5,7 @@
import logging import logging
# Django # Django
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework.response import Response from rest_framework.response import Response

View File

@@ -8,7 +8,7 @@ from django.db.models import Count
from django.db import transaction from django.db import transaction
from django.shortcuts import get_object_or_404 from django.shortcuts import get_object_or_404
from django.utils.timezone import now from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from rest_framework.permissions import SAFE_METHODS from rest_framework.permissions import SAFE_METHODS
from rest_framework.exceptions import PermissionDenied from rest_framework.exceptions import PermissionDenied

View File

@@ -7,7 +7,7 @@ import logging
# Django # Django
from django.db.models import Count from django.db.models import Count
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# AWX # AWX
from awx.main.models import ( from awx.main.models import (

View File

@@ -8,11 +8,11 @@ import operator
from collections import OrderedDict from collections import OrderedDict
from django.conf import settings from django.conf import settings
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.decorators import method_decorator from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie from django.views.decorators.csrf import ensure_csrf_cookie
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response from rest_framework.response import Response
@@ -205,7 +205,7 @@ class ApiV2SubscriptionView(APIView):
elif isinstance(exc, (ValueError, OSError)) and exc.args: elif isinstance(exc, (ValueError, OSError)) and exc.args:
msg = exc.args[0] msg = exc.args[0]
else: else:
logger.exception(smart_text(u"Invalid subscription submitted."), extra=dict(actor=request.user.username)) logger.exception(smart_str(u"Invalid subscription submitted."), extra=dict(actor=request.user.username))
return Response({"error": msg}, status=status.HTTP_400_BAD_REQUEST) return Response({"error": msg}, status=status.HTTP_400_BAD_REQUEST)
return Response(validated) return Response(validated)
@@ -246,7 +246,7 @@ class ApiV2AttachView(APIView):
elif isinstance(exc, (ValueError, OSError)) and exc.args: elif isinstance(exc, (ValueError, OSError)) and exc.args:
msg = exc.args[0] msg = exc.args[0]
else: else:
logger.exception(smart_text(u"Invalid subscription submitted."), extra=dict(actor=request.user.username)) logger.exception(smart_str(u"Invalid subscription submitted."), extra=dict(actor=request.user.username))
return Response({"error": msg}, status=status.HTTP_400_BAD_REQUEST) return Response({"error": msg}, status=status.HTTP_400_BAD_REQUEST)
for sub in validated: for sub in validated:
if sub['pool_id'] == pool_id: if sub['pool_id'] == pool_id:
@@ -322,7 +322,7 @@ class ApiV2ConfigView(APIView):
try: try:
data_actual = json.dumps(request.data) data_actual = json.dumps(request.data)
except Exception: except Exception:
logger.info(smart_text(u"Invalid JSON submitted for license."), extra=dict(actor=request.user.username)) logger.info(smart_str(u"Invalid JSON submitted for license."), extra=dict(actor=request.user.username))
return Response({"error": _("Invalid JSON")}, status=status.HTTP_400_BAD_REQUEST) return Response({"error": _("Invalid JSON")}, status=status.HTTP_400_BAD_REQUEST)
license_data = json.loads(data_actual) license_data = json.loads(data_actual)
@@ -346,7 +346,7 @@ class ApiV2ConfigView(APIView):
try: try:
license_data_validated = get_licenser().license_from_manifest(license_data) license_data_validated = get_licenser().license_from_manifest(license_data)
except Exception: except Exception:
logger.warning(smart_text(u"Invalid subscription submitted."), extra=dict(actor=request.user.username)) logger.warning(smart_str(u"Invalid subscription submitted."), extra=dict(actor=request.user.username))
return Response({"error": _("Invalid License")}, status=status.HTTP_400_BAD_REQUEST) return Response({"error": _("Invalid License")}, status=status.HTTP_400_BAD_REQUEST)
else: else:
license_data_validated = get_licenser().validate() license_data_validated = get_licenser().validate()
@@ -357,7 +357,7 @@ class ApiV2ConfigView(APIView):
settings.TOWER_URL_BASE = "{}://{}".format(request.scheme, request.get_host()) settings.TOWER_URL_BASE = "{}://{}".format(request.scheme, request.get_host())
return Response(license_data_validated) return Response(license_data_validated)
logger.warning(smart_text(u"Invalid subscription submitted."), extra=dict(actor=request.user.username)) logger.warning(smart_str(u"Invalid subscription submitted."), extra=dict(actor=request.user.username))
return Response({"error": _("Invalid subscription")}, status=status.HTTP_400_BAD_REQUEST) return Response({"error": _("Invalid subscription")}, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request): def delete(self, request):

View File

@@ -4,7 +4,7 @@ import logging
import urllib.parse import urllib.parse
from django.utils.encoding import force_bytes from django.utils.encoding import force_bytes
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from rest_framework import status from rest_framework import status

View File

@@ -2,7 +2,7 @@
from django.apps import AppConfig from django.apps import AppConfig
# from django.core import checks # from django.core import checks
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
class ConfConfig(AppConfig): class ConfConfig(AppConfig):

View File

@@ -1,6 +1,6 @@
# Django # Django
from django.conf import settings from django.conf import settings
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# AWX # AWX
from awx.conf import fields, register from awx.conf import fields, register

View File

@@ -7,7 +7,7 @@ from collections import OrderedDict
# Django # Django
from django.core.validators import URLValidator, _lazy_re_compile from django.core.validators import URLValidator, _lazy_re_compile
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework.fields import BooleanField, CharField, ChoiceField, DictField, DateTimeField, EmailField, IntegerField, ListField, NullBooleanField # noqa from rest_framework.fields import BooleanField, CharField, ChoiceField, DictField, DateTimeField, EmailField, IntegerField, ListField, NullBooleanField # noqa

View File

@@ -8,7 +8,7 @@ import logging
# Django # Django
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.utils.text import slugify from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.conf.license import get_license from awx.conf.license import get_license

View File

@@ -6,7 +6,7 @@ from uuid import uuid4
from django.conf import LazySettings from django.conf import LazySettings
from django.core.cache.backends.locmem import LocMemCache from django.core.cache.backends.locmem import LocMemCache
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from rest_framework.fields import empty from rest_framework.fields import empty
import pytest import pytest

View File

@@ -11,7 +11,7 @@ import time
from django.conf import LazySettings from django.conf import LazySettings
from django.core.cache.backends.locmem import LocMemCache from django.core.cache.backends.locmem import LocMemCache
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
import pytest import pytest
from awx.conf import models, fields from awx.conf import models, fields

View File

@@ -13,7 +13,7 @@ from socket import SHUT_RDWR
from django.db import connection from django.db import connection
from django.conf import settings from django.conf import settings
from django.http import Http404 from django.http import Http404
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework.exceptions import PermissionDenied from rest_framework.exceptions import PermissionDenied

View File

@@ -11,7 +11,7 @@ from functools import reduce
from django.conf import settings from django.conf import settings
from django.db.models import Q, Prefetch from django.db.models import Q, Prefetch
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
# Django REST Framework # Django REST Framework

View File

@@ -10,7 +10,7 @@ from django.db.models import Count
from django.conf import settings from django.conf import settings
from django.contrib.sessions.models import Session from django.contrib.sessions.models import Session
from django.utils.timezone import now, timedelta from django.utils.timezone import now, timedelta
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from psycopg2.errors import UntranslatableCharacter from psycopg2.errors import UntranslatableCharacter

View File

@@ -1,5 +1,5 @@
from django.apps import AppConfig from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
class MainConfig(AppConfig): class MainConfig(AppConfig):

View File

@@ -2,7 +2,7 @@
import logging import logging
# Django # Django
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework import serializers from rest_framework import serializers

View File

@@ -3,7 +3,7 @@
import re import re
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
__all__ = [ __all__ = [
'CLOUD_PROVIDERS', 'CLOUD_PROVIDERS',

View File

@@ -2,7 +2,7 @@ from .plugin import CredentialPlugin, CertFiles, raise_for_status
from urllib.parse import quote, urlencode, urljoin from urllib.parse import quote, urlencode, urljoin
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
import requests import requests
aim_inputs = { aim_inputs = {

View File

@@ -1,6 +1,6 @@
from .plugin import CredentialPlugin from .plugin import CredentialPlugin
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from azure.keyvault import KeyVaultClient, KeyVaultAuthentication from azure.keyvault import KeyVaultClient, KeyVaultAuthentication
from azure.common.credentials import ServicePrincipalCredentials from azure.common.credentials import ServicePrincipalCredentials
from msrestazure import azure_cloud from msrestazure import azure_cloud

View File

@@ -1,5 +1,5 @@
from .plugin import CredentialPlugin, raise_for_status from .plugin import CredentialPlugin, raise_for_status
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from urllib.parse import urljoin from urllib.parse import urljoin
import requests import requests

View File

@@ -3,7 +3,7 @@ from .plugin import CredentialPlugin, CertFiles, raise_for_status
import base64 import base64
from urllib.parse import urljoin, quote from urllib.parse import urljoin, quote
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
import requests import requests

View File

@@ -1,7 +1,7 @@
from .plugin import CredentialPlugin from .plugin import CredentialPlugin
from django.conf import settings from django.conf import settings
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from thycotic.secrets.vault import SecretsVault from thycotic.secrets.vault import SecretsVault

View File

@@ -6,7 +6,7 @@ from urllib.parse import urljoin
from .plugin import CredentialPlugin, CertFiles, raise_for_status from .plugin import CredentialPlugin, CertFiles, raise_for_status
import requests import requests
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
base_inputs = { base_inputs = {
'fields': [ 'fields': [

View File

@@ -1,5 +1,5 @@
from .plugin import CredentialPlugin from .plugin import CredentialPlugin
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from thycotic.secrets.server import PasswordGrantAuthorizer, SecretServer, ServerSecret from thycotic.secrets.server import PasswordGrantAuthorizer, SecretServer, ServerSecret

View File

@@ -28,9 +28,9 @@ from django.db.models.fields.related_descriptors import (
ReverseManyToOneDescriptor, ReverseManyToOneDescriptor,
create_forward_many_to_many_manager, create_forward_many_to_many_manager,
) )
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.functional import cached_property from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# jsonschema # jsonschema
from jsonschema import Draft4Validator, FormatChecker from jsonschema import Draft4Validator, FormatChecker
@@ -144,7 +144,7 @@ def resolve_role_field(obj, field):
# use extremely generous duck typing to accomidate all possible forms # use extremely generous duck typing to accomidate all possible forms
# of the model that may be used during various migrations # of the model that may be used during various migrations
if obj._meta.model_name != 'role' or obj._meta.app_label != 'main': if obj._meta.model_name != 'role' or obj._meta.app_label != 'main':
raise Exception(smart_text('{} refers to a {}, not a Role'.format(field, type(obj)))) raise Exception(smart_str('{} refers to a {}, not a Role'.format(field, type(obj))))
ret.append(obj.id) ret.append(obj.id)
else: else:
if type(obj) is ManyToManyDescriptor: if type(obj) is ManyToManyDescriptor:

View File

@@ -16,7 +16,7 @@ from collections import OrderedDict
from django.conf import settings from django.conf import settings
from django.core.management.base import BaseCommand, CommandError from django.core.management.base import BaseCommand, CommandError
from django.db import connection, transaction from django.db import connection, transaction
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
# DRF error class to distinguish license exceptions # DRF error class to distinguish license exceptions
from rest_framework.exceptions import PermissionDenied from rest_framework.exceptions import PermissionDenied
@@ -109,8 +109,8 @@ class AnsibleInventoryLoader(object):
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate() stdout, stderr = proc.communicate()
stdout = smart_text(stdout) stdout = smart_str(stdout)
stderr = smart_text(stderr) stderr = smart_str(stderr)
if proc.returncode != 0: if proc.returncode != 0:
raise RuntimeError('%s failed (rc=%d) with stdout:\n%s\nstderr:\n%s' % ('ansible-inventory', proc.returncode, stdout, stderr)) raise RuntimeError('%s failed (rc=%d) with stdout:\n%s\nstderr:\n%s' % ('ansible-inventory', proc.returncode, stdout, stderr))
@@ -224,7 +224,7 @@ class Command(BaseCommand):
from_dict = instance_id from_dict = instance_id
if instance_id: if instance_id:
break break
return smart_text(instance_id) return smart_str(instance_id)
def _get_enabled(self, from_dict, default=None): def _get_enabled(self, from_dict, default=None):
""" """

View File

@@ -14,7 +14,7 @@ from django.db import connection
from django.shortcuts import redirect from django.shortcuts import redirect
from django.apps import apps from django.apps import apps
from django.utils.deprecation import MiddlewareMixin from django.utils.deprecation import MiddlewareMixin
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.urls import reverse, resolve from django.urls import reverse, resolve
from awx.main.utils.named_url_graph import generate_graph, GraphNode from awx.main.utils.named_url_graph import generate_graph, GraphNode

View File

@@ -1,6 +1,6 @@
import logging import logging
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from awx.main.utils.common import set_current_apps from awx.main.utils.common import set_current_apps
from awx.main.utils.common import parse_yaml_or_json from awx.main.utils.common import parse_yaml_or_json
@@ -19,7 +19,7 @@ def _get_instance_id(from_dict, new_id, default=''):
break break
instance_id = from_dict.get(key, default) instance_id = from_dict.get(key, default)
from_dict = instance_id from_dict = instance_id
return smart_text(instance_id) return smart_str(instance_id)
def _get_instance_id_for_upgrade(host, new_id): def _get_instance_id_for_upgrade(host, new_id):

View File

@@ -2,7 +2,7 @@ import json
import re import re
import logging import logging
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.encoding import iri_to_uri from django.utils.encoding import iri_to_uri

View File

@@ -10,7 +10,7 @@ from awx.main.models.base import accepts_json
from django.db import models from django.db import models
from django.conf import settings from django.conf import settings
from django.utils.encoding import smart_str from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
__all__ = ['ActivityStream'] __all__ = ['ActivityStream']

View File

@@ -9,7 +9,7 @@ from urllib.parse import urljoin
from django.conf import settings from django.conf import settings
from django.db import models from django.db import models
from django.utils.text import Truncator from django.utils.text import Truncator
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
# AWX # AWX

View File

@@ -4,7 +4,7 @@
# Django # Django
from django.db import models from django.db import models
from django.core.exceptions import ValidationError, ObjectDoesNotExist from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.timezone import now from django.utils.timezone import now
# Django-Taggit # Django-Taggit

View File

@@ -15,9 +15,9 @@ from jinja2 import sandbox
# Django # Django
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _, ugettext_noop from django.utils.translation import gettext_lazy as _, gettext_noop
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.utils.encoding import force_text from django.utils.encoding import force_str
from django.utils.functional import cached_property from django.utils.functional import cached_property
from django.utils.timezone import now from django.utils.timezone import now
@@ -230,7 +230,7 @@ class Credential(PasswordFieldsModel, CommonModelNameNotUnique, ResourceMixin):
def display_inputs(self): def display_inputs(self):
field_val = self.inputs.copy() field_val = self.inputs.copy()
for k, v in field_val.items(): for k, v in field_val.items():
if force_text(v).startswith('$encrypted$'): if force_str(v).startswith('$encrypted$'):
field_val[k] = '$encrypted$' field_val[k] = '$encrypted$'
return field_val return field_val
@@ -579,34 +579,34 @@ class ManagedCredentialType(SimpleNamespace):
ManagedCredentialType( ManagedCredentialType(
namespace='ssh', namespace='ssh',
kind='ssh', kind='ssh',
name=ugettext_noop('Machine'), name=gettext_noop('Machine'),
inputs={ inputs={
'fields': [ 'fields': [
{'id': 'username', 'label': ugettext_noop('Username'), 'type': 'string'}, {'id': 'username', 'label': gettext_noop('Username'), 'type': 'string'},
{'id': 'password', 'label': ugettext_noop('Password'), 'type': 'string', 'secret': True, 'ask_at_runtime': True}, {'id': 'password', 'label': gettext_noop('Password'), 'type': 'string', 'secret': True, 'ask_at_runtime': True},
{'id': 'ssh_key_data', 'label': ugettext_noop('SSH Private Key'), 'type': 'string', 'format': 'ssh_private_key', 'secret': True, 'multiline': True}, {'id': 'ssh_key_data', 'label': gettext_noop('SSH Private Key'), 'type': 'string', 'format': 'ssh_private_key', 'secret': True, 'multiline': True},
{ {
'id': 'ssh_public_key_data', 'id': 'ssh_public_key_data',
'label': ugettext_noop('Signed SSH Certificate'), 'label': gettext_noop('Signed SSH Certificate'),
'type': 'string', 'type': 'string',
'multiline': True, 'multiline': True,
'secret': True, 'secret': True,
}, },
{'id': 'ssh_key_unlock', 'label': ugettext_noop('Private Key Passphrase'), 'type': 'string', 'secret': True, 'ask_at_runtime': True}, {'id': 'ssh_key_unlock', 'label': gettext_noop('Private Key Passphrase'), 'type': 'string', 'secret': True, 'ask_at_runtime': True},
{ {
'id': 'become_method', 'id': 'become_method',
'label': ugettext_noop('Privilege Escalation Method'), 'label': gettext_noop('Privilege Escalation Method'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop( 'help_text': gettext_noop(
'Specify a method for "become" operations. This is ' 'equivalent to specifying the --become-method ' 'Ansible parameter.' 'Specify a method for "become" operations. This is ' 'equivalent to specifying the --become-method ' 'Ansible parameter.'
), ),
}, },
{ {
'id': 'become_username', 'id': 'become_username',
'label': ugettext_noop('Privilege Escalation Username'), 'label': gettext_noop('Privilege Escalation Username'),
'type': 'string', 'type': 'string',
}, },
{'id': 'become_password', 'label': ugettext_noop('Privilege Escalation Password'), 'type': 'string', 'secret': True, 'ask_at_runtime': True}, {'id': 'become_password', 'label': gettext_noop('Privilege Escalation Password'), 'type': 'string', 'secret': True, 'ask_at_runtime': True},
], ],
}, },
) )
@@ -614,14 +614,14 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='scm', namespace='scm',
kind='scm', kind='scm',
name=ugettext_noop('Source Control'), name=gettext_noop('Source Control'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{'id': 'username', 'label': ugettext_noop('Username'), 'type': 'string'}, {'id': 'username', 'label': gettext_noop('Username'), 'type': 'string'},
{'id': 'password', 'label': ugettext_noop('Password'), 'type': 'string', 'secret': True}, {'id': 'password', 'label': gettext_noop('Password'), 'type': 'string', 'secret': True},
{'id': 'ssh_key_data', 'label': ugettext_noop('SCM Private Key'), 'type': 'string', 'format': 'ssh_private_key', 'secret': True, 'multiline': True}, {'id': 'ssh_key_data', 'label': gettext_noop('SCM Private Key'), 'type': 'string', 'format': 'ssh_private_key', 'secret': True, 'multiline': True},
{'id': 'ssh_key_unlock', 'label': ugettext_noop('Private Key Passphrase'), 'type': 'string', 'secret': True}, {'id': 'ssh_key_unlock', 'label': gettext_noop('Private Key Passphrase'), 'type': 'string', 'secret': True},
], ],
}, },
) )
@@ -629,17 +629,17 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='vault', namespace='vault',
kind='vault', kind='vault',
name=ugettext_noop('Vault'), name=gettext_noop('Vault'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{'id': 'vault_password', 'label': ugettext_noop('Vault Password'), 'type': 'string', 'secret': True, 'ask_at_runtime': True}, {'id': 'vault_password', 'label': gettext_noop('Vault Password'), 'type': 'string', 'secret': True, 'ask_at_runtime': True},
{ {
'id': 'vault_id', 'id': 'vault_id',
'label': ugettext_noop('Vault Identifier'), 'label': gettext_noop('Vault Identifier'),
'type': 'string', 'type': 'string',
'format': 'vault_id', 'format': 'vault_id',
'help_text': ugettext_noop( 'help_text': gettext_noop(
'Specify an (optional) Vault ID. This is ' 'Specify an (optional) Vault ID. This is '
'equivalent to specifying the --vault-id ' 'equivalent to specifying the --vault-id '
'Ansible parameter for providing multiple Vault ' 'Ansible parameter for providing multiple Vault '
@@ -655,32 +655,32 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='net', namespace='net',
kind='net', kind='net',
name=ugettext_noop('Network'), name=gettext_noop('Network'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{'id': 'username', 'label': ugettext_noop('Username'), 'type': 'string'}, {'id': 'username', 'label': gettext_noop('Username'), 'type': 'string'},
{ {
'id': 'password', 'id': 'password',
'label': ugettext_noop('Password'), 'label': gettext_noop('Password'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
{'id': 'ssh_key_data', 'label': ugettext_noop('SSH Private Key'), 'type': 'string', 'format': 'ssh_private_key', 'secret': True, 'multiline': True}, {'id': 'ssh_key_data', 'label': gettext_noop('SSH Private Key'), 'type': 'string', 'format': 'ssh_private_key', 'secret': True, 'multiline': True},
{ {
'id': 'ssh_key_unlock', 'id': 'ssh_key_unlock',
'label': ugettext_noop('Private Key Passphrase'), 'label': gettext_noop('Private Key Passphrase'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
{ {
'id': 'authorize', 'id': 'authorize',
'label': ugettext_noop('Authorize'), 'label': gettext_noop('Authorize'),
'type': 'boolean', 'type': 'boolean',
}, },
{ {
'id': 'authorize_password', 'id': 'authorize_password',
'label': ugettext_noop('Authorize Password'), 'label': gettext_noop('Authorize Password'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
@@ -695,23 +695,23 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='aws', namespace='aws',
kind='cloud', kind='cloud',
name=ugettext_noop('Amazon Web Services'), name=gettext_noop('Amazon Web Services'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{'id': 'username', 'label': ugettext_noop('Access Key'), 'type': 'string'}, {'id': 'username', 'label': gettext_noop('Access Key'), 'type': 'string'},
{ {
'id': 'password', 'id': 'password',
'label': ugettext_noop('Secret Key'), 'label': gettext_noop('Secret Key'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
{ {
'id': 'security_token', 'id': 'security_token',
'label': ugettext_noop('STS Token'), 'label': gettext_noop('STS Token'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
'help_text': ugettext_noop( 'help_text': gettext_noop(
'Security Token Service (STS) is a web service ' 'Security Token Service (STS) is a web service '
'that enables you to request temporary, ' 'that enables you to request temporary, '
'limited-privilege credentials for AWS Identity ' 'limited-privilege credentials for AWS Identity '
@@ -726,38 +726,38 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='openstack', namespace='openstack',
kind='cloud', kind='cloud',
name=ugettext_noop('OpenStack'), name=gettext_noop('OpenStack'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{'id': 'username', 'label': ugettext_noop('Username'), 'type': 'string'}, {'id': 'username', 'label': gettext_noop('Username'), 'type': 'string'},
{ {
'id': 'password', 'id': 'password',
'label': ugettext_noop('Password (API Key)'), 'label': gettext_noop('Password (API Key)'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
{ {
'id': 'host', 'id': 'host',
'label': ugettext_noop('Host (Authentication URL)'), 'label': gettext_noop('Host (Authentication URL)'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('The host to authenticate with. For example, ' 'https://openstack.business.com/v2.0/'), 'help_text': gettext_noop('The host to authenticate with. For example, ' 'https://openstack.business.com/v2.0/'),
}, },
{ {
'id': 'project', 'id': 'project',
'label': ugettext_noop('Project (Tenant Name)'), 'label': gettext_noop('Project (Tenant Name)'),
'type': 'string', 'type': 'string',
}, },
{ {
'id': 'project_domain_name', 'id': 'project_domain_name',
'label': ugettext_noop('Project (Domain Name)'), 'label': gettext_noop('Project (Domain Name)'),
'type': 'string', 'type': 'string',
}, },
{ {
'id': 'domain', 'id': 'domain',
'label': ugettext_noop('Domain Name'), 'label': gettext_noop('Domain Name'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop( 'help_text': gettext_noop(
'OpenStack domains define administrative boundaries. ' 'OpenStack domains define administrative boundaries. '
'It is only needed for Keystone v3 authentication ' 'It is only needed for Keystone v3 authentication '
'URLs. Refer to the documentation for ' 'URLs. Refer to the documentation for '
@@ -766,13 +766,13 @@ ManagedCredentialType(
}, },
{ {
'id': 'region', 'id': 'region',
'label': ugettext_noop('Region Name'), 'label': gettext_noop('Region Name'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('For some cloud providers, like OVH, region must be specified'), 'help_text': gettext_noop('For some cloud providers, like OVH, region must be specified'),
}, },
{ {
'id': 'verify_ssl', 'id': 'verify_ssl',
'label': ugettext_noop('Verify SSL'), 'label': gettext_noop('Verify SSL'),
'type': 'boolean', 'type': 'boolean',
'default': True, 'default': True,
}, },
@@ -784,20 +784,20 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='vmware', namespace='vmware',
kind='cloud', kind='cloud',
name=ugettext_noop('VMware vCenter'), name=gettext_noop('VMware vCenter'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{ {
'id': 'host', 'id': 'host',
'label': ugettext_noop('VCenter Host'), 'label': gettext_noop('VCenter Host'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('Enter the hostname or IP address that corresponds ' 'to your VMware vCenter.'), 'help_text': gettext_noop('Enter the hostname or IP address that corresponds ' 'to your VMware vCenter.'),
}, },
{'id': 'username', 'label': ugettext_noop('Username'), 'type': 'string'}, {'id': 'username', 'label': gettext_noop('Username'), 'type': 'string'},
{ {
'id': 'password', 'id': 'password',
'label': ugettext_noop('Password'), 'label': gettext_noop('Password'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
@@ -809,20 +809,20 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='satellite6', namespace='satellite6',
kind='cloud', kind='cloud',
name=ugettext_noop('Red Hat Satellite 6'), name=gettext_noop('Red Hat Satellite 6'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{ {
'id': 'host', 'id': 'host',
'label': ugettext_noop('Satellite 6 URL'), 'label': gettext_noop('Satellite 6 URL'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('Enter the URL that corresponds to your Red Hat ' 'Satellite 6 server. For example, https://satellite.example.org'), 'help_text': gettext_noop('Enter the URL that corresponds to your Red Hat ' 'Satellite 6 server. For example, https://satellite.example.org'),
}, },
{'id': 'username', 'label': ugettext_noop('Username'), 'type': 'string'}, {'id': 'username', 'label': gettext_noop('Username'), 'type': 'string'},
{ {
'id': 'password', 'id': 'password',
'label': ugettext_noop('Password'), 'label': gettext_noop('Password'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
@@ -834,21 +834,21 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='gce', namespace='gce',
kind='cloud', kind='cloud',
name=ugettext_noop('Google Compute Engine'), name=gettext_noop('Google Compute Engine'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{ {
'id': 'username', 'id': 'username',
'label': ugettext_noop('Service Account Email Address'), 'label': gettext_noop('Service Account Email Address'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('The email address assigned to the Google Compute ' 'Engine service account.'), 'help_text': gettext_noop('The email address assigned to the Google Compute ' 'Engine service account.'),
}, },
{ {
'id': 'project', 'id': 'project',
'label': 'Project', 'label': 'Project',
'type': 'string', 'type': 'string',
'help_text': ugettext_noop( 'help_text': gettext_noop(
'The Project ID is the GCE assigned identification. ' 'The Project ID is the GCE assigned identification. '
'It is often constructed as three words or two words ' 'It is often constructed as three words or two words '
'followed by a three-digit number. Examples: project-id-000 ' 'followed by a three-digit number. Examples: project-id-000 '
@@ -857,12 +857,12 @@ ManagedCredentialType(
}, },
{ {
'id': 'ssh_key_data', 'id': 'ssh_key_data',
'label': ugettext_noop('RSA Private Key'), 'label': gettext_noop('RSA Private Key'),
'type': 'string', 'type': 'string',
'format': 'ssh_private_key', 'format': 'ssh_private_key',
'secret': True, 'secret': True,
'multiline': True, 'multiline': True,
'help_text': ugettext_noop('Paste the contents of the PEM file associated ' 'with the service account email.'), 'help_text': gettext_noop('Paste the contents of the PEM file associated ' 'with the service account email.'),
}, },
], ],
'required': ['username', 'ssh_key_data'], 'required': ['username', 'ssh_key_data'],
@@ -872,36 +872,36 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='azure_rm', namespace='azure_rm',
kind='cloud', kind='cloud',
name=ugettext_noop('Microsoft Azure Resource Manager'), name=gettext_noop('Microsoft Azure Resource Manager'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{ {
'id': 'subscription', 'id': 'subscription',
'label': ugettext_noop('Subscription ID'), 'label': gettext_noop('Subscription ID'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('Subscription ID is an Azure construct, which is ' 'mapped to a username.'), 'help_text': gettext_noop('Subscription ID is an Azure construct, which is ' 'mapped to a username.'),
}, },
{'id': 'username', 'label': ugettext_noop('Username'), 'type': 'string'}, {'id': 'username', 'label': gettext_noop('Username'), 'type': 'string'},
{ {
'id': 'password', 'id': 'password',
'label': ugettext_noop('Password'), 'label': gettext_noop('Password'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
{'id': 'client', 'label': ugettext_noop('Client ID'), 'type': 'string'}, {'id': 'client', 'label': gettext_noop('Client ID'), 'type': 'string'},
{ {
'id': 'secret', 'id': 'secret',
'label': ugettext_noop('Client Secret'), 'label': gettext_noop('Client Secret'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
{'id': 'tenant', 'label': ugettext_noop('Tenant ID'), 'type': 'string'}, {'id': 'tenant', 'label': gettext_noop('Tenant ID'), 'type': 'string'},
{ {
'id': 'cloud_environment', 'id': 'cloud_environment',
'label': ugettext_noop('Azure Cloud Environment'), 'label': gettext_noop('Azure Cloud Environment'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('Environment variable AZURE_CLOUD_ENVIRONMENT when' ' using Azure GovCloud or Azure stack.'), 'help_text': gettext_noop('Environment variable AZURE_CLOUD_ENVIRONMENT when' ' using Azure GovCloud or Azure stack.'),
}, },
], ],
'required': ['subscription'], 'required': ['subscription'],
@@ -911,16 +911,16 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='github_token', namespace='github_token',
kind='token', kind='token',
name=ugettext_noop('GitHub Personal Access Token'), name=gettext_noop('GitHub Personal Access Token'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{ {
'id': 'token', 'id': 'token',
'label': ugettext_noop('Token'), 'label': gettext_noop('Token'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
'help_text': ugettext_noop('This token needs to come from your profile settings in GitHub'), 'help_text': gettext_noop('This token needs to come from your profile settings in GitHub'),
} }
], ],
'required': ['token'], 'required': ['token'],
@@ -930,16 +930,16 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='gitlab_token', namespace='gitlab_token',
kind='token', kind='token',
name=ugettext_noop('GitLab Personal Access Token'), name=gettext_noop('GitLab Personal Access Token'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{ {
'id': 'token', 'id': 'token',
'label': ugettext_noop('Token'), 'label': gettext_noop('Token'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
'help_text': ugettext_noop('This token needs to come from your profile settings in GitLab'), 'help_text': gettext_noop('This token needs to come from your profile settings in GitLab'),
} }
], ],
'required': ['token'], 'required': ['token'],
@@ -949,12 +949,12 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='insights', namespace='insights',
kind='insights', kind='insights',
name=ugettext_noop('Insights'), name=gettext_noop('Insights'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{'id': 'username', 'label': ugettext_noop('Username'), 'type': 'string'}, {'id': 'username', 'label': gettext_noop('Username'), 'type': 'string'},
{'id': 'password', 'label': ugettext_noop('Password'), 'type': 'string', 'secret': True}, {'id': 'password', 'label': gettext_noop('Password'), 'type': 'string', 'secret': True},
], ],
'required': ['username', 'password'], 'required': ['username', 'password'],
}, },
@@ -973,23 +973,23 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='rhv', namespace='rhv',
kind='cloud', kind='cloud',
name=ugettext_noop('Red Hat Virtualization'), name=gettext_noop('Red Hat Virtualization'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{'id': 'host', 'label': ugettext_noop('Host (Authentication URL)'), 'type': 'string', 'help_text': ugettext_noop('The host to authenticate with.')}, {'id': 'host', 'label': gettext_noop('Host (Authentication URL)'), 'type': 'string', 'help_text': gettext_noop('The host to authenticate with.')},
{'id': 'username', 'label': ugettext_noop('Username'), 'type': 'string'}, {'id': 'username', 'label': gettext_noop('Username'), 'type': 'string'},
{ {
'id': 'password', 'id': 'password',
'label': ugettext_noop('Password'), 'label': gettext_noop('Password'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
{ {
'id': 'ca_file', 'id': 'ca_file',
'label': ugettext_noop('CA File'), 'label': gettext_noop('CA File'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('Absolute file path to the CA file to use (optional)'), 'help_text': gettext_noop('Absolute file path to the CA file to use (optional)'),
}, },
], ],
'required': ['host', 'username', 'password'], 'required': ['host', 'username', 'password'],
@@ -1017,38 +1017,38 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='controller', namespace='controller',
kind='cloud', kind='cloud',
name=ugettext_noop('Red Hat Ansible Automation Platform'), name=gettext_noop('Red Hat Ansible Automation Platform'),
managed=True, managed=True,
inputs={ inputs={
'fields': [ 'fields': [
{ {
'id': 'host', 'id': 'host',
'label': ugettext_noop('Red Hat Ansible Automation Platform'), 'label': gettext_noop('Red Hat Ansible Automation Platform'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('Red Hat Ansible Automation Platform base URL to authenticate with.'), 'help_text': gettext_noop('Red Hat Ansible Automation Platform base URL to authenticate with.'),
}, },
{ {
'id': 'username', 'id': 'username',
'label': ugettext_noop('Username'), 'label': gettext_noop('Username'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop( 'help_text': gettext_noop(
'Red Hat Ansible Automation Platform username id to authenticate as.' 'This should not be set if an OAuth token is being used.' 'Red Hat Ansible Automation Platform username id to authenticate as.' 'This should not be set if an OAuth token is being used.'
), ),
}, },
{ {
'id': 'password', 'id': 'password',
'label': ugettext_noop('Password'), 'label': gettext_noop('Password'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
{ {
'id': 'oauth_token', 'id': 'oauth_token',
'label': ugettext_noop('OAuth Token'), 'label': gettext_noop('OAuth Token'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
'help_text': ugettext_noop('An OAuth token to use to authenticate with.' 'This should not be set if username/password are being used.'), 'help_text': gettext_noop('An OAuth token to use to authenticate with.' 'This should not be set if username/password are being used.'),
}, },
{'id': 'verify_ssl', 'label': ugettext_noop('Verify SSL'), 'type': 'boolean', 'secret': False}, {'id': 'verify_ssl', 'label': gettext_noop('Verify SSL'), 'type': 'boolean', 'secret': False},
], ],
'required': ['host'], 'required': ['host'],
}, },
@@ -1071,30 +1071,30 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='kubernetes_bearer_token', namespace='kubernetes_bearer_token',
kind='kubernetes', kind='kubernetes',
name=ugettext_noop('OpenShift or Kubernetes API Bearer Token'), name=gettext_noop('OpenShift or Kubernetes API Bearer Token'),
inputs={ inputs={
'fields': [ 'fields': [
{ {
'id': 'host', 'id': 'host',
'label': ugettext_noop('OpenShift or Kubernetes API Endpoint'), 'label': gettext_noop('OpenShift or Kubernetes API Endpoint'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('The OpenShift or Kubernetes API Endpoint to authenticate with.'), 'help_text': gettext_noop('The OpenShift or Kubernetes API Endpoint to authenticate with.'),
}, },
{ {
'id': 'bearer_token', 'id': 'bearer_token',
'label': ugettext_noop('API authentication bearer token'), 'label': gettext_noop('API authentication bearer token'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
}, },
{ {
'id': 'verify_ssl', 'id': 'verify_ssl',
'label': ugettext_noop('Verify SSL'), 'label': gettext_noop('Verify SSL'),
'type': 'boolean', 'type': 'boolean',
'default': True, 'default': True,
}, },
{ {
'id': 'ssl_ca_cert', 'id': 'ssl_ca_cert',
'label': ugettext_noop('Certificate Authority data'), 'label': gettext_noop('Certificate Authority data'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
'multiline': True, 'multiline': True,
@@ -1107,31 +1107,31 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='registry', namespace='registry',
kind='registry', kind='registry',
name=ugettext_noop('Container Registry'), name=gettext_noop('Container Registry'),
inputs={ inputs={
'fields': [ 'fields': [
{ {
'id': 'host', 'id': 'host',
'label': ugettext_noop('Authentication URL'), 'label': gettext_noop('Authentication URL'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('Authentication endpoint for the container registry.'), 'help_text': gettext_noop('Authentication endpoint for the container registry.'),
'default': 'quay.io', 'default': 'quay.io',
}, },
{ {
'id': 'username', 'id': 'username',
'label': ugettext_noop('Username'), 'label': gettext_noop('Username'),
'type': 'string', 'type': 'string',
}, },
{ {
'id': 'password', 'id': 'password',
'label': ugettext_noop('Password or Token'), 'label': gettext_noop('Password or Token'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
'help_text': ugettext_noop('A password or token used to authenticate with'), 'help_text': gettext_noop('A password or token used to authenticate with'),
}, },
{ {
'id': 'verify_ssl', 'id': 'verify_ssl',
'label': ugettext_noop('Verify SSL'), 'label': gettext_noop('Verify SSL'),
'type': 'boolean', 'type': 'boolean',
'default': True, 'default': True,
}, },
@@ -1144,27 +1144,27 @@ ManagedCredentialType(
ManagedCredentialType( ManagedCredentialType(
namespace='galaxy_api_token', namespace='galaxy_api_token',
kind='galaxy', kind='galaxy',
name=ugettext_noop('Ansible Galaxy/Automation Hub API Token'), name=gettext_noop('Ansible Galaxy/Automation Hub API Token'),
inputs={ inputs={
'fields': [ 'fields': [
{ {
'id': 'url', 'id': 'url',
'label': ugettext_noop('Galaxy Server URL'), 'label': gettext_noop('Galaxy Server URL'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('The URL of the Galaxy instance to connect to.'), 'help_text': gettext_noop('The URL of the Galaxy instance to connect to.'),
}, },
{ {
'id': 'auth_url', 'id': 'auth_url',
'label': ugettext_noop('Auth Server URL'), 'label': gettext_noop('Auth Server URL'),
'type': 'string', 'type': 'string',
'help_text': ugettext_noop('The URL of a Keycloak server token_endpoint, if using ' 'SSO auth.'), 'help_text': gettext_noop('The URL of a Keycloak server token_endpoint, if using ' 'SSO auth.'),
}, },
{ {
'id': 'token', 'id': 'token',
'label': ugettext_noop('API Token'), 'label': gettext_noop('API Token'),
'type': 'string', 'type': 'string',
'secret': True, 'secret': True,
'help_text': ugettext_noop('A token to use for authentication against the Galaxy instance.'), 'help_text': gettext_noop('A token to use for authentication against the Galaxy instance.'),
}, },
], ],
'required': ['url'], 'required': ['url'],

View File

@@ -10,8 +10,8 @@ from django.db import models, DatabaseError, connection
from django.utils.dateparse import parse_datetime from django.utils.dateparse import parse_datetime
from django.utils.text import Truncator from django.utils.text import Truncator
from django.utils.timezone import utc, now from django.utils.timezone import utc, now
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.encoding import force_text from django.utils.encoding import force_str
from awx.api.versioning import reverse from awx.api.versioning import reverse
from awx.main import consumers from awx.main import consumers
@@ -396,7 +396,7 @@ class BasePlaybookEvent(CreatedModifiedModel):
connection.on_commit(_send_notifications) connection.on_commit(_send_notifications)
for field in ('playbook', 'play', 'task', 'role'): for field in ('playbook', 'play', 'task', 'role'):
value = force_text(event_data.get(field, '')).strip() value = force_str(event_data.get(field, '')).strip()
if value != getattr(self, field): if value != getattr(self, field):
setattr(self, field, value) setattr(self, field, value)
if settings.LOG_AGGREGATOR_ENABLED: if settings.LOG_AGGREGATOR_ENABLED:

View File

@@ -1,5 +1,5 @@
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.api.versioning import reverse from awx.api.versioning import reverse
from awx.main.models.base import CommonModel from awx.main.models.base import CommonModel

View File

@@ -9,7 +9,7 @@ from django.core.validators import MinValueValidator
from django.db import models, connection from django.db import models, connection
from django.db.models.signals import post_save, post_delete from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.conf import settings from django.conf import settings
from django.utils.timezone import now, timedelta from django.utils.timezone import now, timedelta

View File

@@ -14,7 +14,7 @@ import yaml
# Django # Django
from django.conf import settings from django.conf import settings
from django.db import models, connection from django.db import models, connection
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.db import transaction from django.db import transaction
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.utils.timezone import now from django.utils.timezone import now

View File

@@ -19,7 +19,7 @@ from django.db import models
# from django.core.cache import cache # from django.core.cache import cache
from django.utils.encoding import smart_str from django.utils.encoding import smart_str
from django.utils.timezone import now from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.core.exceptions import FieldDoesNotExist from django.core.exceptions import FieldDoesNotExist
# REST Framework # REST Framework

View File

@@ -3,7 +3,7 @@
# Django # Django
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# AWX # AWX
from awx.api.versioning import reverse from awx.api.versioning import reverse

View File

@@ -15,7 +15,7 @@ from django.core.exceptions import ValidationError
from django.db import models from django.db import models
from django.db.models.query import QuerySet from django.db.models.query import QuerySet
from django.utils.crypto import get_random_string from django.utils.crypto import get_random_string
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# AWX # AWX
from awx.main.models.base import prevent_search from awx.main.models.base import prevent_search

View File

@@ -10,8 +10,8 @@ from django.db import models
from django.conf import settings from django.conf import settings
from django.core.mail.message import EmailMessage from django.core.mail.message import EmailMessage
from django.db import connection from django.db import connection
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.encoding import smart_str, force_text from django.utils.encoding import smart_str, force_str
from jinja2 import sandbox, ChainableUndefined from jinja2 import sandbox, ChainableUndefined
from jinja2.exceptions import TemplateSyntaxError, UndefinedError, SecurityError from jinja2.exceptions import TemplateSyntaxError, UndefinedError, SecurityError
@@ -187,7 +187,7 @@ class NotificationTemplate(CommonModelNameNotUnique):
def display_notification_configuration(self): def display_notification_configuration(self):
field_val = self.notification_configuration.copy() field_val = self.notification_configuration.copy()
for field in self.notification_class.init_parameters: for field in self.notification_class.init_parameters:
if field in field_val and force_text(field_val[field]).startswith('$encrypted$'): if field in field_val and force_str(field_val[field]).startswith('$encrypted$'):
field_val[field] = '$encrypted$' field_val[field] = '$encrypted$'
return field_val return field_val

View File

@@ -6,7 +6,7 @@ import re
from django.core.validators import RegexValidator from django.core.validators import RegexValidator
from django.db import models, connection from django.db import models, connection
from django.utils.timezone import now from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.conf import settings from django.conf import settings
# Django OAuth Toolkit # Django OAuth Toolkit

View File

@@ -8,7 +8,7 @@ from django.db import models
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.contrib.sessions.models import Session from django.contrib.sessions.models import Session
from django.utils.timezone import now as tz_now from django.utils.timezone import now as tz_now
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# AWX # AWX

View File

@@ -9,8 +9,8 @@ import urllib.parse as urlparse
# Django # Django
from django.conf import settings from django.conf import settings
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.encoding import smart_str, smart_text from django.utils.encoding import smart_str
from django.utils.text import slugify from django.utils.text import slugify
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.utils.timezone import now, make_aware, get_default_timezone from django.utils.timezone import now, make_aware, get_default_timezone
@@ -214,7 +214,7 @@ class ProjectOptions(models.Model):
for filename in filenames: for filename in filenames:
playbook = could_be_playbook(project_path, dirpath, filename) playbook = could_be_playbook(project_path, dirpath, filename)
if playbook is not None: if playbook is not None:
results.append(smart_text(playbook)) results.append(smart_str(playbook))
return sorted(results, key=lambda x: smart_str(x).lower()) return sorted(results, key=lambda x: smart_str(x).lower())
@property @property
@@ -230,7 +230,7 @@ class ProjectOptions(models.Model):
for filename in filenames: for filename in filenames:
inv_path = could_be_inventory(project_path, dirpath, filename) inv_path = could_be_inventory(project_path, dirpath, filename)
if inv_path is not None: if inv_path is not None:
results.append(smart_text(inv_path)) results.append(smart_str(inv_path))
if len(results) > max_inventory_listing: if len(results) > max_inventory_listing:
break break
if len(results) > max_inventory_listing: if len(results) > max_inventory_listing:

View File

@@ -11,7 +11,7 @@ import re
from django.db import models, transaction, connection from django.db import models, transaction, connection
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.fields import GenericForeignKey
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# AWX # AWX
from awx.api.versioning import reverse from awx.api.versioning import reverse

View File

@@ -14,7 +14,7 @@ from dateutil.zoneinfo import get_zonefile_instance
from django.db import models from django.db import models
from django.db.models.query import QuerySet from django.db.models.query import QuerySet
from django.utils.timezone import now, make_aware from django.utils.timezone import now, make_aware
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# AWX # AWX
from awx.api.versioning import reverse from awx.api.versioning import reverse

View File

@@ -19,9 +19,9 @@ from collections import OrderedDict
from django.conf import settings from django.conf import settings
from django.db import models, connection from django.db import models, connection
from django.core.exceptions import NON_FIELD_ERRORS from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.timezone import now from django.utils.timezone import now
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
# REST Framework # REST Framework
@@ -1090,7 +1090,7 @@ class UnifiedJob(
# function assume a str-based fd will be returned; decode # function assume a str-based fd will be returned; decode
# .write() calls on the fly to maintain this interface # .write() calls on the fly to maintain this interface
_write = fd.write _write = fd.write
fd.write = lambda s: _write(smart_text(s)) fd.write = lambda s: _write(smart_str(s))
tbl = self._meta.db_table + 'event' tbl = self._meta.db_table + 'event'
created_by_cond = '' created_by_cond = ''
if self.has_unpartitioned_events: if self.has_unpartitioned_events:
@@ -1273,7 +1273,7 @@ class UnifiedJob(
id=self.id, id=self.id,
name=self.name, name=self.name,
url=self.get_ui_url(), url=self.get_ui_url(),
created_by=smart_text(self.created_by), created_by=smart_str(self.created_by),
started=self.started.isoformat() if self.started is not None else None, started=self.started.isoformat() if self.started is not None else None,
finished=self.finished.isoformat() if self.finished is not None else None, finished=self.finished.isoformat() if self.finished is not None else None,
status=self.status, status=self.status,

View File

@@ -11,7 +11,7 @@ from urllib.parse import urljoin
# Django # Django
from django.db import connection, models from django.db import connection, models
from django.conf import settings from django.conf import settings
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
# from django import settings as tower_settings # from django import settings as tower_settings

View File

@@ -7,8 +7,8 @@ import logging
import requests import requests
import dateutil.parser as dp import dateutil.parser as dp
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.main.notifications.base import AWXBaseEmailBackend from awx.main.notifications.base import AWXBaseEmailBackend
from awx.main.notifications.custom_notification_base import CustomNotificationBase from awx.main.notifications.custom_notification_base import CustomNotificationBase
@@ -82,9 +82,9 @@ class GrafanaBackend(AWXBaseEmailBackend, CustomNotificationBase):
if m.body.get('finished'): if m.body.get('finished'):
grafana_data['timeEnd'] = int((dp.parse(m.body['finished']).replace(tzinfo=None) - epoch).total_seconds() * 1000) grafana_data['timeEnd'] = int((dp.parse(m.body['finished']).replace(tzinfo=None) - epoch).total_seconds() * 1000)
except ValueError: except ValueError:
logger.error(smart_text(_("Error converting time {} or timeEnd {} to int.").format(m.body['started'], m.body['finished']))) logger.error(smart_str(_("Error converting time {} or timeEnd {} to int.").format(m.body['started'], m.body['finished'])))
if not self.fail_silently: if not self.fail_silently:
raise Exception(smart_text(_("Error converting time {} and/or timeEnd {} to int.").format(m.body['started'], m.body['finished']))) raise Exception(smart_str(_("Error converting time {} and/or timeEnd {} to int.").format(m.body['started'], m.body['finished'])))
grafana_data['isRegion'] = self.isRegion grafana_data['isRegion'] = self.isRegion
grafana_data['dashboardId'] = self.dashboardId grafana_data['dashboardId'] = self.dashboardId
grafana_data['panelId'] = self.panelId grafana_data['panelId'] = self.panelId
@@ -97,8 +97,8 @@ class GrafanaBackend(AWXBaseEmailBackend, CustomNotificationBase):
"{}/api/annotations".format(m.recipients()[0]), json=grafana_data, headers=grafana_headers, verify=(not self.grafana_no_verify_ssl) "{}/api/annotations".format(m.recipients()[0]), json=grafana_data, headers=grafana_headers, verify=(not self.grafana_no_verify_ssl)
) )
if r.status_code >= 400: if r.status_code >= 400:
logger.error(smart_text(_("Error sending notification grafana: {}").format(r.status_code))) logger.error(smart_str(_("Error sending notification grafana: {}").format(r.status_code)))
if not self.fail_silently: if not self.fail_silently:
raise Exception(smart_text(_("Error sending notification grafana: {}").format(r.status_code))) raise Exception(smart_str(_("Error sending notification grafana: {}").format(r.status_code)))
sent_messages += 1 sent_messages += 1
return sent_messages return sent_messages

View File

@@ -7,8 +7,8 @@ import logging
import irc.client import irc.client
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.main.notifications.base import AWXBaseEmailBackend from awx.main.notifications.base import AWXBaseEmailBackend
from awx.main.notifications.custom_notification_base import CustomNotificationBase from awx.main.notifications.custom_notification_base import CustomNotificationBase
@@ -55,7 +55,7 @@ class IrcBackend(AWXBaseEmailBackend, CustomNotificationBase):
connect_factory=connection_factory, connect_factory=connection_factory,
) )
except irc.client.ServerConnectionError as e: except irc.client.ServerConnectionError as e:
logger.error(smart_text(_("Exception connecting to irc server: {}").format(e))) logger.error(smart_str(_("Exception connecting to irc server: {}").format(e)))
if not self.fail_silently: if not self.fail_silently:
raise raise
return True return True

View File

@@ -4,8 +4,8 @@
import logging import logging
import requests import requests
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.main.notifications.base import AWXBaseEmailBackend from awx.main.notifications.base import AWXBaseEmailBackend
from awx.main.notifications.custom_notification_base import CustomNotificationBase from awx.main.notifications.custom_notification_base import CustomNotificationBase
@@ -44,8 +44,8 @@ class MattermostBackend(AWXBaseEmailBackend, CustomNotificationBase):
r = requests.post("{}".format(m.recipients()[0]), json=payload, verify=(not self.mattermost_no_verify_ssl)) r = requests.post("{}".format(m.recipients()[0]), json=payload, verify=(not self.mattermost_no_verify_ssl))
if r.status_code >= 400: if r.status_code >= 400:
logger.error(smart_text(_("Error sending notification mattermost: {}").format(r.status_code))) logger.error(smart_str(_("Error sending notification mattermost: {}").format(r.status_code)))
if not self.fail_silently: if not self.fail_silently:
raise Exception(smart_text(_("Error sending notification mattermost: {}").format(r.status_code))) raise Exception(smart_str(_("Error sending notification mattermost: {}").format(r.status_code)))
sent_messages += 1 sent_messages += 1
return sent_messages return sent_messages

View File

@@ -5,8 +5,8 @@ import json
import logging import logging
import pygerduty import pygerduty
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.main.notifications.base import AWXBaseEmailBackend from awx.main.notifications.base import AWXBaseEmailBackend
from awx.main.notifications.custom_notification_base import CustomNotificationBase from awx.main.notifications.custom_notification_base import CustomNotificationBase
@@ -78,13 +78,13 @@ class PagerDutyBackend(AWXBaseEmailBackend, CustomNotificationBase):
except Exception as e: except Exception as e:
if not self.fail_silently: if not self.fail_silently:
raise raise
logger.error(smart_text(_("Exception connecting to PagerDuty: {}").format(e))) logger.error(smart_str(_("Exception connecting to PagerDuty: {}").format(e)))
for m in messages: for m in messages:
try: try:
pager.trigger_incident(m.recipients()[0], description=m.subject, details=m.body, client=m.from_email) pager.trigger_incident(m.recipients()[0], description=m.subject, details=m.body, client=m.from_email)
sent_messages += 1 sent_messages += 1
except Exception as e: except Exception as e:
logger.error(smart_text(_("Exception sending messages: {}").format(e))) logger.error(smart_str(_("Exception sending messages: {}").format(e)))
if not self.fail_silently: if not self.fail_silently:
raise raise
return sent_messages return sent_messages

View File

@@ -5,8 +5,8 @@ import logging
import requests import requests
import json import json
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.main.notifications.base import AWXBaseEmailBackend from awx.main.notifications.base import AWXBaseEmailBackend
from awx.main.utils import get_awx_http_client_headers from awx.main.utils import get_awx_http_client_headers
@@ -44,8 +44,8 @@ class RocketChatBackend(AWXBaseEmailBackend, CustomNotificationBase):
) )
if r.status_code >= 400: if r.status_code >= 400:
logger.error(smart_text(_("Error sending notification rocket.chat: {}").format(r.status_code))) logger.error(smart_str(_("Error sending notification rocket.chat: {}").format(r.status_code)))
if not self.fail_silently: if not self.fail_silently:
raise Exception(smart_text(_("Error sending notification rocket.chat: {}").format(r.status_code))) raise Exception(smart_str(_("Error sending notification rocket.chat: {}").format(r.status_code)))
sent_messages += 1 sent_messages += 1
return sent_messages return sent_messages

View File

@@ -5,8 +5,8 @@ import logging
from slack_sdk import WebClient from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError from slack_sdk.errors import SlackApiError
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.main.notifications.base import AWXBaseEmailBackend from awx.main.notifications.base import AWXBaseEmailBackend
from awx.main.notifications.custom_notification_base import CustomNotificationBase from awx.main.notifications.custom_notification_base import CustomNotificationBase
@@ -53,7 +53,7 @@ class SlackBackend(AWXBaseEmailBackend, CustomNotificationBase):
else: else:
raise RuntimeError("Slack Notification unable to send {}: {} ({})".format(r, m.subject, response['error'])) raise RuntimeError("Slack Notification unable to send {}: {} ({})".format(r, m.subject, response['error']))
except SlackApiError as e: except SlackApiError as e:
logger.error(smart_text(_("Exception sending messages: {}").format(e))) logger.error(smart_str(_("Exception sending messages: {}").format(e)))
if not self.fail_silently: if not self.fail_silently:
raise raise
return sent_messages return sent_messages

View File

@@ -5,8 +5,8 @@ import logging
from twilio.rest import Client from twilio.rest import Client
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.main.notifications.base import AWXBaseEmailBackend from awx.main.notifications.base import AWXBaseEmailBackend
from awx.main.notifications.custom_notification_base import CustomNotificationBase from awx.main.notifications.custom_notification_base import CustomNotificationBase
@@ -37,14 +37,14 @@ class TwilioBackend(AWXBaseEmailBackend, CustomNotificationBase):
except Exception as e: except Exception as e:
if not self.fail_silently: if not self.fail_silently:
raise raise
logger.error(smart_text(_("Exception connecting to Twilio: {}").format(e))) logger.error(smart_str(_("Exception connecting to Twilio: {}").format(e)))
for m in messages: for m in messages:
try: try:
connection.messages.create(to=m.to, from_=m.from_email, body=m.subject) connection.messages.create(to=m.to, from_=m.from_email, body=m.subject)
sent_messages += 1 sent_messages += 1
except Exception as e: except Exception as e:
logger.error(smart_text(_("Exception sending messages: {}").format(e))) logger.error(smart_str(_("Exception sending messages: {}").format(e)))
if not self.fail_silently: if not self.fail_silently:
raise raise
return sent_messages return sent_messages

View File

@@ -5,8 +5,8 @@ import json
import logging import logging
import requests import requests
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.main.notifications.base import AWXBaseEmailBackend from awx.main.notifications.base import AWXBaseEmailBackend
from awx.main.utils import get_awx_http_client_headers from awx.main.utils import get_awx_http_client_headers
@@ -76,8 +76,8 @@ class WebhookBackend(AWXBaseEmailBackend, CustomNotificationBase):
verify=(not self.disable_ssl_verification), verify=(not self.disable_ssl_verification),
) )
if r.status_code >= 400: if r.status_code >= 400:
logger.error(smart_text(_("Error sending notification webhook: {}").format(r.status_code))) logger.error(smart_str(_("Error sending notification webhook: {}").format(r.status_code)))
if not self.fail_silently: if not self.fail_silently:
raise Exception(smart_text(_("Error sending notification webhook: {}").format(r.status_code))) raise Exception(smart_str(_("Error sending notification webhook: {}").format(r.status_code)))
sent_messages += 1 sent_messages += 1
return sent_messages return sent_messages

View File

@@ -1,5 +1,5 @@
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
# Python # Python
from awx.main.models import ( from awx.main.models import (
@@ -171,7 +171,7 @@ class WorkflowDAG(SimpleDAG):
parms['node_status'] = ",".join(["({},{})".format(id, status) for id, status in failed_path_nodes_id_status]) parms['node_status'] = ",".join(["({},{})".format(id, status) for id, status in failed_path_nodes_id_status])
if len(failed_unified_job_template_node_ids) > 0: if len(failed_unified_job_template_node_ids) > 0:
parms['no_ufjt'] = ",".join(failed_unified_job_template_node_ids) parms['no_ufjt'] = ",".join(failed_unified_job_template_node_ids)
return True, smart_text(s.format(**parms)) return True, smart_str(s.format(**parms))
return False, None return False, None
r''' r'''

View File

@@ -7,7 +7,7 @@ from urllib import parse as urlparse
from django.conf import settings from django.conf import settings
from kubernetes import client, config from kubernetes import client, config
from django.utils.functional import cached_property from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from awx.main.utils.common import parse_yaml_or_json, deepmerge from awx.main.utils.common import parse_yaml_or_json, deepmerge
from awx.main.utils.execution_environments import get_default_pod_spec from awx.main.utils.execution_environments import get_default_pod_spec

View File

@@ -10,7 +10,7 @@ from types import SimpleNamespace
# Django # Django
from django.db import transaction, connection from django.db import transaction, connection
from django.utils.translation import ugettext_lazy as _, gettext_noop from django.utils.translation import gettext_lazy as _, gettext_noop
from django.utils.timezone import now as tz_now from django.utils.timezone import now as tz_now
from django.conf import settings from django.conf import settings

View File

@@ -81,7 +81,7 @@ from awx.main.utils.handlers import SpecialInventoryHandler
from awx.main.tasks.system import handle_success_and_failure_notifications, update_smart_memberships_for_inventory, update_inventory_computed_fields from awx.main.tasks.system import handle_success_and_failure_notifications, update_smart_memberships_for_inventory, update_inventory_computed_fields
from awx.main.utils.update_model import update_model from awx.main.utils.update_model import update_model
from rest_framework.exceptions import PermissionDenied from rest_framework.exceptions import PermissionDenied
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
logger = logging.getLogger('awx.main.tasks.jobs') logger = logging.getLogger('awx.main.tasks.jobs')

View File

@@ -18,7 +18,7 @@ from django.db.models.fields.related import ForeignKey
from django.utils.timezone import now from django.utils.timezone import now
from django.utils.encoding import smart_str from django.utils.encoding import smart_str
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.translation import gettext_noop from django.utils.translation import gettext_noop
from django.core.cache import cache from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist

View File

@@ -5,7 +5,7 @@ import re
from django.conf import settings from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder from django.core.serializers.json import DjangoJSONEncoder
from django.utils.functional import Promise from django.utils.functional import Promise
from django.utils.encoding import force_text from django.utils.encoding import force_str
from openapi_codec.encode import generate_swagger_object from openapi_codec.encode import generate_swagger_object
import pytest import pytest
@@ -16,9 +16,9 @@ from awx.api.versioning import drf_reverse
class i18nEncoder(DjangoJSONEncoder): class i18nEncoder(DjangoJSONEncoder):
def default(self, obj): def default(self, obj):
if isinstance(obj, Promise): if isinstance(obj, Promise):
return force_text(obj) return force_str(obj)
if type(obj) == bytes: if type(obj) == bytes:
return force_text(obj) return force_str(obj)
return super(i18nEncoder, self).default(obj) return super(i18nEncoder, self).default(obj)

View File

@@ -2,8 +2,8 @@ import pytest
import uuid import uuid
import os import os
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from awx.main.scheduler.dag_workflow import WorkflowDAG from awx.main.scheduler.dag_workflow import WorkflowDAG
@@ -468,7 +468,7 @@ class TestIsWorkflowDone:
assert g.is_workflow_done() is True assert g.is_workflow_done() is True
assert g.has_workflow_failed() == ( assert g.has_workflow_failed() == (
True, True,
smart_text( smart_str(
_( _(
"No error handling path for workflow job node(s) [({},{})]. Workflow job node(s)" "No error handling path for workflow job node(s) [({},{})]. Workflow job node(s)"
" missing unified job template and error handling path []." " missing unified job template and error handling path []."
@@ -484,7 +484,7 @@ class TestIsWorkflowDone:
assert g.is_workflow_done() is True assert g.is_workflow_done() is True
assert g.has_workflow_failed() == ( assert g.has_workflow_failed() == (
True, True,
smart_text( smart_str(
_( _(
"No error handling path for workflow job node(s) []. Workflow job node(s) missing" " unified job template and error handling path [{}]." "No error handling path for workflow job node(s) []. Workflow job node(s) missing" " unified job template and error handling path [{}]."
).format(nodes[2].id) ).format(nodes[2].id)
@@ -500,7 +500,7 @@ class TestIsWorkflowDone:
assert g.is_workflow_done() is True assert g.is_workflow_done() is True
assert g.has_workflow_failed() == ( assert g.has_workflow_failed() == (
True, True,
smart_text( smart_str(
_( _(
"No error handling path for workflow job node(s) []. Workflow job node(s) missing" " unified job template and error handling path [{}]." "No error handling path for workflow job node(s) []. Workflow job node(s) missing" " unified job template and error handling path [{}]."
).format(nodes[0].id) ).format(nodes[0].id)
@@ -512,7 +512,7 @@ class TestIsWorkflowDone:
assert g.has_workflow_failed() == ( assert g.has_workflow_failed() == (
True, True,
smart_text( smart_str(
_( _(
"No error handling path for workflow job node(s) [({},{})]. Workflow job node(s)" "No error handling path for workflow job node(s) [({},{})]. Workflow job node(s)"
" missing unified job template and error handling path []." " missing unified job template and error handling path []."
@@ -525,7 +525,7 @@ class TestIsWorkflowDone:
assert g.has_workflow_failed() == ( assert g.has_workflow_failed() == (
True, True,
smart_text( smart_str(
_( _(
"No error handling path for workflow job node(s) [({},{})]. Workflow job node(s)" "No error handling path for workflow job node(s) [({},{})]. Workflow job node(s)"
" missing unified job template and error handling path []." " missing unified job template and error handling path []."

View File

@@ -19,7 +19,7 @@ from functools import reduce, wraps
# Django # Django
from django.core.exceptions import ObjectDoesNotExist, FieldDoesNotExist from django.core.exceptions import ObjectDoesNotExist, FieldDoesNotExist
from django.utils.dateparse import parse_datetime from django.utils.dateparse import parse_datetime
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.utils.functional import cached_property from django.utils.functional import cached_property
from django.db import connection from django.db import connection
from django.db.models.fields.related import ForeignObjectRel, ManyToManyField from django.db.models.fields.related import ForeignObjectRel, ManyToManyField

View File

@@ -33,7 +33,7 @@ from cryptography import x509
# Django # Django
from django.conf import settings from django.conf import settings
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
MAX_INSTANCES = 9999999 MAX_INSTANCES = 9999999

View File

@@ -6,7 +6,7 @@ import base64
import re import re
# Django # Django
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
# REST framework # REST framework

View File

@@ -7,7 +7,7 @@ import json
from django.http import HttpResponse, HttpResponseRedirect from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render from django.shortcuts import render
from django.utils.html import format_html from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
# Django REST Framework # Django REST Framework

View File

@@ -1,6 +1,6 @@
# Django # Django
from django.apps import AppConfig from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
class SSOConfig(AppConfig): class SSOConfig(AppConfig):

View File

@@ -13,7 +13,7 @@ from django.dispatch import receiver
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.conf import settings as django_settings from django.conf import settings as django_settings
from django.core.signals import setting_changed from django.core.signals import setting_changed
from django.utils.encoding import force_text from django.utils.encoding import force_str
# django-auth-ldap # django-auth-ldap
from django_auth_ldap.backend import LDAPSettings as BaseLDAPSettings from django_auth_ldap.backend import LDAPSettings as BaseLDAPSettings
@@ -200,7 +200,7 @@ class RADIUSBackend(BaseRADIUSBackend):
return user return user
def get_django_user(self, username, password=None): def get_django_user(self, username, password=None):
return _get_or_set_enterprise_user(force_text(username), force_text(password), 'radius') return _get_or_set_enterprise_user(force_str(username), force_str(password), 'radius')
class TACACSPlusBackend(object): class TACACSPlusBackend(object):

View File

@@ -5,7 +5,7 @@ import urllib.parse as urlparse
# Django # Django
from django.conf import settings from django.conf import settings
from django.urls import reverse from django.urls import reverse
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django REST Framework # Django REST Framework
from rest_framework import serializers from rest_framework import serializers

View File

@@ -11,7 +11,7 @@ import ldap
import awx import awx
# Django # Django
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# Django Auth LDAP # Django Auth LDAP
import django_auth_ldap.config import django_auth_ldap.config

View File

@@ -4,7 +4,7 @@
# Django # Django
from django.db import models from django.db import models
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
class UserEnterpriseAuth(models.Model): class UserEnterpriseAuth(models.Model):

View File

@@ -11,7 +11,7 @@ from social_core.exceptions import AuthException
# Django # Django
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.db.models import Q from django.db.models import Q

View File

@@ -6,7 +6,7 @@ import ldap
# Django # Django
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 gettext_lazy as _
__all__ = [ __all__ = [
'validate_ldap_dn', 'validate_ldap_dn',

View File

@@ -10,7 +10,7 @@ from django.urls import reverse
from django.http import HttpResponse from django.http import HttpResponse
from django.views.generic import View from django.views.generic import View
from django.views.generic.base import RedirectView from django.views.generic.base import RedirectView
from django.utils.encoding import smart_text from django.utils.encoding import smart_str
from awx.api.serializers import UserSerializer from awx.api.serializers import UserSerializer
from rest_framework.renderers import JSONRenderer from rest_framework.renderers import JSONRenderer
from django.conf import settings from django.conf import settings
@@ -40,10 +40,10 @@ class CompleteView(BaseRedirectView):
def dispatch(self, request, *args, **kwargs): def dispatch(self, request, *args, **kwargs):
response = super(CompleteView, self).dispatch(request, *args, **kwargs) response = super(CompleteView, self).dispatch(request, *args, **kwargs)
if self.request.user and self.request.user.is_authenticated: if self.request.user and self.request.user.is_authenticated:
logger.info(smart_text(u"User {} logged in".format(self.request.user.username))) logger.info(smart_str(u"User {} logged in".format(self.request.user.username)))
response.set_cookie('userLoggedIn', 'true') response.set_cookie('userLoggedIn', 'true')
current_user = UserSerializer(self.request.user) current_user = UserSerializer(self.request.user)
current_user = smart_text(JSONRenderer().render(current_user.data)) current_user = smart_str(JSONRenderer().render(current_user.data))
current_user = urllib.parse.quote('%s' % current_user, '') current_user = urllib.parse.quote('%s' % current_user, '')
response.set_cookie('current_user', current_user, secure=settings.SESSION_COOKIE_SECURE or None) response.set_cookie('current_user', current_user, secure=settings.SESSION_COOKIE_SECURE or None)
response.setdefault('X-API-Session-Cookie-Name', getattr(settings, 'SESSION_COOKIE_NAME', 'awx_sessionid')) response.setdefault('X-API-Session-Cookie-Name', getattr(settings, 'SESSION_COOKIE_NAME', 'awx_sessionid'))

View File

@@ -1,6 +1,6 @@
# Django # Django
from django.apps import AppConfig from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
class UIConfig(AppConfig): class UIConfig(AppConfig):

View File

@@ -2,7 +2,7 @@
# All Rights Reserved. # All Rights Reserved.
# Django # Django
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# AWX # AWX
from awx.conf import register, fields from awx.conf import register, fields

View File

@@ -7,7 +7,7 @@ import binascii
import re import re
# Django # Django
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
# AWX # AWX
from awx.conf import fields from awx.conf import fields

View File

@@ -1,5 +1,5 @@
from django.conf.urls import url from django.conf.urls import url
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import gettext_lazy as _
from django.views.generic.base import TemplateView from django.views.generic.base import TemplateView
from awx.main.utils.licensing import server_product_name from awx.main.utils.licensing import server_product_name