Skip to content

Commit

Permalink
Remove usage of six
Browse files Browse the repository at this point in the history
  • Loading branch information
jeromelebleu committed Jan 7, 2020
1 parent 369d05e commit 09434af
Show file tree
Hide file tree
Showing 12 changed files with 37 additions and 73 deletions.
8 changes: 1 addition & 7 deletions modoboa/admin/management/commands/subcommands/_export.py
@@ -1,20 +1,14 @@
"""Django management command to export admin objects."""

import sys
import csv

from django.core.management.base import BaseCommand
from django.utils import six
from django.utils.encoding import smart_text

from modoboa.core.extensions import exts_pool
from modoboa.core.models import User
from .... import models

if six.PY2:
from backports import csv
else:
import csv


class ExportCommand(BaseCommand):
"""Command class."""
Expand Down
22 changes: 7 additions & 15 deletions modoboa/admin/management/commands/subcommands/_import.py
@@ -1,5 +1,6 @@
"""Django management command to import admin objects."""

import csv
import io
import os

Expand All @@ -8,19 +9,13 @@

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.utils import six
from django.utils.translation import ugettext as _

from modoboa.core import models as core_models
from modoboa.core.extensions import exts_pool
from modoboa.lib.exceptions import Conflict
from .... import signals

if six.PY2:
from backports import csv
else:
import csv


class ImportCommand(BaseCommand):
"""Command class."""
Expand All @@ -31,7 +26,7 @@ class ImportCommand(BaseCommand):
def add_arguments(self, parser):
"""Add extra arguments to command."""
parser.add_argument(
"--sepchar", type=six.text_type, default=";",
"--sepchar", type=str, default=";",
help="Separator used in file.")
parser.add_argument(
"--continue-if-exists", action="store_true",
Expand All @@ -41,7 +36,7 @@ def add_arguments(self, parser):
"--crypt-password", action="store_true",
default=False, help="Encrypt provided passwords.")
parser.add_argument(
"files", type=six.text_type, nargs="+", help="CSV files to import.")
"files", type=str, nargs="+", help="CSV files to import.")

def _import(self, filename, options, encoding="utf-8"):
"""Import domains or identities."""
Expand Down Expand Up @@ -117,10 +112,7 @@ def handle(self, *args, **options):
encoding=detector.result["encoding"]
)
except UnicodeDecodeError as exc:
six.raise_from(
CommandError(
_("Unable to decode CSV file using %(encoding)s "
"encoding") % detector.result
),
exc
)
raise CommandError(
_("Unable to decode CSV file using %(encoding)s "
"encoding") % detector.result
) from exc
3 changes: 1 addition & 2 deletions modoboa/admin/tests/test_export.py
@@ -1,8 +1,7 @@
"""Export related test cases."""

import sys

from six.moves import StringIO
from io import StringIO

from django.core.management import call_command
from django.urls import reverse
Expand Down
13 changes: 5 additions & 8 deletions modoboa/admin/views/export.py
@@ -1,5 +1,8 @@
"""Export related views."""

import csv
from io import StringIO

from rfc6266 import build_header

