hooks.rst 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. .. _plugin_development_hooks:
  2. Using Hooks
  3. ===========
  4. Hooks are invoked based on an event occurring within FlaskBB. This makes it
  5. possible to change the behavior of certain actions without modifying the
  6. actual source code of FlaskBB.
  7. For your plugin to actually do something useful, you probably want to 'hook'
  8. your code into FlaskBB. This can be done throughout a lot of places in the
  9. code. FlaskBB loads and calls the hook calls hook functions from registered
  10. plugins for any given hook specification.
  11. Each hook specification has a corresponding hook implementation. By default,
  12. all hooks that are prefix with ``flaskbb_`` will be marked as a standard
  13. hook implementation. It is possible to modify the behavior of hooks.
  14. For example, default hooks are called in LIFO registered order.
  15. Although, registration order might not be deterministic. A hookimpl
  16. can influence its call-time invocation position using special attributes. If
  17. marked with a "tryfirst" or "trylast" option it will be executed first or last
  18. respectively in the hook call loop::
  19. hookimpl = HookimplMarker('flaskbb')
  20. @hookimpl(trylast=True)
  21. def flaskbb_additional_setup(app):
  22. return "save the best for last"
  23. In order to extend FlaskBB with your Plugin you will need to connect your
  24. callbacks to the hooks.
  25. Let's look at an actually piece of `used code`_.
  26. .. sourcecode:: python
  27. def flaskbb_load_blueprints(app):
  28. app.register_blueprint(portal, url_prefix="/portal")
  29. By defining a function called ``flaskbb_load_blueprints``, which has a
  30. corresponding hook specification under the same name. FlaskBB will pass
  31. in an ``app`` object as specified in the hook spec, which we will use to
  32. register a new blueprint. It is also possible to completely omit the ``app``
  33. argument from the function where it is **not possible** to add new arguments to
  34. the hook implemention.
  35. For a complete list of all available hooks in FlaskBB see the
  36. :ref:`hooks` section.
  37. pytest and pluggy are good resources to get better understanding on how to
  38. write `hook functions`_ using `pluggy`_.
  39. .. _`used code`: https://github.com/sh4nks/flaskbb-plugins/blob/master/portal/portal/__init__.py#L31
  40. .. _`hook functions`: https://docs.pytest.org/en/latest/writing_plugins.html#writing-hook-functions
  41. .. _`pluggy`: https://pluggy.readthedocs.io/en/latest/#defining-and-collecting-hooks