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

Grammar and readability changes. Deleted example plugin

djsilcock 8 лет назад
Родитель
Сommit
85ab0201d9

+ 3 - 2
flaskbb/cli/plugins.py

@@ -133,7 +133,8 @@ def list_plugins():
 @plugins.command("migrations")
 @click.argument("plugin_identifier")
 def migrate_plugin(plugin_identifier):
-    """Installs a new plugin."""
+    """Generates migration files for a plugin.
+    Migration version files are stored in flaskbb/plugins/<plugin_dir>/migration_versions"""
     validate_plugin(plugin_identifier)
     plugin = get_plugin_from_all(plugin_identifier)
     click.secho("[+] Updating plugin migrations{}...".format(plugin.name), fg="cyan")
@@ -146,7 +147,7 @@ def migrate_plugin(plugin_identifier):
 @plugins.command("upgrade")
 @click.argument("plugin_identifier")
 def upgrade_plugin(plugin_identifier):
-    """Uninstalls a plugin from FlaskBB."""
+    """Upgrades database to the latest version of a plugin's models"""
     validate_plugin(plugin_identifier)
     plugin = get_plugin_from_all(plugin_identifier)
     click.secho("[+] Upgrading plugin {}...".format(plugin.name), fg="cyan")

+ 65 - 28
flaskbb/plugins/__init__.py

@@ -8,68 +8,104 @@
     :copyright: (c) 2014 by the FlaskBB Team.
     :license: BSD, see LICENSE for more details.
 """
+import contextlib
+
+import copy
+import os
 from flask import current_app
+from flask import g
+from flask_migrate import upgrade, downgrade, migrate
 from flask_plugins import Plugin
-from flask_migrate import upgrade,downgrade,migrate
-from flaskbb.extensions import db,migrate as mig
+from flaskbb.extensions import db, migrate as mig
 from flaskbb.management.models import SettingsGroup
-from flask import g
-import contextlib
-import os,copy
 
-@contextlib.contextmanager
+
+@contextlib.contextmanager  # TODO: Add tests
 def plugin_name_migrate(name):
-    g.plugin_name=name
+    """Migrations in this with block will only apply to models from the named plugin"""
+    g.plugin_name = name
     yield
     del g.plugin_name
 
-def db_for_plugin(plugin_name,db):
-    newdb=copy.copy(db)
-    def Table(*args,**kwargs):
-        newtable=db.Table(*args,**kwargs)
-        newtable._plugin=plugin_name
-        return newtable
-    newdb.Table=Table
-    return newdb
+
+def db_for_plugin(plugin_name,sqla_instance=None):
+    """Labels models as belonging to this plugin.
+    sqla_instance is a valid Flask-SQLAlchemy instance, if None, then the default db is used
+
+    Usage:
+        from flaskbb.plugins import db_for_plugin
+
+        db=db_for_plugin(__name__)
+
+        mytable = db.Table(...)
+
+        class MyModel(db.Model):
+            ...
+
+        """
+    sqla_instance=sqla_instance or db
+    new_db = copy.copy(sqla_instance)
+
+    def Table(*args, **kwargs):
+        new_table = sqla_instance.Table(*args, **kwargs)
+        new_table._plugin = plugin_name
+        return new_table
+
+    new_db.Table = Table
+    return new_db
+
 
 @mig.configure
 def config_migrate(config):
+    """Configuration callback for plugins environment"""
     plugins = current_app.extensions['plugin_manager'].all_plugins.values()
     migration_dirs = [p.get_migration_version_dir() for p in plugins]
-    if config.get_main_option('version_table')=='plugins':
+    if config.get_main_option('version_table') == 'plugins':
         config.set_main_option('version_locations', ' '.join(migration_dirs))
     return config
 
 
 class FlaskBBPlugin(Plugin):
-
     #: This is the :class:`SettingsGroup` key - if your the plugin needs to
     #: install additional things you must set it, else it won't install
     #: anything.
     settings_key = None
 
     def resource_filename(self, *names):
-        return os.path.join(self.path, *names)
+        "Returns an absolute filename for a plugin resource."
+        if len(names)==1 and '/' in names[0]:
+            names=names[0].split('/')
+        fname= os.path.join(self.path, *names)
+        if ' ' in fname and not '"' in fname and not "'" in fname:
+            fname='"%s"'%fname
+        return fname
 
     def get_migration_version_dir(self):
+        """Returns path to directory containing the migration version files"""
         return self.resource_filename('migration_versions')
 
     def upgrade_database(self, target='head'):
-        plugindir = current_app.extensions['plugin_manager'].plugin_folder
-        upgrade(directory=os.path.join(plugindir, 'migrations'), revision=self.settings_key + '@' + target)
+        """Updates database to a later version of plugin models.
+        Default behaviour is to upgrade to latest version"""
+        plugin_dir = current_app.extensions['plugin_manager'].plugin_folder
+        upgrade(directory=os.path.join(plugin_dir, '_migration_environment'), revision=self.settings_key + '@' + target)
 
     def downgrade_database(self, target='base'):
-        plugindir = current_app.extensions['plugin_manager'].plugin_folder
-        downgrade(directory=os.path.join(plugindir, 'migrations'), revision=self.settings_key + '@' + target)
+        """Rolls back database to a previous version of plugin models.
+        Default behaviour is to remove models completely"""
+        plugin_dir = current_app.extensions['plugin_manager'].plugin_folder
+        downgrade(directory=os.path.join(plugin_dir, '_migration_environment'), revision=self.settings_key + '@' + target)
 
     def migrate(self):
+        """Generates new migration files for a plugin and stores them in
+        flaskbb/plugins/<plugin_folder>/migration_versions"""
         with plugin_name_migrate(self.__module__):
-            plugindir = current_app.extensions['plugin_manager'].plugin_folder
+            plugin_dir = current_app.extensions['plugin_manager'].plugin_folder
             try:
-                migrate(directory=os.path.join(plugindir, 'migrations'),
+                migrate(directory=os.path.join(plugin_dir, '_migration_environment'),
                         head=self.settings_key)
-            except Exception as e:  #presumably this is the initial migration?
-                migrate(directory=os.path.join(plugindir, 'migrations'),
+            except Exception as e:  # presumably this is the initial migration?
+                migrate(directory=os.path.join(plugin_dir, '_migration_environment'),
                         version_path=self.resource_filename('migration_versions'),
                         branch_label=self.settings_key)
 
@@ -84,8 +120,8 @@ 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).\
+            group = SettingsGroup.query. \
+                filter_by(key=self.settings_key). \
                 first()
             if group and len(group.settings.all()) > 0:
                 return True
@@ -93,6 +129,7 @@ class FlaskBBPlugin(Plugin):
         return False
 
         # Some helpers
+
     def register_blueprint(self, blueprint, **kwargs):
         """Registers a blueprint.
 

