API

这部分文档涵盖了Flask-PluginKit几乎所有的公开接口

PluginManager Object

class flask_pluginkit.PluginManager(app=None, plugins_base=None, plugins_folder='plugins', **options)[源代码]

Flask Plugin Manager Extension, collects all plugins and maps the metadata to the plugin.

The plugin is a directory or a locally importable module, and the plugin entry file is __init__.py, including __plugin_name__, __version__, __author__ and other metadata.

A meaningful plugin structure should look like this:

plugins/
├── plugin1
│   ├── __init__.py
│   ├── LICENCE
│   ├── README
│   ├── static
│   │   └── plugin1.css
│   └── templates
│       └── plugin1
│           └── plugin1.html
└── plugin2
    ├── __init__.py
    ├── LICENCE
    ├── README
    ├── static
    │   └── plugin2.css
    └── templates
        └── plugin2
            └── plugin2.html

Initializes the PluginManager. It is also possible to initialize the PluginManager via a factory:

from flask_pluginkit import Flask, PluginManager
app = Flask(__name__)
pm = PluginManager()
pm.init_app(app)
参数:
  • app – flask application.

  • plugins_base – plugin folder where the plugins resides.

  • plugins_folder – base folder for the application. It is used to build the plugins package name.

  • logger – logging instance, for debug.

  • stpl – turn on template sorting when the value is True, ASC, DESC. Sorting rules can be used, DESC or ASC(default).

  • plugin_packages – list of third-party plugin packages.

  • static_url_path – can be used to specify a different path for the static files on the plugins. Defaults to the name of the static_endpoint folder.

  • static_endpoint – the endpoint name of plugins static files that should be served at static_url_path. Defaults to the 'assets'

  • pluginkit_config – additional configuration can be used in the template via emit_config().

在 3.1.0 版本发生变更: Add a vep handler

在 3.2.0 版本发生变更: Add filter handler, error handler, template context processor

在 3.3.1 版本发生变更: Add try_compatible, if True, it will try to load old version

在 3.4.0 版本发生变更: Add hep named before_first_request.

在 3.4.0 版本发生变更: The param stpl allows to be set to asc or desc, respectively, ascending, descending, which will also open the template sorting. So, the param stpl_reverse will be deprecated.

在 3.5.0 版本发生变更: Add cvep feature for beta.

自 3.7.0 版本弃用: Ready to remove stpl_reverse and try_compatible in the next minor version, if it is still used, a warning will be issued.

在 3.7.0 版本发生变更: Add p3 feature for beta.

自 3.7.2 版本弃用: Remove before_first_request hep

__init__(app=None, plugins_base=None, plugins_folder='plugins', **options)[源代码]

Receive initialization parameters and pass options to init_app() method.

init_app(app, plugins_base=None, plugins_folder='plugins')[源代码]
_tep_handler(plugin_info, tep_rule)[源代码]

Template extension point handler.

参数:
  • plugin_info – if tep is valid, will update it.

  • tep_rule

    look like {tep_name: your_html_file_or_code}

    1. This must be dict, where key means that tep is the extension point identifier, and each extension point can contain only one template type, either HTML or string, which requires string, and other types trigger exceptions.

    2. HTML template type suffix for html or htm as template file (the other as pure HTML code), to be real, will adopt a render_template way rendering, using template type can be specified when rendering and introduced to additional data.

抛出:
_hep_handler(plugin_info, hep_rule)[源代码]

Hook extension point handler.

参数:

hep_rule

look like {hook: func}, the supporting hooks:

1. before_request, Before request (intercept requests are allowed)

2. after_request, After request (no exception before return)

3. teardown_request, After request (before return, with or without exception)

抛出:

PEPError – if hep rule or content is invalid.

_bep_handler(plugin_info, bep_rule)[源代码]

Blueprint extension point handler.

参数:

bep_rule – look like {blueprint=, prefix=, parent=}

抛出:

PEPError – if bep rule or content is invalid.

_vep_handler(plugin_info, vep_rule)[源代码]

Viewfunc extension point handler.

参数:

vep_rule – look like [{rule=, view_func=, _blurprint=, opts}, ]

抛出:

PEPError – if vep rule or content is invalid.

在 3.1.0 版本加入.

在 3.6.0 版本发生变更: Allow adding vep on blueprint

_cvep_handler(plugin_info, cvep_rule)[源代码]

