Browse Source

PEP8 and some code cleanup

sh4nks 9 years ago
parent
commit
7e0db818b3

+ 12 - 10
flaskbb/app.py

@@ -34,19 +34,21 @@ from flaskbb.management.views import management
 from flaskbb.forum.views import forum
 from flaskbb.forum.models import Post, Topic, Category, Forum
 # extensions
-from flaskbb.extensions import db, login_manager, mail, cache, redis_store, \
-    debugtoolbar, migrate, themes, plugin_manager, babel, csrf, allows, limiter
+from flaskbb.extensions import (db, login_manager, mail, cache, redis_store,
+                                debugtoolbar, migrate, themes, plugin_manager,
+                                babel, csrf, allows, limiter)
 # various helpers
-from flaskbb.utils.helpers import format_date, time_since, crop_title, \
-    is_online, render_markup, mark_online, forum_is_unread, topic_is_unread, \
-    render_template
+from flaskbb.utils.helpers import (format_date, time_since, crop_title,
+                                   is_online, render_markup, mark_online,
+                                   forum_is_unread, topic_is_unread,
+                                   render_template)
 from flaskbb.utils.translations import FlaskBBDomain
 # permission checks (here they are used for the jinja filters)
-from flaskbb.utils.requirements import (
-    IsAdmin, IsAtleastModerator, TplCanModerate,
-    CanBanUser, CanEditUser, TplCanDeletePost, TplCanDeleteTopic,
-    TplCanEditPost, TplCanPostTopic, TplCanPostReply
-)
+from flaskbb.utils.requirements import (IsAdmin, IsAtleastModerator,
+                                        CanBanUser, CanEditUser,
+                                        TplCanModerate, TplCanDeletePost,
+                                        TplCanDeleteTopic, TplCanEditPost,
+                                        TplCanPostTopic, TplCanPostReply)
 # app specific configurations
 from flaskbb.utils.settings import flaskbb_config
 

+ 2 - 3
flaskbb/auth/views.py

@@ -75,6 +75,8 @@ limiter.limit(login_rate_limit, error_message=login_rate_limit_message)(auth)
 @auth.route("/login", methods=["GET", "POST"])
 def login():
     """Logs the user in."""
+    if current_user is not None and current_user.is_authenticated:
+        return redirect_or_next(url_for("forum.index"))
 
     current_limit = getattr(g, 'view_rate_limit', None)
     login_recaptcha = False
@@ -83,9 +85,6 @@ def login():
         stats_diff = flaskbb_config["AUTH_REQUESTS"] - window_stats[1]
         login_recaptcha = stats_diff >= flaskbb_config["LOGIN_RECAPTCHA"]
 
-    if current_user is not None and current_user.is_authenticated:
-        return redirect_or_next(url_for("forum.index"))
-
     form = LoginForm(request.form)
     if form.validate_on_submit():
         try:

+ 18 - 0
flaskbb/email.py

@@ -17,6 +17,10 @@ from flaskbb.utils.tokens import make_token
 
 
 def send_reset_token(user):
