Browse Source

Remove Python 2 compatibility stuff

Peter Justin 4 years ago
parent
commit
b56b88d933

+ 0 - 44
flaskbb/_compat.py

@@ -1,44 +0,0 @@
-"""
-Look here for more information:
-https://github.com/mitsuhiko/flask/blob/master/flask/_compat.py
-"""
-
-import sys
-
-PY2 = sys.version_info[0] == 2
-
-if not PY2:  # pragma: no cover
-    from abc import ABC
-    text_type = str
-    string_types = (str, )
-    integer_types = (int, )
-    intern_method = sys.intern
-    range_method = range
-    iterkeys = lambda d: iter(d.keys())
-    itervalues = lambda d: iter(d.values())
-    iteritems = lambda d: iter(d.items())
-else:  # pragma: no cover
-    from abc import ABCMeta
-    ABC = ABCMeta('ABC', (object, ), {})
-    text_type = unicode
-    string_types = (str, unicode)
-    integer_types = (int, long)
-    intern_method = intern
-    range_method = xrange
-    iterkeys = lambda d: d.iterkeys()
-    itervalues = lambda d: d.itervalues()
-    iteritems = lambda d: d.iteritems()
-
-
-def to_bytes(text, encoding='utf-8'):
-    """Transform string to bytes."""
-    if isinstance(text, text_type):
-        text = text.encode(encoding)
-    return text
-
-
-def to_unicode(input_bytes, encoding='utf-8'):
-    """Decodes input_bytes to text if needed."""
-    if not isinstance(input_bytes, text_type):
-        input_bytes = input_bytes.decode(encoding)
-    return input_bytes

+ 5 - 5
flaskbb/app.py

@@ -22,7 +22,6 @@ from sqlalchemy import event
 from sqlalchemy.engine import Engine
 from sqlalchemy.exc import OperationalError, ProgrammingError
 