+ 0 - 0
flaskbb/plugins/migrations/README → flaskbb/plugins/_migration_environment/README


+ 0 - 0
flaskbb/plugins/migrations/alembic.ini → flaskbb/plugins/_migration_environment/alembic.ini


+ 0 - 0
flaskbb/plugins/migrations/env.py → flaskbb/plugins/_migration_environment/env.py


+ 0 - 0
flaskbb/plugins/migrations/script.py.mako → flaskbb/plugins/_migration_environment/script.py.mako


+ 0 - 9
flaskbb/plugins/example_model_plugin/CHANGELOG.md

@@ -1,9 +0,0 @@
-Changelog
-=========
-
-Here you can see the full list of changes between each release.
-
-Version 0.1.0
--------------
-
-* Initial commit

+ 0 - 29
flaskbb/plugins/example_model_plugin/LICENSE

@@ -1,29 +0,0 @@
-BSD License
-
-Copyright (c) 2017, Your Name <Your email address (eq. you@example.com)>
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without modification,
-are permitted provided that the following conditions are met:
-
-* Redistributions of source code must retain the above copyright notice, this
-  list of conditions and the following disclaimer.
-
-* Redistributions in binary form must reproduce the above copyright notice, this
-  list of conditions and the following disclaimer in the documentation and/or
-  other materials provided with the distribution.
-
-* Neither the name of the copyright holder nor the names of its
-  contributors may be used to endorse or promote products derived from this
-  software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
-INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
-BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
-OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
-OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-OF THE POSSIBILITY OF SUCH DAMAGE.

+ 0 - 65
flaskbb/plugins/example_model_plugin/__init__.py

