zerver/lib: remove import six.

This commit is contained in:
rht
2017-09-27 10:06:17 +02:00
committed by Tim Abbott
parent 43fd0e8134
commit 035ed93111
17 changed files with 21 additions and 39 deletions

View File

@@ -72,7 +72,6 @@ from django.core.mail import EmailMessage
from django.utils.timezone import now as timezone_now
from confirmation.models import Confirmation, create_confirmation_link
import six
from six.moves import filter
from six.moves import map
from six.moves import range
@@ -1267,7 +1266,7 @@ def check_typing_notification(sender, notification_to, operator):
recipient = recipient_for_emails(notification_to, False,
sender, sender)
except ValidationError as e:
assert isinstance(e.messages[0], six.string_types)
assert isinstance(e.messages[0], str)
raise JsonableError(e.messages[0])
if recipient.type == Recipient.STREAM:
raise ValueError('Forbidden recipient type')
@@ -1438,7 +1437,7 @@ def extract_recipients(s):
except ValueError:
data = s
if isinstance(data, six.string_types):
if isinstance(data, str):
data = data.split(',')
if not isinstance(data, list):
@@ -1608,7 +1607,7 @@ def check_message(sender, client, addressee,
recipient = recipient_for_user_profiles(user_profiles, not_forged_mirror_message,
forwarder_user_profile, sender)
except ValidationError as e:
assert isinstance(e.messages[0], six.string_types)
assert isinstance(e.messages[0], str)
raise JsonableError(e.messages[0])
else:
raise JsonableError(_("Invalid message type"))

View File

@@ -10,7 +10,6 @@ from zerver.models import (
UserProfile,
get_user_including_cross_realm,
)
import six
def user_profiles_from_unvalidated_emails(emails, realm):
# type: (Iterable[Text], Realm) -> List[UserProfile]
@@ -28,7 +27,7 @@ def get_user_profiles(emails, realm):
try:
return user_profiles_from_unvalidated_emails(emails, realm)
except ValidationError as e:
assert isinstance(e.messages[0], six.string_types)
assert isinstance(e.messages[0], str)
raise JsonableError(e.messages[0])
class Addressee(object):

View File

@@ -3,7 +3,6 @@ from django.db.models import Q
from zerver.models import UserProfile, Realm
from zerver.lib.cache import cache_with_key, realm_alert_words_cache_key
import ujson
import six
from typing import Dict, Iterable, List, Text
@cache_with_key(realm_alert_words_cache_key, timeout=3600*24)
@@ -12,7 +11,7 @@ def alert_words_in_realm(realm):
users_query = UserProfile.objects.filter(realm=realm, is_active=True)
alert_word_data = users_query.filter(~Q(alert_words=ujson.dumps([]))).values('id', 'alert_words')
all_user_words = dict((elt['id'], ujson.loads(elt['alert_words'])) for elt in alert_word_data)
user_ids_with_words = dict((user_id, w) for (user_id, w) in six.iteritems(all_user_words) if len(w))
user_ids_with_words = dict((user_id, w) for (user_id, w) in all_user_words.items() if len(w))
return user_ids_with_words
def user_alert_words(user_profile):

View File

@@ -55,7 +55,6 @@ import zerver.lib.alert_words as alert_words
import zerver.lib.mention as mention
from zerver.lib.str_utils import force_str, force_text
from zerver.lib.tex import render_tex
import six
from six.moves import range, html_parser
FullNameInfo = TypedDict('FullNameInfo', {
@@ -1247,7 +1246,7 @@ class AtomicLinkPattern(LinkPattern):
ret = LinkPattern.handleMatch(self, m)
if ret is None:
return None
if not isinstance(ret, six.string_types):
if not isinstance(ret, str):
ret.text = markdown.util.AtomicString(ret.text)
return ret
@@ -1459,7 +1458,7 @@ def maybe_update_realm_filters(realm_filters_key):
if realm_filters_key is None:
all_filters = all_realm_filters()
all_filters[DEFAULT_BUGDOWN_KEY] = []
for realm_filters_key, filters in six.iteritems(all_filters):
for realm_filters_key, filters in all_filters.items():
make_realm_filters(realm_filters_key, filters)
# Hack to ensure that getConfig("realm") is right for mirrored Zephyrs
make_realm_filters(ZEPHYR_MIRROR_BUGDOWN_KEY, [])

View File

@@ -79,7 +79,6 @@ Dependencies:
import re
import subprocess
import markdown
import six
from django.utils.html import escape
from markdown.extensions.codehilite import CodeHilite, CodeHiliteExtension
from zerver.lib.str_utils import force_bytes

View File

@@ -17,7 +17,6 @@ import random
import sys
import os
import hashlib
import six
if False:
from zerver.models import UserProfile, Realm, Message

View File

@@ -29,7 +29,6 @@ from typing import Any, Dict, List, Optional, Text
from zerver.lib.str_utils import force_bytes
import base64
import struct
import six
# Some DER encoding stuff. Bleh. This is because the ccache contains a
# DER-encoded krb5 Ticket structure, whereas Webathena deserializes
@@ -54,7 +53,7 @@ def der_encode_tlv(tag, value):
def der_encode_integer_value(val):
# type: (int) -> bytes
if not isinstance(val, six.integer_types):
if not isinstance(val, int):
raise TypeError("int")
# base 256, MSB first, two's complement, minimum number of octets
# necessary. This has a number of annoying edge cases:

View File

@@ -3,7 +3,6 @@ from typing import Any, Callable, Dict, Iterable, List, Set, Tuple, Text
from collections import defaultdict
import datetime
import pytz
import six
from django.db.models import Q, QuerySet
from django.template import loader

View File

@@ -21,7 +21,6 @@ from zerver.models import Stream, Recipient, \
get_user_profile_by_id, get_display_recipient, get_recipient, \
Message, Realm, UserProfile, get_system_bot
from six import binary_type
import six
import talon
from talon import quotations
@@ -162,7 +161,7 @@ def send_to_missed_message_address(address, message):
# Testing with basestring so we don't depend on the list return type from
# get_display_recipient
if not isinstance(display_recipient, six.string_types):
if not isinstance(display_recipient, str):
recipient_str = u','.join([user['email'] for user in display_recipient])
else:
recipient_str = display_recipient

View File

@@ -1,6 +1,5 @@
import logging
import six
from collections import defaultdict
from django.conf import settings
@@ -52,7 +51,7 @@ def email_browser_error(report):
more_info = report['more_info']
if more_info is not None:
body += "\nAdditional information:"
for (key, value) in six.iteritems(more_info):
for (key, value) in more_info.items():
body += "\n %s: %s" % (key, value)
body += "\n\nLog:\n%s" % (report['log'],)

View File

@@ -2,7 +2,6 @@
# high-level documentation on how this system works.
import copy
import six
import ujson
from django.utils.translation import ugettext as _

View File

@@ -11,8 +11,7 @@ Currently we have strings of 3 semantic types:
typing.Text (which is `str` in python 3 and `unicode` in python 2).
2. binary strings: These strings are used to represent binary data.
This should be of type six.binary_type (which is `bytes` in python 3
and `str` in python 2).
This should be of type `bytes`
3. native strings: These strings are for internal use only. Strings of
this type are not meant to be stored in database, displayed to end
@@ -30,27 +29,25 @@ force_text and force_bytes.
It is recommended to use the utility functions for other string conversions.
"""
import six
from six import binary_type
from typing import Any, Dict, Mapping, Union, TypeVar, Text
NonBinaryStr = TypeVar('NonBinaryStr', str, Text)
# This is used to represent text or native strings
def force_text(s, encoding='utf-8'):
# type: (Union[Text, binary_type], str) -> Text
# type: (Union[Text, bytes], str) -> Text
"""converts a string to a text string"""
if isinstance(s, Text):
return s
elif isinstance(s, binary_type):
elif isinstance(s, bytes):
return s.decode(encoding)
else:
raise TypeError("force_text expects a string type")
def force_bytes(s, encoding='utf-8'):
# type: (Union[Text, binary_type], str) -> binary_type
# type: (Union[Text, bytes], str) -> bytes
"""converts a string to binary string"""
if isinstance(s, binary_type):
if isinstance(s, bytes):
return s
elif isinstance(s, Text):
return s.encode(encoding)
@@ -58,13 +55,13 @@ def force_bytes(s, encoding='utf-8'):
raise TypeError("force_bytes expects a string type")
def force_str(s, encoding='utf-8'):
# type: (Union[Text, binary_type], str) -> str
# type: (Union[Text, bytes], str) -> str
"""converts a string to a native string"""
if isinstance(s, str):
return s
elif isinstance(s, Text):
return s.encode(encoding)
elif isinstance(s, binary_type):
elif isinstance(s, bytes):
return s.decode(encoding)
else:
raise TypeError("force_str expects a string type")
@@ -72,7 +69,7 @@ def force_str(s, encoding='utf-8'):
def dict_with_str_keys(dct, encoding='utf-8'):
# type: (Mapping[NonBinaryStr, Any], str) -> Dict[str, Any]
"""applies force_str on the keys of a dict (non-recursively)"""
return {force_str(key, encoding): value for key, value in six.iteritems(dct)}
return {force_str(key, encoding): value for key, value in dct.items()}
class ModelReprMixin(object):
"""

View File

@@ -61,7 +61,6 @@ from six import binary_type
from zerver.lib.str_utils import NonBinaryStr
from contextlib import contextmanager
import six
API_KEYS = {} # type: Dict[Text, Text]
@@ -380,7 +379,7 @@ class ZulipTestCase(TestCase):
message_type_name = "stream"
else:
raise AssertionError("Recipient type should be an Recipient.STREAM type enum")
if isinstance(raw_recipients, six.string_types):
if isinstance(raw_recipients, str):
recipient_list = [raw_recipients]
else:
recipient_list = raw_recipients

View File

@@ -58,7 +58,6 @@ from six import binary_type
from zerver.lib.str_utils import NonBinaryStr
from contextlib import contextmanager
import six
import fakeldap
import ldap

View File

@@ -1,11 +1,11 @@
from types import TracebackType
from typing import Any, Callable, Optional, Tuple, Type, TypeVar
import six
import sys
import time
import ctypes
import threading
import six
from six.moves import range
# Based on http://code.activestate.com/recipes/483752/

View File

@@ -23,7 +23,6 @@ from sqlalchemy.sql import (
Selectable
)
import six
import ujson
def get_topic_mutes(user_profile):

View File

@@ -28,7 +28,6 @@ for any particular type of object.
from django.utils.translation import ugettext as _
from django.core.exceptions import ValidationError
from django.core.validators import validate_email, URLValidator
import six
from typing import Any, Callable, Iterable, Optional, Tuple, TypeVar, Text
from zerver.lib.request import JsonableError
@@ -37,7 +36,7 @@ Validator = Callable[[str, Any], Optional[str]]
def check_string(var_name, val):
# type: (str, Any) -> Optional[str]
if not isinstance(val, six.string_types):
if not isinstance(val, str):
return _('%s is not a string') % (var_name,)
return None