Permalink
Fetching contributors…
Cannot retrieve contributors at this time
55 lines (41 sloc) 1.51 KB
from pyramid_mailer.mailer import Mailer
from pyramid_mailer.interfaces import IMailer
def mailer_factory_from_settings(settings, prefix='mail.'):
"""
Factory function to create a Mailer instance from settings.
Equivalent to :meth:`pyramid_mailer.mailer.Mailer.from_settings`.
:versionadded: 0.2.2
"""
return Mailer.from_settings(settings, prefix)
def includeme(config):
"""
Registers a mailer instance.
:versionadded: 0.4
"""
settings = config.registry.settings
prefix = settings.get('pyramid_mailer.prefix', 'mail.')
mailer = mailer_factory_from_settings(settings, prefix=prefix)
_set_mailer(config, mailer)
def _set_mailer(config, mailer):
"""Set mailer in application config.
Also adds a ``.mailer`` request property.
"""
config.registry.registerUtility(mailer, IMailer)
if hasattr(config, 'add_request_method'):
config.add_request_method(get_mailer, 'mailer', reify=True)
def get_mailer(request):
"""Obtain a mailer previously registered via
``config.include('pyramid_mailer')`` or
``config.include('pyramid_mailer.testing')``.
The mailer instance will be re-bound to the transaction manager set via
``request.tm`` if available.
:versionadded: 0.4
"""
registry = getattr(request, 'registry', None)
if registry is None:
registry = request
mailer = registry.getUtility(IMailer)
tm = getattr(request, 'tm', None)
if tm:
mailer = mailer.bind(transaction_manager=tm)
return mailer