@@ -1,65 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-    flaskbb.plugins.plugin_name
-    ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-    A Portal Plugin for FlaskBB.
-
-    :copyright: (c) 2014 by the FlaskBB Team.
-    :license: BSD, see LICENSE for more details.
-"""
-from flask_plugins import connect_event
-
-from flaskbb.plugins import FlaskBBPlugin,db_for_plugin
-from flaskbb.utils.populate import (create_settings_from_fixture,
-                                    delete_settings_from_fixture)
-from flaskbb.extensions import db
-from flaskbb.forum.models import Forum
-
-from .views import plugin_bp, inject_navigation_link
-
-__version__ = "0.1"
-__plugin__ = "HelloWorldPlugin"
-
-
-fixture = (
-    ('plugin_plugin_name', {
-        'name': "Plugin Name Settings",
-        "description": "Configure the Plugin Name Plugin",
-        "settings": (
-            ('plugin_name_display_in_navigation', {
-                'value':       True,
-                'value_type':  "boolean",
-                'name':        "Show Link in Navigation",
-                'description': "If enabled, it will show the link in the navigation"
-            }),
-        ),
-    }),
-)
-
-db=db_for_plugin(__name__,db)
-
-class MyModel(db.Model):
-    __tablename__='my_model'
-    field1=db.Column(db.String,primary_key=True)
-
-moderators = db.Table(
-    'test_table',
-    db.Column('user_id', db.Integer(), db.ForeignKey('users.id'),
-              nullable=False),
-    db.Column('forum_id', db.Integer(),
-              db.ForeignKey('forums.id', use_alter=True, name="fk_forum_id"),
-              nullable=False))
-
-class HelloWorldPlugin(FlaskBBPlugin):
-    settings_key = 'plugin_plugin_name'
-
-    def setup(self):
-        self.register_blueprint(plugin_bp, url_prefix="/plugin-name")
-        connect_event("before-first-navigation-element", inject_navigation_link)
-
-    def install(self):
-        create_settings_from_fixture(fixture)
-
-    def uninstall(self):
-        delete_settings_from_fixture(fixture)

+ 0 - 9
flaskbb/plugins/example_model_plugin/info.json

@@ -1,9 +0,0 @@
-{
-    "identifier": "test_model_plugin",
-    "name": "Plugin Name",
-    "author": "Your Name",
-    "website": "http://flaskbb.org",
-    "license": "BSD License",
-    "description": "A description of the plugin",
-    "version": "0.1.0"
-}

+ 0 - 7
flaskbb/plugins/example_model_plugin/templates/navigation_link.html

@@ -1,7 +0,0 @@
-{% if flaskbb_config["PLUGIN_NAME_DISPLAY_IN_NAVIGATION"] %}
-<li {% if 'plugin_name.index' == request.endpoint %}class="active"{% endif %}>
-    <a href="{{ url_for('plugin_name.index') }}">
-        <i class="fa fa-home"></i> Plugin Name
-    </a>
-</li>
-{% endif %}

+ 0 - 25
flaskbb/plugins/example_model_plugin/templates/plugin_name.html

@@ -1,25 +0,0 @@
-{% extends theme("layout.html") %}
-
-{% block css %}
-{{  super() }}
-<!-- put some plugin css style here -->
-{% endblock %}
-
-{% block content %}
-<div class="row">
-    <div class="col-md-12 col-sm-12 col-xs-12">
-        <div class="panel panel-default panel-widget">
-            <div class="panel-heading panel-widget-heading">
-                <h3 class="panel-title">Plugin Information</h3>
-            </div>
-            <div class="panel-body panel-widget-body">
-                <p>Plugin Name: {{ plugin_obj.name }}, {{ plugin_obj.version }}</p>
-                <p>Plugin Description: {{ plugin_obj.description }}</p>
-                <p>Plugin Website: {{ plugin_obj.website }}</p>
-                <p>Plugin License: {{ plugin_obj.license }}</p>
-                <p>Plugin Author: {{ plugin_obj.author }}</p>
-            </div>
-        </div>
-    </div>
-</div>
-{% endblock %}

+ 0 - 27
flaskbb/plugins/example_model_plugin/views.py

@@ -1,27 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-    flaskbb.plugins.plugin_name.views
-    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-    This module contains the plugin_name view.
-
-    :copyright: (c) 2016 by Your Name.
-    :license: BSD License, see LICENSE for more details.
-"""
-from flask import Blueprint
-from flask_plugins import get_plugin_from_all
-
-from flaskbb.utils.helpers import render_template
-
-# You can modify this to your liking
-plugin_bp = Blueprint("plugin_name", __name__, template_folder="templates")
-
-
-def inject_navigation_link():
-    return render_template("navigation_link.html")
-
-
-@plugin_bp.route("/")
-def index():
-    plugin_obj = get_plugin_from_all("plugin_name")
-    return render_template("plugin_name.html", plugin_obj=plugin_obj)

BIN
flaskbb/plugins/migrations/env.pyc