Class-based views extension point handler.

参数:

cvep_rule – look like [{view_class=, other options}, etc.]

抛出:

PEPError – if cvep rule or content is invalid.

在 3.5.0 版本加入.

_filter_handler(plugin_info, filter_rule)[源代码]

Template filter handler.

参数:

filter_rule – e.g. {filter_name=func,} or [func, (name,func)]

抛出:

PEPError – if filter rule or content is invalid.

在 3.2.0 版本加入.

在 3.4.0 版本发生变更: If filter_rule is list or tuple, allow nested tuple to set name

_error_handler(plugin_info, errhandler_rule)[源代码]

Error code handler.

参数:

errhandler_rule – eg: {err_code=func} or [{error=exception_class, handler=func}, {error=err_code, handler=func}]

抛出:

PEPError – if error handler rule or content is invalid.

在 3.2.0 版本加入.

在 3.4.0 版本发生变更: Allow registration of class-based exception handlers

_context_processor_handler(plugin_info, processor_rule)[源代码]

Template context processor(tcp) handler.

参数:

processor_rule – look like {var_name=var, func_name=func,}

抛出:

PEPError – if tcp rule or content is invalid.

在 3.2.0 版本加入.

_p3_handler(plugin_info, p3_rule)[源代码]

Plugin preprocessor handler.

参数:

p3_rule – look like {plugin_name:{pet:func}}

抛出:

PEPError – if the rule or content is invalid.

在 3.7.0 版本加入.

_dcp_manager

the instance of DcpManager

在 3.2.0 版本加入.

disable_plugin(plugin_name)[源代码]

Disable a plugin (that is, create a DISABLED empty file) and restart the application to take effect.

emit_assets(plugin_name, filename, _raw=False, _external=False)[源代码]

Get the static file in template context. This global function, which can be used directly in the template, is used to quickly reference the static resources of the plugin.

In addition, static resources can still pass through the blueprint, but emit_assets can be used if there is no blueprint.

Of course, you can also use flask.url_for() instead.

If filename ends with .css, then this function will return the link code, like this:

<link rel="stylesheet" href="/assets/plugin/css/demo.css">

If filename ends with .js, then this function will return the script code, like this:

<script src="/assets/plugin/js/demo.js"></script>

Other types of files, only return file url path segment, like this:

/assets/plugin/img/logo.png
/assets/plugin/attachment/test.zip

However, the _raw parameter has been added in v3.4.0, and if it is True, only path is generated.

The following is a mini example:

<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
    {{ emit_assets('demo','css/demo.css') }}
</head>
<body>
    <div class="logo">
        <img src="{{ emit_assets('demo', 'img/logo.png') }}">
    </div>
    <div class="showJsPath">
        <scan>
            {{ emit_assets('demo', 'js/demo.js', _raw=True) }}
        </scan>
    </div>
</body>
</html>
参数:
  • plugin_name – name of the plugin, which is __plugin_name__

  • filename – filename in the static directory of the plugin package

  • _raw – if True, not to parse automatically, only generate uri. Default False.

  • _external – _external parameter passed to url_for

返回:

html code with Markup.

在 3.4.0 版本发生变更: Add _raw, only generate uri without parse

在 3.6.0 版本发生变更: Add _external, pass to flask.url_for()

emit_config(conf_name)[源代码]

Get configuration information in the template context.

emit_tep(tep, typ='all', **context)[源代码]

Emit a tep and get the tep data(html code) with flask.render_template() or flask.render_template_string()

Please use this function in the template file or code. The emit_tep needs to be defined by yourself. It can render HTML code and files for a tep, or even pass in extra data at render time.

Suppose you have a tep named hello, only need to enable custom extension points in the template context, eg:

{{ emit_tep("hello", context="world") }}
参数:
  • tep – Template extension point name, it is the only one. A tep parsing result is list, within which can be HTML code and files, or one of them.

  • typ

    Render type, default is all.

    all - render HTML file and code;

    fil - render HTML file only;

    cod - render HTML code only.

  • context – Keyword params, additional data passed to the template

返回:

html code with Markup.

enable_plugin(plugin_name)[源代码]

Enable a plugin (that is, create a ENABLED empty file) and restart the application to take effect.

property get_all_plugins

Get all plugins, enabled and disabled

property get_enabled_beps

Get all bep of the enabled plugins.

返回:

