Writing Plugins

This guide explains the plugin API and how to write custom plugins. I suggest readingPlugin Basics first if you have not done so already. You might also want to have a look at theUsing Plugins for some practical examples.

Plugin API

Any callable that accepts a function and returns a function is a valid plugin. This simple approach has its limits, though. Plugins that need more context and control can implement the extendedPlugin interface and hook into advanced features. Note that this is not a real class you can import frombottle, just a contract that plugins must implement to be recognized as extended plugins.

classPlugin

Plugins must be callable or implementapply(). Ifapply() is defined, it is always preferred over calling the plugin directly. All other methods and attributes are optional.

name

BothBottle.uninstall() and theskip parameter ofBottle.route() accept a name string to refer to a plugin or plugin type. This works only for plugins that have a name attribute.

api

The Plugin API is still evolving. This integer attribute tells bottle which version to use. If it is missing, bottle defaults to the first version. The current version is2. SeePlugin API Versions for details.

setup(self,app:Bottle)

Called as soon as the plugin is installed to an application viaBottle.install(). The only parameter is the application object the plugin is installed to. This method isnot called for plugins that were applied to routes viaapply, but only for plugins installed to an application.

__call__(self,callback)

As long asapply() is not defined, the plugin itself is used as a decorator and applied directly to each route callback. The only parameter is the callback to be decorated. Whatever is returned by this method replaces the original callback. If there is no need to wrap or replace a given callback, just return the unmodified callback parameter.

apply(self,callback,route:Route)

If defined, this method is used in favor of__call__() to decorate route callbacks. The additionalroute parameter is an instance ofRoute and provides a lot of context and meta-information and about the route to be decorated. SeeThe Route Context for details.

close(self)

Called as soon as the plugin is uninstalled or the application is closed (seeBottle.uninstall() orBottle.close()). This method isnot called for plugins that were applied to routes viaapply, but only for plugins installed to an application.

Plugin API Versions

The Plugin API is still evolving and changed with Bottle 0.10 to address certain issues with the route context dictionary. To ensure backwards compatibility with 0.9 Plugins, we added an optionalPlugin.api attribute to tell bottle which API to use. The API differences are summarized here.

  • Bottle 0.9 API 1 (Plugin.api not present)

    • Original Plugin API as described in the 0.9 docs.

  • Bottle 0.10 API 2 (Plugin.api equals 2)

    • Thecontext parameter of thePlugin.apply() method is now an instance ofRoute instead of a context dictionary.

The Route Context

TheRoute instance passed toPlugin.apply() provides detailed information about the to-be-decorated route, the original route callback and route specific configuration.

Keep in mind thatRoute.config is local to the route, but shared between all plugins. It is always a good idea to add a unique prefix or, if your plugin needs a lot of configuration, store it in a separate namespace within theconfig dictionary. This helps to avoid naming collisions between plugins.

While someRoute attributes are mutable, changes may have unwanted effects on other plugins and also only affect plugins that were not applied yet. If you need to make changes to the route that are recognized by all plugins, callRoute.reset() afterwards. This will clear the route cache and apply all plugins again next time the route is called, giving all plugins a chance to adapt to the new config. The router is not updated, however. Changes torule ormethod values have no effect on the router, only on plugins. This may change in the future.

Runtime optimizations

Once all plugins are applied to a route, the wrapped route callback is cached to speed up subsequent requests. If the behavior of your plugin depends on configuration, and you want to be able to change that configuration at runtime, you need to read the configuration on each request. Easy enough.

For performance reasons however, it might be worthwhile to return a different wrapper based on current needs, work with closures, or enable or disable a plugin at runtime. Let’s take the built-inHooksPlugin as an example: If no hooks are installed, the plugin removes itself from all routes and has virtually no overhead. As soon as you install the first hook, the plugin activates itself and takes effect again.

To achieve this, you need control over the callback cache:Route.reset() clears the cache for a single route andBottle.reset() clears all caches for all routes of an application at once. On the next request, all plugins are re-applied to the route as if it were requested for the first time.

