Просмотр исходного кода

Merge branch 'small-code-cleanups' of https://github.com/hkupty/flaskbb into hkupty-small-code-cleanups

Conflicts:
	flaskbb/forum/views.py
	flaskbb/management/forms.py
sh4nks 10 лет назад
Родитель
Сommit
d527ae29ed
5 измененных файлов с 147 добавлено и 109 удалено
  1. 4 2
      flaskbb/app.py
  2. 69 44
      flaskbb/forum/views.py
  3. 52 33
      flaskbb/management/forms.py
  4. 15 24
      flaskbb/management/models.py
  5. 7 6
      flaskbb/management/views.py

+ 4 - 2
flaskbb/app.py

@@ -74,7 +74,9 @@ def configure_blueprints(app):
     app.register_blueprint(forum, url_prefix=app.config["FORUM_URL_PREFIX"])
     app.register_blueprint(user, url_prefix=app.config["USER_URL_PREFIX"])
     app.register_blueprint(auth, url_prefix=app.config["AUTH_URL_PREFIX"])
-    app.register_blueprint(management, url_prefix=app.config["ADMIN_URL_PREFIX"])
+    app.register_blueprint(
+        management, url_prefix=app.config["ADMIN_URL_PREFIX"]
+    )
 
 
 def configure_extensions(app):
