mbpy_plugin_example

Description of plugin architecture

Usage

When the directory structure is complete, go to the mbpy folder, and import it with the following command. Remember you should be in your virtual environment:

pip install --editable /path/to/mbpy_plugin_example

Check it was successful by inputting the command mbpy plugins --help and seeing the name displayed. It can then be executed by typing mbpy plugins name_of_plugin.

Directory Structure

The bare-bones essentials for getting started building a plugin for mbpy, with explanations.

Place the following files into the same directory:

setup.py:

from setuptools import setup

setup(
    name='example',
    version='0.1',
    py_modules=['example'],
    install_requires=[
        'click',
    ],
    entry_points='''
        [mbpy_plugins]
        example=example.cli:cli
    ''',
)

The name property can be anything, rename it to whatever makes sense. The py_modules value needs to match the name of the module, which in this example is "example". The entry_points parameter is where the magic happens. It simply maps out that we will be injecting which module, into where. In this case, it's indicating to inject as an mbpy_plugin, so that it'll be available as a subcommand when the user uses mbpy_plugins --help to discover how to use it. The path is specified as example=example.cli:cli which means "The example module, which has a file called cli, which has a function defined as cli, and that is the code that will be injected.

example/cli.py:

import click

@click.command('example')
def cli():
    """
    Example Plugin!
    """
    pass

This is the subcommand that will be added to mbpy plugins command. You can specify parameters using the click api interface. There are many example of how to do this in the codebase.

example/__init__.py

This is actually a blank file, but required to exist (as this is how a module is created in Python.)

Common Idioms

The above code is truly bare-bones; there is very little that can be actually accomplished without additional imports and boilerplate.

To continue building, please use the following example idioms:

Execute a DB query:

import click
from mbpy.db.schema import Student  # to query Student table

@click.command('your-name')
@click.option('-g', '--grade', 'grade_variable', type=int)
@click.pass_context
def cli(ctx, grade_variable):
    """ Show students in the passed grade """
    with ctx.obj.Session() as session:
        students = session.query(Student) \
                     .where(Student.class_grade_number == grade_number) \
                     .all()
        print(students)

With the code installed the user can execute mbpy plugins your-name --grade 10.

Last updated