Plugin Module
Every plugin is a class that extends FastPluggyBaseModule (a Pydantic BaseModel).
Minimal example
from typing import Any
from fastpluggy.core.module_base import FastPluggyBaseModule
def get_router():
# Deferred import also avoids circular-import problems at load time.
from .router import my_router
return my_router
class MyPlugin(FastPluggyBaseModule):
module_name: str = "my_plugin"
module_version: str = "1.0.0"
module_router: Any = get_router # the FUNCTION — never get_router()
module_router must be a module-level function
FastPluggyBaseModule is a Pydantic BaseModel, and Pydantic deep-copies mutable field
defaults on every instantiation. A live APIRouter as the default drags the whole route graph
through copy.deepcopy during plugin discovery, so the moment anything reachable from a route
holds a _thread.lock the plugin dies with TypeError: cannot pickle '_thread.lock' object
before it ever mounts. (FastAPI ≥ 0.139.2 puts a lock in every nested include_router().)
Core resolves the default lazily only when it is a types.FunctionType
(base_module_manager.py, plugin_state.py). So these three all break:
| Form | Why it fails |
|---|---|
module_router = get_router() |
stores the live router — deep-copied |
module_router = my_router |
same, one step more direct |
def module_router(self): ... |
a bound method is MethodType, not FunctionType — core skips the lazy branch and treats it as a router object |
Field reference
|| Field | Type | Default | Description |
|---|---|---|---|
| module_name | str | "" | Unique identifier. Used in URLs, admin, and depends_on. |
| module_version | str | "0.0.0" | Semantic version string. |
| module_menu_name | str | "" | Label shown in the sidebar. Defaults to module_name. |
| module_menu_icon | str | "ti ti-box" | Icon CSS classes, e.g. "ti ti-star". |
| module_menu_type | str \| None | "main" | "main" (the sidebar), "admin" (Plugin tools on the admin home), or None to hide. |
| module_router | Callable[[], APIRouter \| list] | None | A zero-arg factory function returning the router (or a list of them). Assigning a live APIRouter — or calling the factory — crashes plugin discovery; see the warning above. |
| module_mount_url | str \| None | None | Override mount URL. Default: /{module_type}/{module_name}. |
| module_settings | type \| None | None | Pydantic BaseSettings class (not instance). |
| depends_on | Dict[str, str] | {} | Hard plugin dependencies: {"other": ">=1.0.0"}. A missing, disabled or version-mismatched dependency, or a dependency cycle, blocks the loading of that plugin only; the plugin page shows the reason. |
| optional_depends_on | Dict[str, str] | {} | Optional plugin dependencies: {"other": ">=1.0.0"}. When present, the other plugin loads first. When missing, the plugin still loads normally. |
| integrates_with | Dict[str, str] | {} | Companion plugins, used when they are loaded: {"other": ">=1.0.0"}. Same version check and warning as optional_depends_on, and no load order. |
| companion_reasons | Dict[str, str] | {} | What the plugin loses without an optional_depends_on / integrates_with plugin: {"other": "its history is never purged"}. Given by the advisory that reports the missing plugin and by the startup log line. |
| extra_js_files | List[str] | [] | JS file paths injected into every page <head>, e.g. "/app_static/my_plugin/js/app.js". Each /app_static/ path gets its plugin's cache token; see Static files. |
| extra_css_files | List[str] | [] | CSS file paths injected into every page <head>, same rule as extra_js_files. |
| sw_handler_files | List[str] | [] | Service worker handler scripts (paths relative to plugin's static dir). See Service Worker Handlers. |
Dependencies
Hard dependencies (depends_on)
Hard dependencies must be present and version-compatible for the plugin to load. If a dependency is missing or its version doesn't match the constraint, the plugin is marked as unloadable.
class MyPlugin(FastPluggyBaseModule):
module_name: str = "my_plugin"
depends_on: dict = {"auth_user": ">=1.0.0"} # auth_user must be loaded
Optional dependencies (optional_depends_on)
An optional dependency is loaded before your plugin when it is there, and never blocks loading. Use it when your plugin needs the other one set up first: its tables created, its hooks registered.
class MyPlugin(FastPluggyBaseModule):
module_name: str = "my_plugin"
optional_depends_on: dict = {"notifications": ">=1.0.0"}
Behavior: - Present + version matches → plugin loads after the dependency (load order guaranteed) - Present + version mismatch → warning logged and an advisory, no load-order edge, plugin still loads - Missing → info logged and an advisory (one per missing plugin, naming every plugin that declares it), plugin loads normally
Companion plugins (integrates_with)
A companion is a plugin yours uses when it is there, without needing it loaded first. It gets the same version check, the same status and the same warning as an optional dependency, and no load order.
class MyPlugin(FastPluggyBaseModule):
module_name: str = "my_plugin"
integrates_with: dict = {"db_purge": ">=0.1.8"}
Which one to declare:
| Your plugin... | Declare |
|---|---|
| cannot work without the other one | depends_on |
| needs the other one loaded first, when it is there | optional_depends_on |
| only calls the other one when it is there, in either order | integrates_with |
Two plugins can name each other in integrates_with. In optional_depends_on they cannot: each asks to load after the other.
Saying what a missing plugin costs (companion_reasons)
When an optional dependency or a companion is missing, the core reports it in one advisory that names every plugin declaring it. Say in companion_reasons what your plugin loses without it, and the advisory gives that reason, like the line logged at startup (INFO):
class MyPlugin(FastPluggyBaseModule):
module_name: str = "my_plugin"
integrates_with: dict = {"db_purge": ">=0.1.8"}
companion_reasons: dict = {"db_purge": "its history is never purged"}
db_purge is not loaded. Used by my_plugin (its history is never purged).
Report it there rather than in a log line or an advisory of your own: the operator then reads one line per missing plugin. A key that is in neither optional_depends_on nor integrates_with is shown as a warning on the plugin page.
When optional dependencies form a cycle
If plugin A lists B in optional_depends_on and B lists A, neither order satisfies both. Both plugins still load. The optional dependencies on that cycle lose their load order, and only those: the other plugins of the app keep theirs. Each plugin on the cycle shows the dependency as "Not ordered" on its page, and an advisory gives the cycle and this advice: move the side that does not need the order to integrates_with.
A cycle of hard dependencies (depends_on) is an error: those plugins do not load.
Importing a plugin that may be missing
For an optional dependency or a companion, guard the import in your plugin code:
try:
from fastpluggy_plugin.notifications.service import send_notification
except ImportError:
send_notification = None
Declare it as well: a bare try/except ImportError with no declaration fails silently, and nobody is told the feature is off.
What the admin shows
Each plugin's page lists its dependencies, optional dependencies and companion plugins with their status (available, version mismatch, not loaded), and the warnings above.
Fields that are not read
A plugin class accepts extra fields, so a wrong name does nothing and raises nothing. Two cases are reported, as a warning on the plugin's page and a "Warning" status, with the message, in the plugin list; the plugin still loads:
optional_dependencies: a name several plugins used and that FastPluggy never read. Useoptional_depends_onorintegrates_with.- a field whose name is one typo away from a core field (
optional_depend_on,extra_js_file): the warning names the field it resembles.
Plugin discovery
Plugins are loaded from two sources:
Folder scan
Place a directory with a plugin.py (containing a FastPluggyBaseModule subclass) under the
configured plugins/ path:
plugins/
my_plugin/
__init__.py ← optional; may stay empty
plugin.py ← MyPlugin(FastPluggyBaseModule) is looked up here
router/
templates/
static/
The core imports the package, then its plugin.py, and takes the FastPluggyBaseModule subclass
found there. __init__.py does not need to import the class, and the core writes nothing in the
directory. A cloned plugin repository works as is: when the directory has no plugin.py but a
pyproject.toml, the code is read from its [tool.setuptools] package-dir and imported under the
package name of its fastpluggy.plugins entry point (fastpluggy_plugin.<name>).
A folder plugin's code is imported once per process: after changing it, restart the application.
Entry points
Declare in pyproject.toml:
The framework walks up the directory tree from plugin.py to locate pyproject.toml /
requirements.txt for dependency display.
Control which entry-point plugins are loaded with the FP_PLUGINS env var
(comma-separated names, or "*" for all).
Static files (/app_static)
A module's static/ folder (next to its plugin.py) is served at
/app_static/<module_name>/<path>: my_plugin/static/js/app.js is
/app_static/my_plugin/js/app.js.
Only files inside that folder are served: a path that leads out of it (.., an absolute path)
gets a 404, like a missing file. Symlinks are followed and the file they point to must also be
inside static/; a static/ folder that is itself a symlink (to a build output, say) is
served from its target. The route needs no sign-in, so put nothing private in static/.
Caching
A browser keeps a file a year without asking again (Cache-Control: public,
max-age=31536000, immutable) only when its URL carries ?v=<token> and the token is the
file's current one. Any other request (no v, an old or wrong v) is answered no-cache:
the browser keeps the file but asks the server before each use, and gets an empty 304 while
the file has not changed (ETag / Last-Modified). A wrong token therefore never pins a file.
The token is:
| How the module is installed | Token | Why |
|---|---|---|
| Package from a package index (entry point) | the plugin's version, e.g. 1.4.2 |
a version published on an index never changes content |
Anything else: plugin folder, application domain, editable install (pip install -e), local directory, VCS, wheel file |
a 12-character fingerprint of the file's mtime and size | these files change without a version bump; each save of the file changes its URL |
The server checks the installed version when the request arrives: a package upgraded on disk
but not reloaded yet is not served immutable for its old version.
Building the URL
extra_js_files/extra_css_files: nothing to do.base.html.j2adds the token of the module named in each/app_static/<module>/...path. Other absolute paths keep the core's version (?v=<core version>), as before.- In a template, use the Jinja global
app_static_url(module_name, path):
<link rel="stylesheet" href="{{ app_static_url('my_plugin', 'css/page.css') }}">
<script type="module" src="{{ app_static_url('my_plugin', 'js/pages/page.js') }}"></script>
It returns /app_static/my_plugin/js/pages/page.js?v=<token>, or the URL without v (no
long cache) when the module or the file does not exist.
- In Python: fastpluggy.core.routers.app_static.app_static_url(fast_pluggy, module_name, path).
A hand-written ?v= that is not the token (the core version, a date) is served no-cache, as
before. A plugin that already writes ?v=<its distribution version> gets the long cache when
installed from an index.
ES modules: relative imports stay revalidated
An entry module loaded with a token is cached a year, but the files it imports with a relative
path (import "../lib/x.js") are requested without v, so they are always revalidated. When
the plugin is upgraded, the page asks for the entry under its new URL, and the entry gets the
new imports. Do not give those imports a hand-made ?v= of their own.
Service Worker Handlers
Plugins can extend the core service worker by registering handler scripts via sw_handler_files. The core serves a single SW at /service-worker.js (scope /) composed from:
- Base skeleton (
service-worker-base.jsin core) —install,activate, genericpushandnotificationclickhandlers - Plugin handlers appended in plugin load order
Registering handlers
class MyPlugin(FastPluggyBaseModule):
module_name: str = "my_plugin"
sw_handler_files: list = ["js/sw-handlers.js"] # relative to static/
The file executes in the service worker global scope (self). Handlers register by type into the dispatch map:
// static/js/sw-handlers.js
self.swHandlers = self.swHandlers || {};
self.swHandlers['MY_CUSTOM_MESSAGE'] = function(event) {
console.log('Got custom message:', event.data);
// event.data = {type: 'MY_CUSTOM_MESSAGE', ...}
};
Do NOT add raw addEventListener('message', ...) — multiple plugins doing so would conflict. Use the dispatch map instead. The base SW's message listener delegates to self.swHandlers[event.data.type].
Available SW APIs
Handler scripts can use:
- self.clients — iterate open pages, send messages
- self.registration — push subscriptions, notifications
- self.addEventListener() for push, notificationclick, etc.
Cache busting
The SW URL includes a hash of the composed content (/service-worker.js?v=<sha256>), so any plugin handler change triggers SW re-registration on the next page load.
Load Error Handling
When a plugin raises an exception during initialization (in on_load_complete() or earlier), the framework disables it gracefully instead of leaving it in a broken state.
PluginLoadError
Raise PluginLoadError for expected load failures (e.g. missing external service, unsupported DB):
from fastpluggy.core.module_base import PluginLoadError
class MyPlugin(FastPluggyBaseModule):
def on_load_complete(self):
if not self.check_postgres():
raise PluginLoadError("PostgreSQL required — this plugin does not support SQLite")
The admin UI shows the clean user-facing message (no traceback). The plugin is marked load_failed=True and routes return a friendly error page instead of 500.
Unexpected errors
For unexpected exceptions (bugs, programming errors), the framework still disables the plugin but stores the full traceback. Admins see it in the plugin overview page.
Plugin state
After a load failure:
- plugin_state.load_failed = True
- plugin_state.loaded = False
- plugin_state.error contains the message (clean for PluginLoadError, full traceback for others)
- Requests to the plugin's routes show an error page with the failure reason
- Other plugins continue loading normally
The admin UI shows a red "Load Failed" badge and hides the Enable/Disable toggle (the plugin cannot be re-enabled until the cause is fixed and the app restarted).