-from flaskbb._compat import iteritems, string_types
 # extensions
 from flaskbb.extensions import (alembic, allows, babel, cache, celery, csrf,
                                 db, debugtoolbar, limiter, login_manager, mail,
@@ -62,6 +61,7 @@ from .forum import views as forum_views  # noqa
 from .management import views as management_views  # noqa
 from .user import views as user_views  # noqa
 
+
 logger = logging.getLogger(__name__)
 
 
@@ -110,7 +110,7 @@ def configure_app(app, config):
     app.config.from_object("flaskbb.configs.default.DefaultConfig")
     config = get_flaskbb_config(app, config)
     # Path
-    if isinstance(config, string_types):
+    if isinstance(config, str):
         app.config.from_pyfile(config)
     # Module
     else:
@@ -131,7 +131,7 @@ def configure_app(app, config):
     # Setting up logging as early as possible
     configure_logging(app)
 
-    if not isinstance(config, string_types) and config is not None:
+    if not isinstance(config, str) and config is not None:
         config_name = "{}.{}".format(config.__module__, config.__name__)
     else:
         config_name = config
@@ -438,7 +438,7 @@ def load_plugins(app):
     # ('None' - appears on py2) and thus using a set
     flaskbb_modules = set(
         module
-        for name, module in iteritems(sys.modules)
+        for name, module in sys.modules.items()
         if name.startswith("flaskbb")
     )
     for module in flaskbb_modules:
@@ -489,7 +489,7 @@ def load_plugins(app):
     disabled_plugins = [
         p.__package__ for p in app.pluggy.get_disabled_plugins()
     ]
-    for task_name, task in iteritems(tasks):
+    for task_name, task in tasks.items():
         if task.__module__.split(".")[0] in disabled_plugins:
             logger.debug("Unregistering task: '{}'".format(task))
             celery.tasks.unregister(task_name)

+ 1 - 4
flaskbb/core/auth/activation.py

@@ -8,10 +8,7 @@
     :copyright: (c) 2014-2018 the FlaskBB Team
     :license: BSD, see LICENSE for more details
 """
-
-from abc import abstractmethod
-
-from ..._compat import ABC
+from abc import ABC, abstractmethod
 
 
 class AccountActivator(ABC):

+ 1 - 2
flaskbb/core/auth/authentication.py

@@ -6,9 +6,8 @@
     :license: BSD, see LICENSE for more details
 """
 
-from abc import abstractmethod
+from abc import ABC, abstractmethod
 
-from ..._compat import ABC
 from ..exceptions import BaseFlaskBBError
 
 

+ 1 - 4
flaskbb/core/auth/password.py

@@ -8,10 +8,7 @@
     :copyright: (c) 2014-2018 the FlaskBB Team.
     :license: BSD, see LICENSE for more details
 """
-
-from abc import abstractmethod
-
-from ..._compat import ABC
+from abc import ABC, abstractmethod
 
 
 class ResetPasswordService(ABC):

+ 1 - 4
flaskbb/core/auth/registration.py

@@ -9,13 +9,10 @@
     :copyright: (c) 2014-2018 by the FlaskBB Team.
     :license: BSD, see LICENSE for more details.
 """
-
-from abc import abstractmethod
+from abc import ABC, abstractmethod
 
 import attr
 
-from ..._compat import ABC
-
 
 @attr.s(hash=True, eq=False, order=False, repr=True, frozen=True)
 class UserRegistrationInfo(object):

+ 1 - 2
flaskbb/core/changesets.py

@@ -9,10 +9,9 @@
     :license: BSD, see LICENSE for more details
 """
 
-from abc import abstractmethod
+from abc import ABC, abstractmethod
 from inspect import isclass
 
-from .._compat import ABC
 
 empty = None
 

+ 1 - 2
flaskbb/core/tokens.py

@@ -9,12 +9,11 @@
     :copyright: (c) 2014-2018 by the FlaskBB Team.
     :license: BSD, see LICENSE for more details
 """
-from abc import abstractmethod
+from abc import ABC, abstractmethod
 
 import attr
 from flask_babelplus import gettext as _
 
-from .._compat import ABC
 from .exceptions import BaseFlaskBBError
 
 

+ 1 - 2
flaskbb/core/user/update.py

@@ -10,11 +10,10 @@
     :license: BSD, see LICENSE for more details.
 """
 
-from abc import abstractmethod
+from abc import ABC, abstractmethod
 
 import attr
 
-from ..._compat import ABC
 from ..changesets import empty, is_empty
 
 

+ 1 - 3
flaskbb/deprecation.py

@@ -8,7 +8,7 @@
     :copyright: (c) 2018 the FlaskBB Team.
     :license: BSD, see LICENSE for more details.
 """
-
+from abc import ABC
 import inspect
 import warnings
 from abc import abstractproperty
@@ -16,8 +16,6 @@ from functools import wraps
 
 from flask_babelplus import gettext as _
 
-from ._compat import ABC
-
 
 class FlaskBBWarning(Warning):
     """

+ 1 - 3
flaskbb/display/navigation.py

@@ -8,13 +8,11 @@
     :copyright: (c) 2018 the FlaskBB Team
     :license: BSD, see LICENSE for more details
 """
-
-from abc import abstractproperty
+from abc import ABC, abstractproperty
 from enum import Enum
 
 import attr
 
-from .._compat import ABC
 
 __all__ = (
     "NavigationContentType",

+ 1 - 2
flaskbb/management/models.py

@@ -10,7 +10,6 @@
 """
 import logging
 
-from flaskbb._compat import iteritems
 from flaskbb.extensions import cache, db
 from flaskbb.utils.database import CRUDMixin
 from flaskbb.utils.forms import SettingValueType, generate_settings_form
@@ -75,7 +74,7 @@ class Setting(db.Model, CRUDMixin):
         :param settings: A dictionary with setting items.
         """
         # update the database
-        for key, value in iteritems(settings):
+        for key, value in settings.items():
             setting = cls.query.filter(Setting.key == key.lower()).first()
 
             setting.value = value

+ 1 - 2
flaskbb/plugins/models.py

@@ -13,7 +13,6 @@ from flask import current_app
 from sqlalchemy import UniqueConstraint
 from sqlalchemy.orm.collections import attribute_mapped_collection
 
-from flaskbb._compat import itervalues
 from flaskbb.extensions import db
 from flaskbb.utils.database import CRUDMixin
 from flaskbb.utils.forms import generate_settings_form, SettingValueType
@@ -71,7 +70,7 @@ class PluginRegistry(CRUDMixin, db.Model):
     @property
     def settings(self):
         """Returns a dict with contains all the settings in a plugin."""
-        return {kv.key: kv.value for kv in itervalues(self.values)}
+        return {kv.key: kv.value for kv in self.values.values()}
 
     @property
     def info(self):

+ 0 - 14
flaskbb/utils/datastructures.py

@@ -9,20 +9,6 @@
     :license: BSD, see LICENSE for more details.
 """
 import sys
-try:
-    from types import SimpleNamespace
-except ImportError:
-    class SimpleNamespace(dict):
-
-        def __getattr__(self, name):
-            try:
-                return super(SimpleNamespace, self).__getitem__(name)
-            except KeyError:
-                raise AttributeError('{0} has no attribute {1}'
-                                     .format(self.__class__.__name__, name))
-
-        def __setattr__(self, name, value):
-            super(SimpleNamespace, self).__setitem__(name, value)
 
 
 class TemplateEventResult(list):

+ 3 - 7
flaskbb/utils/fields.py

@@ -12,11 +12,7 @@
 """
 from datetime import datetime
 import logging
-try:
-    import urllib2 as http
-except ImportError:
-    # Python 3
-    from urllib import request as http
+import urllib
 
 from flask import request, current_app, Markup, json
 from werkzeug.urls import url_encode
@@ -24,7 +20,7 @@ from wtforms import ValidationError
 from wtforms.fields import DateField, Field
 from wtforms.widgets.core import Select, html_params
 
-from flaskbb._compat import to_bytes, to_unicode
+from flaskbb.utils.helpers import to_bytes, to_unicode
 from flaskbb.utils.settings import flaskbb_config
 
 
@@ -86,7 +82,7 @@ class RecaptchaValidator(object):
             'response': response
         })
 