List of nested dictionaries, like [{blueprint=,prefix=},]

property get_enabled_cveps

Get all cvep for the enabled plugins.

返回:

List of nested tuples, like [(view_class, other options),]

在 3.5.0 版本加入.

property get_enabled_errhandlers

Get all error handlers for the enabled plugins.

返回:

list, like [(err_code_class, func_handler), …]

在 3.2.0 版本加入.

在 3.4.0 版本发生变更: Return type changed from dict to list

property get_enabled_filters

Get all template filters for the enabled plugins.

返回:

List of nested tuples, like [(filter_name, filter_func),]

在 3.2.0 版本加入.

property get_enabled_heps

Get all hep of the enabled plugins.

返回:

dictionary with nested tuples, look like {hook:[]}

property get_enabled_plugins

Get all enabled plugins

property get_enabled_tcps

Get all template context processors for the enabled plugins.

返回:

List of Nested Dictionaries, like [{name:var_or_func},]

在 3.2.0 版本加入.

property get_enabled_teps

Get all tep of the enabled plugins.

返回:

dict, look like {tep_1: dict(fil=[], cod=[]), tep_n…}

property get_enabled_veps

Get all vep for the enabled plugins.

返回:

List of nested tuples, like [(path, view_func),]

在 3.1.0 版本加入.

get_plugin_info(plugin_name)[源代码]

Get plugin information from all plugins

logger

logging Logger instance

plugin_packages

Third-party plugin package

pluginkit_config

Configuration Dictionary of Flask-PLuginKit in Project

static_endpoint

Static endpoint

static_url_path

Static url prefix

stpl

Template sorting

flask_pluginkit.push_dcp(event, callback, position='right')[源代码]

Push a callable for with push().

Example usage:

push_dcp('demo', lambda:'Hello dcp')

在 3.2.0 版本加入.

flask_pluginkit.blueprint

The Blueprint instance for managing plugins.

在 3.3.0 版本加入.

Inherited Application Objects

class flask_pluginkit.Flask(import_name: str, static_url_path: Optional[str] = None, static_folder: Optional[Union[str, PathLike]] = 'static', static_host: Optional[str] = None, host_matching: bool = False, subdomain_matching: bool = False, template_folder: Optional[Union[str, PathLike]] = 'templates', instance_path: Optional[str] = None, instance_relative_config: bool = False, root_path: Optional[str] = None)[源代码]
before_request_second(f)[源代码]

Registers a function to run before each request. Priority Second.

before_request_top(f)[源代码]

Registers a function to run before each request. Priority First.

The usage is equivalent to the flask.Flask.before_request() decorator, and before_request registers the function at the end of the before_request_funcs, while this decorator registers the function at the top of the before_request_funcs (index 0).

Because flask-pluginkit has registered all cep into the app at load time, if your web application uses before_request and plugins depend on one of them (like g), the plugin will not run properly, so your web application should use this decorator at this time.

class flask_pluginkit.JsonResponse(response: Optional[Union[Iterable[bytes], bytes, Iterable[str], str]] = None, status: Optional[Union[int, str, HTTPStatus]] = None, headers: Optional[Union[Mapping[str, Union[str, int, Iterable[Union[str, int]]]], Iterable[Tuple[str, Union[str, int]]]]] = None, mimetype: Optional[str] = None, content_type: Optional[str] = None, direct_passthrough: bool = False)[源代码]

In response to a return type that cannot be processed. If it is a dict, return json.

在 3.4.0 版本加入.

classmethod force_type(rv, environ=None)[源代码]

Enforce that the WSGI response is a response object of the current type. Werkzeug will use the Response internally in many situations like the exceptions. If you call get_response() on an exception you will get back a regular Response object, even if you are using a custom subclass.

This method can enforce a given response type, and it will also convert arbitrary WSGI callables into response objects if an environ is provided:

# convert a Werkzeug response object into an instance of the
# MyResponseClass subclass.
response = MyResponseClass.force_type(response)

# convert any WSGI application into a response object
response = MyResponseClass.force_type(response, environ)

This is especially useful if you want to post-process responses in the main dispatcher and use functionality provided by your subclass.

Keep in mind that this will modify response objects in place if possible!

参数:
  • response – a response object or wsgi application.

  • environ – a WSGI environment object.

返回:

a response object.

response: Union[Iterable[str], Iterable[bytes]]