from django.contrib.auth.decorators import (
Expand All @@ -8,17 +11,11 @@
from django.http import HttpResponse
from django.shortcuts import render
from django.urls import reverse
from django.utils import six
from django.utils.translation import ugettext as _

from ..forms import ExportDomainsForm, ExportIdentitiesForm
from ..lib import get_domains, get_identities

if six.PY2:
from backports import csv
else:
import csv


def _export(content, filename):
"""Export a csv file's content
Expand Down Expand Up @@ -50,7 +47,7 @@ def export_identities(request):
if request.method == "POST":
form = ExportIdentitiesForm(request.POST)
form.is_valid()
fp = six.StringIO()
fp = StringIO()
csvwriter = csv.writer(fp, delimiter=form.cleaned_data["sepchar"])
identities = get_identities(
request.user, **request.session["identities_filters"])
Expand Down Expand Up @@ -78,7 +75,7 @@ def export_domains(request):
if request.method == "POST":
form = ExportDomainsForm(request.POST)
form.is_valid()
fp = six.StringIO()
fp = StringIO()
csvwriter = csv.writer(fp, delimiter=form.cleaned_data["sepchar"])
for dom in get_domains(request.user,
**request.session["domains_filters"]):
Expand Down
7 changes: 1 addition & 6 deletions modoboa/admin/views/import_.py
@@ -1,5 +1,6 @@
"""Import related views."""

import csv
import io

from reversion import revisions as reversion
Expand All @@ -10,19 +11,13 @@
from django.db import transaction
from django.shortcuts import render
from django.urls import reverse
from django.utils import six
from django.utils.encoding import smart_text
from django.utils.translation import ugettext as _

from modoboa.lib.exceptions import Conflict, ModoboaException
from .. import signals
from ..forms import ImportDataForm, ImportIdentitiesForm

if six.PY2:
from backports import csv
else:
import csv


@reversion.create_revision()
def importdata(request, formclass=ImportDataForm):
Expand Down
1 change: 0 additions & 1 deletion modoboa/core/commands/deploy.py
Expand Up @@ -14,7 +14,6 @@
from django.core import management
from django.template import Context, Template
from django.utils.encoding import smart_str
from django.utils.six.moves import input

from modoboa.core.commands import Command
from modoboa.lib.api_client import ModoAPIClient
Expand Down
@@ -1,7 +1,6 @@
"""Inactive accounts cleanup tool."""

from dateutil.relativedelta import relativedelta
from six.moves import input

from django.core.management.base import BaseCommand
from django.utils import timezone
Expand Down
4 changes: 1 addition & 3 deletions modoboa/core/password_hashers/base.py
Expand Up @@ -13,8 +13,6 @@
from django.utils.crypto import constant_time_compare
from django.utils.encoding import force_bytes, force_text

from six import with_metaclass


class MetaHasher(type):
"""
Expand All @@ -32,7 +30,7 @@ def label(cls):
return cls.name if not cls._weak else "{} (weak)".format(cls.name)


class PasswordHasher(with_metaclass(MetaHasher, object)):
class PasswordHasher(metaclass=MetaHasher):
"""
Base class of all hashers.
"""
Expand Down
3 changes: 2 additions & 1 deletion modoboa/core/tests/test_core.py
@@ -1,8 +1,9 @@
"""Tests for core application."""

from io import StringIO

import httmock
from dateutil.relativedelta import relativedelta
from six import StringIO

from django.core import management
from django.test import TestCase
Expand Down
4 changes: 1 addition & 3 deletions modoboa/ldapsync/tests.py
Expand Up @@ -2,7 +2,6 @@

from unittest import skipIf

from django.utils import six
from django.utils.encoding import force_bytes, force_str

from modoboa.core import factories as core_factories
Expand Down Expand Up @@ -36,8 +35,7 @@ def setUp(self):

def reset_ldap_directory(self):
try:
tmp_dn = force_bytes(self.dn) if six.PY2 else self.dn
self.conn.delete_s(tmp_dn)
self.conn.delete_s(self.dn)
except ldap.NO_SUCH_OBJECT:
pass

Expand Down
41 changes: 17 additions & 24 deletions modoboa/lib/email_utils.py
Expand Up @@ -12,7 +12,6 @@
from lxml.html.clean import Cleaner

from django.template.loader import render_to_string
from django.utils import six
from django.utils.encoding import smart_str, smart_text
from django.utils.html import conditional_escape, escape
from django.utils.translation import ugettext as _
Expand Down Expand Up @@ -130,20 +129,17 @@ def get_header(self, msg, header):
continue
if encoding:
value = smart_text(value, encoding=encoding)
elif isinstance(value, six.binary_type):
elif isinstance(value, bytes):
# SMTPUTF8 fallback (most of the time)
# Address contains non ASCII chars but is not RFC2047
# encoded...
encoding = chardet.detect(value)
try:
value = value.decode(encoding["encoding"], "replace")
except (TypeError, UnicodeDecodeError) as exc:
six.raise_from(
InternalError(
_("unable to determine encoding of string")
),
exc
)
raise InternalError(
_("unable to determine encoding of string")
) from exc
decoded_values.append(value)
return "".join(decoded_values)
return ""
Expand Down Expand Up @@ -289,8 +285,8 @@ def render_headers(self, **kwargs):

def split_address(address):
"""Split an e-mail address into local part and domain."""
assert isinstance(address, six.text_type),\
"address should be of type %s" % six.text_type.__name__
assert isinstance(address, str),\
"address should be of type str"
if "@" not in address:
local_part = address
domain = None
Expand All @@ -301,10 +297,10 @@ def split_address(address):

def split_local_part(local_part, delimiter=None):
"""Split a local part into local part and extension."""
assert isinstance(local_part, six.text_type),\
"local_part should be of type %s" % six.text_type.__name__
assert isinstance(delimiter, six.text_type) or delimiter is None,\
"delimiter should be of type %s" % six.text_type.__name__
assert isinstance(local_part, str),\
"local_part should be of type str"
assert isinstance(delimiter, str) or delimiter is None,\
"delimiter should be of type str"
extension = None
if local_part.lower() in ["mailer-daemon", "double-bounce"]:
# never split these special addresses
Expand Down Expand Up @@ -346,8 +342,8 @@ def split_mailbox(mailbox, return_extension=False):

def decode(value_bytes, encoding, append_to_error=""):
"""Try to decode the given string."""
assert isinstance(value_bytes, six.binary_type),\
"value_bytes should be of type %s" % six.binary_type.__name__
assert isinstance(value_bytes, bytes),\
"value_bytes should be of type bytes"
if len(value_bytes) == 0:
# short circuit for empty strings
return ""
Expand All @@ -360,13 +356,10 @@ def decode(value_bytes, encoding, append_to_error=""):
encoding["encoding"], "replace"
)
except (TypeError, UnicodeDecodeError) as exc:
six.raise_from(
InternalError(
_("unable to determine encoding of string") +
append_to_error
),
exc
)
raise InternalError(
_("unable to determine encoding of string") +
append_to_error
) from exc
return value


Expand All @@ -378,7 +371,7 @@ def prepare_addresses(addresses, usage="header"):
:return: a string or a list depending on usage value
"""
result = []
if isinstance(addresses, six.text_type):
if isinstance(addresses, str):
addresses = [addresses]
for name, address in getaddresses(addresses):
if not address:
Expand Down
3 changes: 1 addition & 2 deletions modoboa/lib/ldap_utils.py
Expand Up @@ -34,7 +34,6 @@
import ldap

from django.conf import settings
from django.utils import six
from django.utils.encoding import force_bytes, force_str
from django.utils.translation import ugettext as _

Expand Down Expand Up @@ -66,7 +65,7 @@ def _setting(self, name, default):

def _get_conn(self, dn, password):
"""Get a connection from the server."""
conn = ldap.initialize(self.server_uri, bytes_mode=six.PY2)
conn = ldap.initialize(self.server_uri)
conn.set_option(ldap.OPT_X_TLS_DEMAND, True)
conn.set_option(ldap.OPT_DEBUG_LEVEL, 255)
conn.simple_bind_s(
Expand Down

0 comments on commit 09434af

Please sign in to comment.