Common patterns

Dependency or resource injection

Plugins may checks if the callback accepts a specific keyboard parameter and only apply themselves if that parameter is present. For example, route callbacks that expect adb keyword argument need a database connection. Routes that do not expect such a parameter can be skipped and not decorated. The paramneter name should be configurable to avoid conflicts with other plugins or route parameters.

Request context properties

Plugins may add new request-local properties to the currentrequest, for examplerequest.session for a durable session orrequest.user for logged in users. SeeRequest.__setattr__.

Response type mapping

Plugins may check the return value of the wrapped callback and transform or serialize the output to a new type. The bundledJsonPlugin does exactly that.

Zero overhead plugins

Plugins that are not needed on a specific route should return the callback unchanged. If they want to remove themselves from a route at runtime, they can callRoute.reset() and skip the route the next time it is triggered.

Before / after each request

Plugins can be a convenient alternative tobefore_request orafter_request hooks (seeBottle.add_hook()), especially if both are needed.

Plugin Example: SQLitePlugin

This plugin provides an sqlite3 database connection handle as an additional keyword argument to wrapped callbacks, but only if the callback expects it. If not, the route is ignored and no overhead is added. The wrapper does not affect the return value, but handles plugin-related exceptions properly.Plugin.setup() is used to inspect the application and search for conflicting plugins.

importsqlite3importinspectclassSQLitePlugin:name='sqlite'api=2def__init__(self,dbfile=':memory:',autocommit=True,dictrows=True,keyword='db'):self.dbfile=dbfileself.autocommit=autocommitself.dictrows=dictrowsself.keyword=keyworddefsetup(self,app):''' Make sure that other installed plugins don't affect the same            keyword argument.'''forotherinapp.plugins:ifnotisinstance(other,SQLitePlugin):continueifother.keyword==self.keyword:raisePluginError("Found another sqlite plugin with "\"conflicting settings (non-unique keyword).")defapply(self,callback,route):# Override global configuration with route-specific values.conf=route.config.get('sqlite')or{}dbfile=conf.get('dbfile',self.dbfile)autocommit=conf.get('autocommit',self.autocommit)dictrows=conf.get('dictrows',self.dictrows)keyword=conf.get('keyword',self.keyword)# Test if the original callback accepts a 'db' keyword.# Ignore it if it does not need a database handle.args=inspect.getargspec(route.callback)[0]ifkeywordnotinargs:returncallbackdefwrapper(*args,**kwargs):# Connect to the databasedb=sqlite3.connect(dbfile)# This enables column access by name: row['column_name']ifdictrows:db.row_factory=sqlite3.Row# Add the connection handle as a keyword argument.kwargs[keyword]=dbtry:rv=callback(*args,**kwargs)ifautocommit:db.commit()exceptsqlite3.IntegrityError,e:db.rollback()raiseHTTPError(500,"Database Error",e)finally:db.close()returnrv# Replace the route callback with the wrapped one.returnwrapper

This plugin is just an example, but actually usable:

sqlite=SQLitePlugin(dbfile='/tmp/test.db')bottle.install(sqlite)@route('/show/<page>')defshow(page,db):row=db.execute('SELECT * from pages where name=?',page).fetchone()ifrow:returntemplate('showpage',page=row)returnHTTPError(404,"Page not found")@route('/static/<fname:path>')defstatic(fname):returnstatic_file(fname,root='/some/path')@route('/admin/set/<db:re:[a-zA-Z]+>',skip=[sqlite])defchange_dbfile(db):sqlite.dbfile='/tmp/%s.db'%dbreturn"Switched DB to%s.db"%db

The first route needs a database connection and tells the plugin to create a handle by accepting adb keyword argument. The second route does not need a database and is therefore ignored by the plugin. The third route does expect a ‘db’ keyword argument, but explicitly skips the sqlite plugin. This way the argument is not overruled by the plugin and still contains the value of the same-named url argument.