The response body to send as the WSGI iterable. A list of strings or bytes represents a fixed-length response, any other iterable is a streaming response. Strings are encoded to bytes as UTF-8.

Do not set to a plain string or bytes, that will cause sending the response to be very inefficient as it will iterate one byte at a time.

Storage Objects

class flask_pluginkit.LocalStorage(path=None)[源代码]

Local file system storage based on the shelve module.

index

The default index, as the only key, you can override it.

get(key, default=None)[源代码]

Get persistent data from shelve.

返回:

data

property list

list all data

返回:

dict

set(key, value)[源代码]

Set persistent data with shelve.

参数:
  • key – str: Index key

  • value – All supported data types in python

Raises:

返回:

setmany(**mapping)[源代码]

Set more data

参数:

mapping – the more k=v

在 3.4.1 版本加入.

class flask_pluginkit.RedisStorage(redis_url=None, redis_connection=None)[源代码]

Use redis stand-alone storage

index

The default index, as the only key, you can override it.

get(key, default=None)[源代码]

get key original data from redis

property list

list redis hash data

remove(key)[源代码]

delete key from redis

set(key, value)[源代码]

set key data

setmany(**mapping)[源代码]

Set more data

参数:

mapping – the more k=v

在 3.4.1 版本加入.

Useful Functions and Classes

flask_pluginkit.utils.isValidSemver(version)[源代码]

Semantic version number - determines whether the version is qualified. The format is MAJOR.Minor.PATCH, more with https://semver.org

flask_pluginkit.utils.sortedSemver(versions, sort='ASC')[源代码]

Semantically sort the list of version Numbers

class flask_pluginkit.utils.BaseStorage[源代码]

This is the base class for storage. The available storage classes need to inherit from BaseStorage and override the get and set methods, it’s best to implement the remote method as well.

This base class customizes the __getitem__, __setitem__ and __delitem__ methods so that the user can call it like a dict.

在 3.4.1 版本发生变更: Change index to DEFAULT_INDEX

DEFAULT_INDEX = 'flask_pluginkit_dat'

The default index, as the only key, you can override it.

property index

Get the final index

在 3.4.1 版本加入.

class flask_pluginkit.utils.DcpManager[源代码]
emit(event, *args, **kwargs)[源代码]

Emits events for the template context.

返回:

strings with Markup

push(event, callback, position='right')[源代码]

Connect a dcp, push a function.

参数:
  • event – a unique identifier name for dcp.

  • callback – corresponding to the event to perform a function.

  • position – the position of the insertion function, right(default) or left. The default right is inserted at the end of the event, and left is inserted into the event first.

抛出:

在 3.2.0 版本加入.

remove(event, callback)[源代码]

Remove a callback again.

class flask_pluginkit.PluginInstaller(plugin_abspath, **kwargs)[源代码]

plugin installer for installing a compressed local/remote plugin

addPlugin(method='remote', **kwargs)[源代码]

Add plugin, support only for .tar.gz or .zip compression packages.

参数:
  • method

    supported method:

    remote, download and unpack a remote plugin package;

    local, unzip a local plugin package.

    pip, install package with pip command.

  • url – for method is remote, plugin can be downloaded from the address.

  • filepath – for method is local, plugin local absolute path

  • remove – for method is local, remove the plugin source code package, default is False.

  • package_or_url – for method is pip, pypi’s package or VCS url.

返回:

the result of adding the plugin, like {msg:str, code:int}, code=0 is successful.

在 3.3.0 版本发生变更: Add pip method, with package_or_url param.

removePlugin(package)[源代码]

Remove a local plugin

参数:

package – The plugin package name, not __plugin_name.

Custom Exceptions

flask_pluginkit.exceptions

Exception Classes

exception flask_pluginkit.exceptions.InstallError[源代码]

基类:PluginError

exception flask_pluginkit.exceptions.NotCallableError[源代码]

基类:PluginError

exception flask_pluginkit.exceptions.PEPError[源代码]

基类:PluginError

exception flask_pluginkit.exceptions.PluginError[源代码]

基类:Exception

exception flask_pluginkit.exceptions.TarError[源代码]

基类:PluginError

exception flask_pluginkit.exceptions.TemplateNotFound[源代码]

基类:PluginError

exception flask_pluginkit.exceptions.VersionError[源代码]

基类:PluginError

exception flask_pluginkit.exceptions.ZipError[源代码]

基类:PluginError