To create a new extension, define a class that implements the init_app(self, app) method. During the sea initialization process, the current_app instance is automatically passed as the app argument to this method.
Implementation Pattern
- Define an
__init__ method to set up initial state. - Implement
init_app(self, app) to configure the extension using app.config. Use app.config.get_namespace('PREFIX_') to retrieve a dictionary of configuration settings starting with a specific prefix. - (Optional) Implement
__getattr__ to proxy method calls from the extension instance directly to an underlying client object, making the extension transparent to the user.
Example: Redis Extension
This example creates a Redis extension that initializes a redis.StrictRedis object using configuration keys prefixed with REDIS_.
import redis
class Redis:
def __init__(self):
self._client = None
def init_app(self, app):
# Retrieves config keys starting with 'REDIS_'
opts = app.config.get_namespace('REDIS_')
self._pool = redis.ConnectionPool(**opts)
self._client = redis.StrictRedis(connection_pool=self._pool)
def __getattr__(self, name):
# Proxies all calls to the underlying redis client
return getattr(self._client, name)