+    """Sends the reset token to the user's email address.
+
+    :param user: The user object to whom the email should be sent.
+    """
     token = make_token(user=user, operation="reset_password")
     send_email(
         subject=_("Password Recovery Confirmation"),
@@ -35,6 +39,10 @@ def send_reset_token(user):
 
 
 def send_activation_token(user):
+    """Sends the activation token to the user's email address.
+
+    :param user: The user object to whom the email should be sent.
+    """
     token = make_token(user=user, operation="activate_account")
     send_email(
         subject=_("Account Activation"),
@@ -53,6 +61,16 @@ def send_activation_token(user):
 
 
 def send_email(subject, recipients, text_body, html_body, sender=None):
+    """Sends an email to the given recipients.
+
+    :param subject: The subject of the email.
+    :param recipients: A list of recipients.
+    :param text_body: The text body of the email.
+    :param html_body: The html body of the email.
+    :param sender: A two-element tuple consisting of name and address.
+                   If no sender is given, it will fall back to the one you
+                   have configured with ``MAIL_DEFAULT_SENDER``.
+    """
     msg = Message(subject, recipients=recipients, sender=sender)
     msg.body = text_body
     msg.html = html_body

+ 0 - 8
flaskbb/exceptions.py

@@ -21,11 +21,3 @@ class AuthorizationRequired(FlaskBBError, Forbidden):
 
 class AuthenticationError(FlaskBBError):
     description = "Invalid username and password combination."
-
-
-class LoginAttemptsExceeded(FlaskBBError):
-    description = "The user has entered the wrong password too many times."
-
-    def __init__(self, user):
-        super(LoginAttemptsExceeded, self).__init__()
-        self.user = user

+ 2 - 2
flaskbb/forum/models.py

@@ -14,8 +14,8 @@ from flask import url_for, abort
 from sqlalchemy.orm import aliased
 
 from flaskbb.extensions import db
-from flaskbb.utils.helpers import slugify, get_categories_and_forums, \
-    get_forums
+from flaskbb.utils.helpers import (slugify, get_categories_and_forums,
+                                   get_forums)
 from flaskbb.utils.database import CRUDMixin
 from flaskbb.utils.settings import flaskbb_config
 

+ 11 - 24
flaskbb/forum/views.py

@@ -18,33 +18,20 @@ from flask_babelplus import gettext as _
 from flask_allows import Permission, And
 from flaskbb.extensions import db, allows
 from flaskbb.utils.settings import flaskbb_config
-from flaskbb.utils.helpers import (
-    get_online_users, time_diff, format_quote, render_template, do_topic_action
-)
+from flaskbb.utils.helpers import (get_online_users, time_diff, format_quote,
+                                   render_template, do_topic_action)
 
-from flaskbb.utils.requirements import (
-    CanAccessForum,
-    CanAccessTopic,
-    CanDeletePost,
-    CanDeleteTopic,
-    CanEditPost,
-    CanPostReply,
-    CanPostTopic,
-    IsAtleastModeratorInForum,
-)
+from flaskbb.utils.requirements import (CanAccessForum, CanAccessTopic,
+                                        CanDeletePost, CanDeleteTopic,
+                                        CanEditPost, CanPostReply,
+                                        CanPostTopic,
+                                        IsAtleastModeratorInForum)
 
 
-from flaskbb.forum.models import (
-    Category, Forum, Topic, Post, ForumsRead, TopicsRead
-)
-from flaskbb.forum.forms import (
-    NewTopicForm,
-    QuickreplyForm,
-    ReplyForm,
-    ReportForm,
-    SearchPageForm,
-    UserSearchForm,
-)
+from flaskbb.forum.models import (Category, Forum, Topic, Post, ForumsRead,
+                                  TopicsRead)
+from flaskbb.forum.forms import (NewTopicForm, QuickreplyForm, ReplyForm,
+                                 ReportForm, SearchPageForm, UserSearchForm)
 from flaskbb.user.models import User
 
 forum = Blueprint("forum", __name__)

+ 14 - 16
flaskbb/management/forms.py

@@ -9,16 +9,12 @@
     :license: BSD, see LICENSE for more details.
 """
 from flask_wtf import Form
-from wtforms import (
-    BooleanField, HiddenField, IntegerField, PasswordField,
-    SelectField, StringField, SubmitField, TextAreaField,
-)
-from wtforms.validators import (
-    DataRequired, Optional, Email, regexp, Length, URL, ValidationError
-)
-from wtforms.ext.sqlalchemy.fields import (
-    QuerySelectField, QuerySelectMultipleField
-)
+from wtforms import (BooleanField, HiddenField, IntegerField, PasswordField,
+                     SelectField, StringField, SubmitField, TextAreaField)
+from wtforms.validators import (DataRequired, Optional, Email, regexp, Length,
+                                URL, ValidationError)
+from wtforms.ext.sqlalchemy.fields import (QuerySelectField,
+                                           QuerySelectMultipleField)
 from sqlalchemy.orm.session import make_transient, make_transient_to_detached
 from flask_babelplus import lazy_gettext as _
 
@@ -187,21 +183,23 @@ class GroupForm(Form):
     )
     deletepost = BooleanField(
         _("Can delete posts"),
-        description=_("Check this is the users in this group can delete posts.")
+        description=_("Check this if the users in this group can delete "
+                      "posts.")
     )
     deletetopic = BooleanField(
         _("Can delete topics"),
-        description=_("Check this is the users in this group can delete "
+        description=_("Check this if the users in this group can delete "
                       "topics.")
     )
     posttopic = BooleanField(
         _("Can create topics"),
-        description=_("Check this is the users in this group can create "
+        description=_("Check this if the users in this group can create "
                       "topics.")
     )
     postreply = BooleanField(
         _("Can post replies"),
-        description=_("Check this is the users in this group can post replies.")
+        description=_("Check this if the users in this group can post "
+                      "replies.")
     )
 
     mod_edituser = BooleanField(
@@ -311,8 +309,8 @@ class ForumForm(Form):
 
     moderators = StringField(
         _("Moderators"),
-        description=_("Comma seperated usernames. Leave it blank if you do not "
-                      "want to set any moderators.")
+        description=_("Comma seperated usernames. Leave it blank if you do "
+                      "not want to set any moderators.")
     )
 
     show_moderators = BooleanField(

+ 3 - 4
flaskbb/management/views.py

@@ -22,10 +22,9 @@ from flaskbb import __version__ as flaskbb_version
 from flaskbb._compat import iteritems
 from flaskbb.forum.forms import UserSearchForm
 from flaskbb.utils.settings import flaskbb_config
-from flaskbb.utils.requirements import (
-    IsAtleastModerator, IsAdmin, CanBanUser, CanEditUser,
-    IsAtleastSuperModerator
-)
+from flaskbb.utils.requirements import (IsAtleastModerator, IsAdmin,
+                                        CanBanUser, CanEditUser,
+                                        IsAtleastSuperModerator)
 from flaskbb.extensions import db, allows
 from flaskbb.utils.helpers import render_template, time_diff, get_online_users
 from flaskbb.user.models import Guest, User, Group

+ 3 - 1
flaskbb/plugins/__init__.py

@@ -32,7 +32,9 @@ class FlaskBBPlugin(Plugin):
     def uninstallable(self):
         """Is ``True`` if the Plugin can be uninstalled."""
         if self.installable:
-            group = SettingsGroup.query.filter_by(key=self.settings_key).first()
+            group = SettingsGroup.query.\
+                filter_by(key=self.settings_key).\
+                first()
             if group and len(group.settings.all()) > 0:
                 return True
             return False

+ 2 - 2
flaskbb/plugins/portal/views.py

@@ -36,7 +36,6 @@ def index():
         flash(_("Please install the plugin first to configure the forums "
               "which should be displayed"), "warning")
 
-
     group_ids = [group.id for group in current_user.groups]
     forums = Forum.query.filter(Forum.groups.any(Group.id.in_(group_ids)))
 
@@ -66,7 +65,8 @@ def index():
         online_users = len(get_online_users())
         online_guests = len(get_online_users(guest=True))
 
-    return render_template("index.html", news=news, recent_topics=recent_topics,
+    return render_template("index.html", news=news,
+                           recent_topics=recent_topics,
                            user_count=user_count, topic_count=topic_count,
                            post_count=post_count, newest_user=newest_user,
                            online_guests=online_guests,

+ 2 - 2
flaskbb/user/models.py

@@ -9,7 +9,7 @@
     :license: BSD, see LICENSE for more details.
 """
 import os
-from datetime import datetime, timedelta
+from datetime import datetime
 
 from werkzeug.security import generate_password_hash, check_password_hash
 from flask import url_for
@@ -17,7 +17,7 @@ from flask_login import UserMixin, AnonymousUserMixin
 
 from flaskbb._compat import max_integer
 from flaskbb.extensions import db, cache
-from flaskbb.exceptions import AuthenticationError, LoginAttemptsExceeded
+from flaskbb.exceptions import AuthenticationError
 from flaskbb.utils.settings import flaskbb_config
 from flaskbb.utils.database import CRUDMixin
 from flaskbb.forum.models import (Post, Topic, topictracker, TopicsRead,

+ 4 - 3
flaskbb/utils/helpers.py

@@ -82,7 +82,8 @@ def do_topic_action(topics, user, action, reverse):
                     For example, to unlock a topic, ``reverse`` should be
                     set to ``True``.
     """
-    from flaskbb.utils.requirements import IsAtleastModeratorInForum, CanDeleteTopic
+    from flaskbb.utils.requirements import (IsAtleastModeratorInForum,
+                                            CanDeleteTopic)
 
     from flaskbb.user.models import User
     from flaskbb.forum.models import Post
@@ -263,7 +264,7 @@ def topic_is_unread(topic, topicsread, user, forumsread=None):
     # topicsread is none if the user has marked the forum as read
     # or if he hasn't visited yet
     if topicsread is None:
-        # user has cleared the forum sometime ago - check if there is a new post
+        # user has cleared the forum - check if there is a new post
         if forumsread and forumsread.cleared is not None:
             return forumsread.cleared < topic.last_post.date_created
 
@@ -469,7 +470,7 @@ def get_image_info(url):
                     h, w = struct.unpack(b">HH", jpeg.read(4))
                     break
                 else:
-                    jpeg.read(int(struct.unpack(b">H", jpeg.read(2))[0])-2)
+                    jpeg.read(int(struct.unpack(b">H", jpeg.read(2))[0]) - 2)
                 b = jpeg.read(1)
             width = int(w)
             height = int(h)

+ 0 - 1
flaskbb/utils/populate.py

@@ -8,7 +8,6 @@
     :copyright: (c) 2014 by the FlaskBB Team.
     :license: BSD, see LICENSE for more details.
 """
-from datetime import datetime
 from flaskbb.management.models import Setting, SettingsGroup
 from flaskbb.user.models import User, Group
 from flaskbb.forum.models import Post, Topic, Forum, Category

+ 3 - 3
flaskbb/utils/recaptcha.py

@@ -74,9 +74,9 @@ class RecaptchaValidator(object):
             raise RuntimeError("No RECAPTCHA_PRIVATE_KEY config set")
 
         data = url_encode({
-            'secret':     private_key,
-            'remoteip':   remote_addr,
-            'response':   response
+            'secret': private_key,
+            'remoteip': remote_addr,
+            'response': response
         })
 
         http_response = http.urlopen(RECAPTCHA_VERIFY_SERVER, to_bytes(data))

+ 3 - 3
flaskbb/utils/requirements.py

@@ -7,8 +7,8 @@
     :copyright: (c) 2015 by the FlaskBB Team.
     :license: BSD, see LICENSE for more details
 """
-
 from flask_allows import Requirement, Or, And
+
 from flaskbb.exceptions import FlaskBBError
 from flaskbb.forum.models import Post, Topic, Forum
 from flaskbb.user.models import Group
@@ -107,8 +107,8 @@ class TopicNotLocked(Requirement):
             * Is the topic locked?
             * Is the forum the topic belongs to locked?
 
-        Except in the case of a topic instance being provided to the constructor,
-        all of these tuples are SQLA KeyedTuples
+        Except in the case of a topic instance being provided to the
+        constructor, all of these tuples are SQLA KeyedTuples.
         """
         if self._topic is not None:
             return self._topic.locked, self._topic.forum.locked

+ 3 - 1
flaskbb/utils/widgets.py

@@ -80,7 +80,9 @@ class SelectBirthdayWidget(object):
 
                     # Defaults to blank
                     if value == 1 or value == 1930:
-                        html.append(Select.render_option("None", " ", selected))
+                        html.append(
+                            Select.render_option("None", " ", selected)
+                        )
 
                     html.append(Select.render_option(value, label, selected))