-        http_response = http.urlopen(RECAPTCHA_VERIFY_SERVER, to_bytes(data))
+        http_response = urllib.request.urlopen(RECAPTCHA_VERIFY_SERVER, to_bytes(data))
 
         if http_response.code != 200:
             return False

+ 4 - 5
flaskbb/utils/forms.py

@@ -11,7 +11,6 @@
 from wtforms import (TextField, IntegerField, FloatField, BooleanField,
                      SelectField, SelectMultipleField, validators)
 from flask_wtf import FlaskForm
-from flaskbb._compat import text_type, iteritems
 from enum import Enum
 
 
@@ -35,7 +34,7 @@ class SettingValueType(Enum):
 
 def populate_settings_dict(form, settings):
     new_settings = {}
-    for key, value in iteritems(settings):
+    for key, value in settings.items():
         try:
             # check if the value has changed
             if value == form[key].data:
@@ -49,7 +48,7 @@ def populate_settings_dict(form, settings):
 
 
 def populate_settings_form(form, settings):
-    for key, value in iteritems(settings):
+    for key, value in settings.items():
         try:
             form[key].data = value
         except (KeyError, ValueError):
@@ -118,7 +117,7 @@ def generate_settings_form(settings):  # noqa: C901
             if "coerce" in setting.extra:
                 coerce_to = setting.extra['coerce']
             else:
-                coerce_to = text_type
+                coerce_to = str
 
             setattr(
                 SettingsForm, setting.key,
@@ -136,7 +135,7 @@ def generate_settings_form(settings):  # noqa: C901
             if "coerce" in setting.extra:
                 coerce_to = setting.extra['coerce']
             else:
-                coerce_to = text_type
+                coerce_to = str
 
             setattr(
                 SettingsForm, setting.key,

+ 18 - 10
flaskbb/utils/helpers.py

@@ -38,21 +38,29 @@ from pytz import UTC
 from werkzeug.local import LocalProxy
 from werkzeug.utils import ImportStringError, import_string
 
-from flaskbb._compat import (iteritems, range_method, string_types, text_type,
-                             to_bytes, to_unicode)
 from flaskbb.extensions import babel, redis_store
 from flaskbb.utils.settings import flaskbb_config
 
-try:  # compat
-    FileNotFoundError
-except NameError:
-    FileNotFoundError = IOError
 
 logger = logging.getLogger(__name__)
 
 _punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
 
 
+def to_bytes(text, encoding="utf-8"):
+    """Transform string to bytes."""
+    if isinstance(text, str):
+        text = text.encode(encoding)
+    return text
+
+
+def to_unicode(input_bytes, encoding="utf-8"):
+    """Decodes input_bytes to text if needed."""
+    if not isinstance(input_bytes, str):
+        input_bytes = input_bytes.decode(encoding)
+    return input_bytes
+
+
 def slugify(text, delim=u"-"):
     """Generates an slightly worse ASCII-only slug.
     Taken from the Flask Snippets page.
@@ -65,7 +73,7 @@ def slugify(text, delim=u"-"):
     for word in _punct_re.split(text.lower()):
         if word:
             result.append(word)
-    return text_type(delim.join(result))
+    return str(delim.join(result))
 
 
 def redirect_or_next(endpoint, **kwargs):
@@ -366,7 +374,7 @@ def get_online_users(guest=False):  # pragma: no cover
     :param guest: If True, it will return the online guests
     """
     current = int(time.time()) // 60
-    minutes = range_method(flaskbb_config["ONLINE_LAST_MINUTES"])
+    minutes = range(flaskbb_config["ONLINE_LAST_MINUTES"])
     if guest:
         users = redis_store.sunion(
             ["online-guests/%d" % (current - x) for x in minutes]
@@ -647,7 +655,7 @@ def app_config_from_env(app, prefix="FLASKBB_"):
     :param app: The application object.
     :param prefix: The prefix of the environment variables.
     """
-    for key, value in iteritems(os.environ):
+    for key, value in os.environ.items():
         if key.startswith(prefix):
             key = key[len(prefix) :]
             try:
@@ -672,7 +680,7 @@ def get_flaskbb_config(app, config_file):
     """
     if config_file is not None:
         # config is an object
-        if not isinstance(config_file, string_types):
+        if not isinstance(config_file, str):
             return config_file
 
         # config is a file

+ 20 - 21
flaskbb/utils/search.py

@@ -13,7 +13,6 @@ import logging
 import whoosh
 from flask_whooshee import AbstractWhoosheer
 
-from flaskbb._compat import text_type
 from flaskbb.forum.models import Forum, Topic, Post
 from flaskbb.user.models import User
 
@@ -35,18 +34,18 @@ class PostWhoosheer(AbstractWhoosheer):
     def update_post(cls, writer, post):
         writer.update_document(
             post_id=post.id,
-            username=text_type(post.username),
-            modified_by=text_type(post.modified_by),
-            content=text_type(post.content)
+            username=str(post.username),
+            modified_by=str(post.modified_by),
+            content=str(post.content)
         )
 
     @classmethod
     def insert_post(cls, writer, post):
         writer.add_document(
             post_id=post.id,
-            username=text_type(post.username),
-            modified_by=text_type(post.modified_by),
-            content=text_type(post.content)
+            username=str(post.username),
+            modified_by=str(post.modified_by),
+            content=str(post.content)
         )
 
     @classmethod
@@ -68,18 +67,18 @@ class TopicWhoosheer(AbstractWhoosheer):
     def update_topic(cls, writer, topic):
         writer.update_document(
             topic_id=topic.id,
-            title=text_type(topic.title),
-            username=text_type(topic.username),
-            content=text_type(getattr(topic.first_post, 'content', None))
+            title=str(topic.title),
+            username=str(topic.username),
+            content=str(getattr(topic.first_post, 'content', None))
         )
 
     @classmethod
     def insert_topic(cls, writer, topic):
         writer.add_document(
             topic_id=topic.id,
-            title=text_type(topic.title),
-            username=text_type(topic.username),
-            content=text_type(getattr(topic.first_post, 'content', None))
+            title=str(topic.title),
+            username=str(topic.username),
+            content=str(getattr(topic.first_post, 'content', None))
         )
 
     @classmethod
@@ -100,16 +99,16 @@ class ForumWhoosheer(AbstractWhoosheer):
     def update_forum(cls, writer, forum):
         writer.update_document(
             forum_id=forum.id,
-            title=text_type(forum.title),
-            description=text_type(forum.description)
+            title=str(forum.title),
+            description=str(forum.description)
         )
 
     @classmethod
     def insert_forum(cls, writer, forum):
         writer.add_document(
             forum_id=forum.id,
-            title=text_type(forum.title),
-            description=text_type(forum.description)
+            title=str(forum.title),
+            description=str(forum.description)
         )
 
     @classmethod
@@ -130,16 +129,16 @@ class UserWhoosheer(AbstractWhoosheer):
     def update_user(cls, writer, user):
         writer.update_document(
             user_id=user.id,
-            username=text_type(user.username),
-            email=text_type(user.email)
+            username=str(user.username),
+            email=str(user.email)
         )
 
     @classmethod
     def insert_user(cls, writer, user):
         writer.add_document(
             user_id=user.id,
-            username=text_type(user.username),
-            email=text_type(user.email)
+            username=str(user.username),
+            email=str(user.email)
         )
 
     @classmethod