@@ -125,7 +127,7 @@ def configure_extensions(app):
         Loads the user. Required by the `login` extension
         """
         unread_count = db.session.query(db.func.count(PrivateMessage.id)).\
-            filter(PrivateMessage.unread == True,
+            filter(PrivateMessage.unread,
                    PrivateMessage.user_id == id).subquery()
         u = db.session.query(User, unread_count).filter(User.id == id).first()
 

+ 69 - 44
flaskbb/forum/views.py

@@ -26,7 +26,7 @@ from flaskbb.forum.models import (Category, Forum, Topic, Post, ForumsRead,
                                   TopicsRead)
 from flaskbb.forum.forms import (QuickreplyForm, ReplyForm, NewTopicForm,
                                  ReportForm, UserSearchForm, SearchPageForm)
-from flaskbb.user.models import User, Group
+from flaskbb.user.models import User
 
 forum = Blueprint("forum", __name__)
 
@@ -77,16 +77,21 @@ def view_category(category_id, slug=None):
 def view_forum(forum_id, slug=None):
     page = request.args.get('page', 1, type=int)
 
-    forum, forumsread = Forum.get_forum(forum_id=forum_id, user=current_user)
+    forum_instance, forumsread = Forum.get_forum(forum_id=forum_id,
+                                                 user=current_user)
 
-    if forum.external:
-        return redirect(forum.external)
+    if forum_instance.external:
+        return redirect(forum_instance.external)
 
-    topics = Forum.get_topics(forum_id=forum.id, user=current_user, page=page,
-                              per_page=flaskbb_config["TOPICS_PER_PAGE"])
+    topics = Forum.get_topics(
+        forum_id=forum_instance.id, user=current_user, page=page,
+        per_page=flaskbb_config["TOPICS_PER_PAGE"]
+    )
 
-    return render_template("forum/forum.html", forum=forum, topics=topics,
-                           forumsread=forumsread,)
+    return render_template(
+        "forum/forum.html", forum=forum_instance,
+        topics=topics, forumsread=forumsread,
+    )
 
 
 @forum.route("/topic/<int:topic_id>", methods=["POST", "GET"])
@@ -148,23 +153,28 @@ def view_post(post_id):
 @forum.route("/<int:forum_id>-<slug>/topic/new", methods=["POST", "GET"])
 @login_required
 def new_topic(forum_id, slug=None):
-    forum = Forum.query.filter_by(id=forum_id).first_or_404()
+    forum_instance = Forum.query.filter_by(id=forum_id).first_or_404()
 
     if not can_post_topic(user=current_user, forum=forum):
-        flash("You do not have the permissions to create a new topic.", "danger")
+        flash("You do not have the permissions to create a new topic.",
+              "danger")
         return redirect(forum.url)
 
     form = NewTopicForm()
     if form.validate_on_submit():
         if request.form['button'] == 'preview':
-            return render_template("forum/new_topic.html", forum=forum,
-                                   form=form, preview=form.content.data)
+            return render_template(
+                "forum/new_topic.html", forum=forum_instance,
+                form=form, preview=form.content.data
+            )
         else:
-            topic = form.save(current_user, forum)
+            topic = form.save(current_user, forum_instance)
 
             # redirect to the new topic
             return redirect(url_for('forum.view_topic', topic_id=topic.id))
-    return render_template("forum/new_topic.html", forum=forum, form=form)
+    return render_template(
+        "forum/new_topic.html", forum=forum_instance, form=form
+    )
 
 
 @forum.route("/topic/<int:topic_id>/delete")
@@ -220,23 +230,28 @@ def unlock_topic(topic_id, slug=None):
 
 
 @forum.route("/topic/<int:topic_id>/move/<int:forum_id>")
-@forum.route("/topic/<int:topic_id>-<topic_slug>/move/<int:forum_id>-<forum_slug>")
+@forum.route(
+    "/topic/<int:topic_id>-<topic_slug>/move/<int:forum_id>-<forum_slug>"
+)
 @login_required
 def move_topic(topic_id, forum_id, topic_slug=None, forum_slug=None):
-    forum = Forum.query.filter_by(id=forum_id).first_or_404()
+    forum_instance = Forum.query.filter_by(id=forum_id).first_or_404()
     topic = Topic.query.filter_by(id=topic_id).first_or_404()
 
     # TODO: Bulk move
 
     if not can_moderate(user=current_user, forum=topic.forum):
-        flash("You do not have the permissions to move this topic", "danger")
-        return redirect(forum.url)
-
-    if not topic.move(forum):
-        flash("Could not move the topic to forum %s" % forum.title, "danger")
+        flash("Yo do not have the permissions to move this topic", "danger")
+        return redirect(forum_instance.url)
+
+    if not topic.move(forum_instance):
+        flash(
+            "Could not move the topic to forum %s" % forum_instance.title,
+            "danger"
+        )
         return redirect(topic.url)
 
-    flash("Topic was moved to forum %s" % forum.title, "success")
+    flash("Topic was moved to forum %s" % forum_instance.title, "success")
     return redirect(topic.url)
 
 
@@ -244,21 +259,22 @@ def move_topic(topic_id, forum_id, topic_slug=None, forum_slug=None):
 @forum.route("/topic/<int:old_id>-<old_slug>/merge/<int:new_id>-<new_slug>")
 @login_required
 def merge_topic(old_id, new_id, old_slug=None, new_slug=None):
-    old_topic = Topic.query.filter_by(id=old_id).first_or_404()
-    new_topic = Topic.query.filter_by(id=new_id).first_or_404()
+    _old_topic = Topic.query.filter_by(id=old_id).first_or_404()
+    _new_topic = Topic.query.filter_by(id=new_id).first_or_404()
 
     # TODO: Bulk merge
 
-    if not can_moderate(user=current_user, forum=old_topic.forum):
+    # Looks to me that the user should have permissions on both forums, right?
+    if not can_moderate(user=current_user, forum=_old_topic.forum):
         flash("Yo do not have the permissions to merge this topic", "danger")
-        return redirect(old_topic.url)
+        return redirect(_old_topic.url)
 
-    if not old_topic.merge(new_topic):
+    if not _old_topic.merge(_new_topic):
         flash("Could not merge the topic.", "danger")
-        return redirect(old_topic.url)
+        return redirect(_old_topic.url)
 
     flash("Topic succesfully merged.", "success")
-    return redirect(new_topic.url)
+    return redirect(_new_topic.url)
 
 
 @forum.route("/topic/<int:topic_id>/post/new", methods=["POST", "GET"])
@@ -274,8 +290,10 @@ def new_post(topic_id, slug=None):
     form = ReplyForm()
     if form.validate_on_submit():
         if request.form['button'] == 'preview':
-            return render_template("forum/new_post.html", topic=topic,
-                                   form=form, preview=form.content.data)
+            return render_template(
+                "forum/new_post.html", topic=topic,
+                form=form, preview=form.content.data
+            )
         else:
             post = form.save(current_user, topic)
             return view_post(post.id)
@@ -283,7 +301,9 @@ def new_post(topic_id, slug=None):
     return render_template("forum/new_post.html", topic=topic, form=form)
 
 
-@forum.route("/topic/<int:topic_id>/post/<int:post_id>/reply", methods=["POST", "GET"])
+@forum.route(
+    "/topic/<int:topic_id>/post/<int:post_id>/reply", methods=["POST", "GET"]
+)
 @login_required
 def reply_post(topic_id, post_id):
     topic = Topic.query.filter_by(id=topic_id).first_or_404()
@@ -296,8 +316,10 @@ def reply_post(topic_id, post_id):
     form = ReplyForm()
     if form.validate_on_submit():
         if request.form['button'] == 'preview':
-            return render_template("forum/new_post.html", topic=topic,
-                                   form=form, preview=form.content.data)
+            return render_template(
+                "forum/new_post.html", topic=topic,
+                form=form, preview=form.content.data
+            )
         else:
             form.save(current_user, topic)
             return redirect(post.topic.url)
@@ -319,8 +341,10 @@ def edit_post(post_id):
     form = ReplyForm()
     if form.validate_on_submit():
         if request.form['button'] == 'preview':
-            return render_template("forum/new_post.html", topic=post.topic,
-                                   form=form, preview=form.content.data)
+            return render_template(
+                "forum/new_post.html", topic=post.topic,
+                form=form, preview=form.content.data
+            )
         else:
             form.populate_obj(post)
             post.date_modified = datetime.datetime.utcnow()
@@ -383,16 +407,17 @@ def raw_post(post_id):
 def markread(forum_id=None, slug=None):
     # Mark a single forum as read
     if forum_id:
-        forum = Forum.query.filter_by(id=forum_id).first_or_404()
-        forumsread = ForumsRead.query.filter_by(user_id=current_user.id,
-                                                forum_id=forum.id).first()
+        forum_instance = Forum.query.filter_by(id=forum_id).first_or_404()
+        forumsread = ForumsRead.query.filter_by(
+            user_id=current_user.id, forum_id=forum_instance.id
+        ).first()
         TopicsRead.query.filter_by(user_id=current_user.id,
-                                   forum_id=forum.id).delete()
+                                   forum_id=forum_instance.id).delete()
 
         if not forumsread:
             forumsread = ForumsRead()
             forumsread.user_id = current_user.id
-            forumsread.forum_id = forum.id
+            forumsread.forum_id = forum_instance.id
 
         forumsread.last_read = datetime.datetime.utcnow()
         forumsread.cleared = datetime.datetime.utcnow()
@@ -400,7 +425,7 @@ def markread(forum_id=None, slug=None):
         db.session.add(forumsread)
         db.session.commit()
 
-        return redirect(forum.url)
+        return redirect(forum_instance.url)
 
     # Mark all forums as read
     ForumsRead.query.filter_by(user_id=current_user.id).delete()
@@ -408,10 +433,10 @@ def markread(forum_id=None, slug=None):
 
     forums = Forum.query.all()
     forumsread_list = []
-    for forum in forums:
+    for forum_instance in forums:
         forumsread = ForumsRead()
         forumsread.user_id = current_user.id
-        forumsread.forum_id = forum.id
+        forumsread.forum_id = forum_instance.id
         forumsread.last_read = datetime.datetime.utcnow()
         forumsread.cleared = datetime.datetime.utcnow()
         forumsread_list.append(forumsread)

+ 52 - 33
flaskbb/management/forms.py

@@ -11,8 +11,8 @@
 from flask.ext.wtf import Form
 from wtforms import (StringField, TextAreaField, PasswordField, IntegerField,
                      BooleanField, SelectField, DateField)
-from wtforms.validators import (DataRequired, Optional, Email, regexp, Length, URL,
-                                ValidationError)
+from wtforms.validators import (DataRequired, Optional, Email, regexp, Length,
+                                URL, ValidationError)
 
 from wtforms.ext.sqlalchemy.fields import (QuerySelectField,
                                            QuerySelectMultipleField)
@@ -36,7 +36,7 @@ def selectable_categories():
 
 
 def select_primary_group():
-    return Group.query.filter(Group.guest == False).order_by(Group.id)
+    return Group.query.filter(not Group.guest).order_by(Group.id)
 
 
 class UserForm(Form):
@@ -90,9 +90,10 @@ class UserForm(Form):
     def validate_username(self, field):
         if hasattr(self, "user"):
             user = User.query.filter(
-                db.and_(User.username.like(field.data),
-                        db.not_(User.id == self.user.id)
-                        )
+                db.and_(
+                    User.username.like(field.data),
+                    db.not_(User.id == self.user.id)
+                )
             ).first()
         else:
             user = User.query.filter(User.username.like(field.data)).first()
@@ -103,9 +104,10 @@ class UserForm(Form):
     def validate_email(self, field):
         if hasattr(self, "user"):
             user = User.query.filter(
-                db.and_(User.email.like(field.data),
-                        db.not_(User.id == self.user.id)
-                        )
+                db.and_(
+                    User.email.like(field.data),
+                    db.not_(User.id == self.user.id)
+                )
             ).first()
         else:
             user = User.query.filter(User.email.like(field.data)).first()
@@ -193,9 +195,10 @@ class GroupForm(Form):
     def validate_name(self, field):
         if hasattr(self, "group"):
             group = Group.query.filter(
-                db.and_(Group.name.like(field.data),
-                        db.not_(Group.id == self.group.id)
-                        )
+                db.and_(
+                    Group.name.like(field.data),
+                    db.not_(Group.id == self.group.id)
+                )
             ).first()
         else:
             group = Group.query.filter(Group.name.like(field.data)).first()
@@ -206,9 +209,10 @@ class GroupForm(Form):
     def validate_banned(self, field):
         if hasattr(self, "group"):
             group = Group.query.filter(
-                db.and_(Group.banned == True,
-                        db.not_(Group.id == self.group.id)
-                        )
+                db.and_(
+                    Group.banned,
+                    db.not_(Group.id == self.group.id)
+                )
             ).count()
         else:
             group = Group.query.filter_by(banned=True).count()
@@ -219,9 +223,10 @@ class GroupForm(Form):
     def validate_guest(self, field):
         if hasattr(self, "group"):
             group = Group.query.filter(
-                db.and_(Group.guest == True,
-                        db.not_(Group.id == self.group.id)
-                        )
+                db.and_(
+                    Group.guest,
+                    db.not_(Group.id == self.group.id)
+                )
             ).count()
         else:
             group = Group.query.filter_by(guest=True).count()
@@ -246,15 +251,22 @@ class AddGroupForm(GroupForm):
 
 
 class ForumForm(Form):
-    title = StringField("Forum Title", validators=[
-        DataRequired(message="Forum title required")])
+    title = StringField(
+        "Forum Title",
+        validators=[DataRequired(message="Forum title required")]
+    )
 
-    description = TextAreaField("Description", validators=[
-        Optional()],
-        description="You can format your description with BBCode.")
+    description = TextAreaField(
+        "Description",
+        validators=[Optional()],
+        description="You can format your description with BBCode."
+    )
 
-    position = IntegerField("Position", default=1, validators=[
-        DataRequired(message="Forum position required")])
+    position = IntegerField(
+        "Position",
+        default=1,
+        validators=[DataRequired(message="Forum position required")]
+    )
 
     category = QuerySelectField(
         "Category",
@@ -264,9 +276,11 @@ class ForumForm(Form):
         description="The category that contains this forum."
     )
 
-    external = StringField("External link", validators=[
-        Optional(), URL()],
-        description="A link to a website i.e. 'http://flaskbb.org'")
+    external = StringField(
+        "External link",
+        validators=[Optional(), URL()],
+        description="A link to a website i.e. 'http://flaskbb.org'"
+    )
 
     moderators = StringField(
         "Moderators",
@@ -354,12 +368,17 @@ class CategoryForm(Form):
     title = StringField("Category title", validators=[
         DataRequired(message="Category title required")])
 
-    description = TextAreaField("Description", validators=[
-        Optional()],
-        description="You can format your description with BBCode.")
+    description = TextAreaField(
+        "Description",
+        validators=[Optional()],
+        description="You can format your description with BBCode."
+    )
 
-    position = IntegerField("Position", default=1, validators=[
-        DataRequired(message="Category position required")])
+    position = IntegerField(
+        "Position",
+        default=1,
+        validators=[DataRequired(message="Category position required")]
+    )
 
     def save(self):
         category = Category(**self.data)

+ 15 - 24
flaskbb/management/models.py

@@ -75,32 +75,23 @@ class Setting(db.Model):
         for setting in group.settings:
             field_validators = []
 
+            if setting.value_type in ("integer", "float"):
+                validator_class = validators.NumberRange
+            elif setting.value_type == "string":
+                validator_class = validators.Length
+
             # generate the validators
             if "min" in setting.extra:
                 # Min number validator
-                if setting.value_type in ("integer", "float"):
-                    field_validators.append(
-                        validators.NumberRange(min=setting.extra["min"])
-                    )
-
-                # Min text length validator
-                elif setting.value_type in ("string"):
-                    field_validators.append(
-                        validators.Length(min=setting.extra["min"])
-                    )
+                field_validators.append(
+                    validator_class(min=setting.extra["min"])
+                )
 
             if "max" in setting.extra:
                 # Max number validator
-                if setting.value_type in ("integer", "float"):
-                    field_validators.append(
-                        validators.NumberRange(max=setting.extra["max"])
-                    )
-
-                # Max text length validator
-                elif setting.value_type in ("string"):
-                    field_validators.append(
-                        validators.Length(max=setting.extra["max"])
-                    )
+                field_validators.append(
+                    validator_class(max=setting.extra["max"])
+                )
 
             # Generate the fields based on value_type
             # IntegerField
@@ -119,7 +110,7 @@ class Setting(db.Model):
                 )
 
             # TextField
-            if setting.value_type == "string":
+            elif setting.value_type == "string":
                 setattr(
                     SettingsForm, setting.key,
                     TextField(setting.name, validators=field_validators,
@@ -127,7 +118,7 @@ class Setting(db.Model):
                 )
 
             # SelectMultipleField
-            if setting.value_type == "selectmultiple":
+            elif setting.value_type == "selectmultiple":
                 # if no coerce is found, it will fallback to unicode
                 if "coerce" in setting.extra:
                     coerce_to = setting.extra['coerce']
@@ -145,7 +136,7 @@ class Setting(db.Model):
                 )
 
             # SelectField
-            if setting.value_type == "select":
+            elif setting.value_type == "select":
                 # if no coerce is found, it will fallback to unicode
                 if "coerce" in setting.extra:
                     coerce_to = setting.extra['coerce']
@@ -162,7 +153,7 @@ class Setting(db.Model):
                 )
 
             # BooleanField
-            if setting.value_type == "boolean":
+            elif setting.value_type == "boolean":
                 setattr(
                     SettingsForm, setting.key,
                     BooleanField(setting.name, description=setting.description)

+ 7 - 6
flaskbb/management/views.py

@@ -125,7 +125,7 @@ def edit_user(user_id):
 
     secondary_group_query = Group.query.filter(
         db.not_(Group.id == user.primary_group_id),
-        db.not_(Group.banned == True),
+        db.not_(Group.banned),
         db.not_(Group.guest == True))
 
     form = EditUserForm(user)
@@ -203,10 +203,10 @@ def ban_user(user_id):
     # Do not allow moderators to ban admins
     if user.get_permissions()['admin'] and \
             (current_user.permissions['mod'] or
-                current_user.permissions['super_mod']):
+             current_user.permissions['super_mod']):
 
-            flash("A moderator cannot ban an admin user.", "danger")
-            return redirect(url_for("management.overview"))
+        flash("A moderator cannot ban an admin user.", "danger")
+        return redirect(url_for("management.overview"))
 
     if user.ban():
         flash("User was banned successfully.", "success")
@@ -368,8 +368,9 @@ def edit_forum(forum_id):
         return redirect(url_for("management.edit_forum", forum_id=forum.id))
     else:
         if forum.moderators:
-            form.moderators.data = ",".join([user.username
-                                            for user in forum.moderators])
+            form.moderators.data = ",".join([
+                user.username for user in forum.moderators
+            ])
         else:
             form.moderators.data = None