diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f930f8d --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012 Alen Mujezinovic, Caffeinehit Ltd + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..02a2156 --- /dev/null +++ b/README.rst @@ -0,0 +1,55 @@ +==== +yell +==== + +Pluggable notifications for your Python apps. + +`yell` is not a notification storage or delivery backend but a set of APIs that make it easy to add your own delivery mechanisms. + + +Using yelling decorators +------------------------ + +:: + + from yell.decorators import yelling + + @yelling(name = 'buffalo') + def buffalo_printer(message): + print message + + @yelling(name = 'buffalo') + def buffalo_saver(message): + save(message) + + yell("buffalo", _("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo")) + + +Using yelling classes +--------------------- + +:: + + from yell import Yell, yell + + class Buffalo(Yell): + name = "buffalo" + message = _("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo") + + def yell(self, *args, **kwargs): + print self.message + + class BuffaloEmail(Buffalo): + def yell(self, *args, **kwargs): + send_mail("Buffalo", self.message, 'buffalo@example.com', [kwargs.get('user').email]) + + class BuffaloDatabase(Buffalo): + def yell(self, *args, **kwargs): + BuffaloModel.objects.create(user = kwargs.get('user')) + + # The default behaviour is to use every notification backend with the same + # name + yell("buffalo", user = User.objects.get(id=1)) + + # Only send emails + yell("buffalo", user = User.objects.get(id=1), backends = [BuffaloEmail]) diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..a0e2df3 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/yell.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/yell.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/yell" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/yell" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..f846a8b --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,242 @@ +# -*- coding: utf-8 -*- +# +# yell documentation build configuration file, created by +# sphinx-quickstart on Wed Apr 4 15:42:17 2012. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os, yell + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'yell' +copyright = u'2012, Alen Mujezinovic' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = yell.__version__ +# The full version, including alpha/beta/rc tags. +release = yell.__version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'yelldoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'yell.tex', u'yell Documentation', + u'Alen Mujezinovic', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'yell', u'yell Documentation', + [u'Alen Mujezinovic'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'yell', u'yell Documentation', + u'Alen Mujezinovic', 'yell', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..26e31bc --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,68 @@ +==== +yell +==== + +Pluggable notifications for your Python apps. + +`yell` is not a notification storage or delivery backend but a set of APIs that make it easy to add your own delivery mechanisms. + + +Using yelling decorators +------------------------ + +:: + + from yell.decorators import yelling + + @yelling(name = 'buffalo') + def buffalo_printer(message): + print message + + @yelling(name = 'buffalo') + def buffalo_saver(message): + save(message) + + yell("buffalo", _("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo")) + + +Using yelling classes +--------------------- + +:: + + from yell import Yell, yell + + class Buffalo(Yell): + name = "buffalo" + message = _("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo") + + def yell(self, *args, **kwargs): + print self.message + + class BuffaloEmail(Buffalo): + def yell(self, *args, **kwargs): + send_mail("Buffalo", self.message, 'buffalo@example.com', [kwargs.get('user').email]) + + class BuffaloDatabase(Buffalo): + def yell(self, *args, **kwargs): + BuffaloModel.objects.create(user = kwargs.get('user')) + + # The default behaviour is to use every notification backend with the same + # name + yell("buffalo", user = User.objects.get(id=1)) + + # Only send emails + yell("buffalo", user = User.objects.get(id=1), backends = [BuffaloEmail]) + + + +API +=== + +.. toctree:: + :maxdepth: 5 + + yell + yell.backends + + diff --git a/docs/yell.backends.rst b/docs/yell.backends.rst new file mode 100644 index 0000000..92a7c7d --- /dev/null +++ b/docs/yell.backends.rst @@ -0,0 +1,15 @@ +:mod:`yell.backends.celery` +--------------------------- + +.. automodule:: yell.backends.celery + :members: + + +:mod:`yell.backends.django` +--------------------------- + +.. automodule:: yell.backends.django + :members: + + + diff --git a/docs/yell.rst b/docs/yell.rst new file mode 100644 index 0000000..618e08d --- /dev/null +++ b/docs/yell.rst @@ -0,0 +1,21 @@ +:mod:`yell` +----------- + +.. automodule:: yell + :members: + + +:mod:`yell.decorators` +---------------------- + +.. automodule:: yell.decorators + :members: + + +:mod:`yell.registry` +-------------------- + +.. automodule:: yell.registry + :members: + + diff --git a/readthedocs.txt b/readthedocs.txt new file mode 100644 index 0000000..3873968 --- /dev/null +++ b/readthedocs.txt @@ -0,0 +1 @@ +celery \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..47c9ae6 --- /dev/null +++ b/setup.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +from setuptools import setup, find_packages + +import yell + +METADATA = dict( + name='yell', + version=yell.__version__, + author='Alen Mujezinovic', + author_email='flashingpumpkin@gmail.com', + description='User notification library with pluggable backends. Compatible with popular frameworks such as Django, Flask, Celery.', + long_description=open('README.rst').read(), + url='https://github.com/caffeinehit/yell', + keywords='django flask celery user notifications yell buffalo', + include_package_data=True, + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Environment :: Console', + 'Environment :: MacOS X', + 'Environment :: Web Environment', + 'Environment :: Other Environment', + 'Environment :: X11 Applications', + 'Framework :: Django', + 'Framework :: Paste', + 'Framework :: Pylons', + 'Framework :: TurboGears', + 'Framework :: Twisted', + 'Intended Audience :: Developers', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Topic :: Communications', + 'Topic :: Communications :: Email', + 'Topic :: Database', + 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', + 'Topic :: Software Development :: Libraries :: Application Frameworks', + 'Topic :: Software Development :: Libraries :: Python Modules', + 'Topic :: Utilities', + ], + packages=find_packages(), + test_suite='yell.tests', +) + +if __name__ == '__main__': + setup(**METADATA) diff --git a/yell/__init__.py b/yell/__init__.py new file mode 100644 index 0000000..4d9fba5 --- /dev/null +++ b/yell/__init__.py @@ -0,0 +1,63 @@ +__version__ = "0.1" + +import registry + +class MetaYell(type): + """ + Metaclass that stores all yells in the registry. + """ + def __new__(cls, name, bases, attrs): + Yell = super(MetaYell, cls).__new__(cls, name, bases, attrs) + + if Yell.name is not None: + registry.yells[Yell.name] = registry.yells.get(Yell.name, []) + [Yell] + + return Yell + + +class Yell(object): + """ + Base class for any kind of notifications. Inherit from this class to create + your own notification types and backends. + + Subclasses need to implement :meth:`yell`. + """ + __metaclass__ = MetaYell + + name = None + """ + A name for this yell. + """ + + def yell(self, *args, **kwargs): + """ + A method that delivers a notification. + """ + raise NotImplementedError + +def yell(name, *args, **kwargs): + """ + Send notifications. If ``backends==None``, all backends with the same name + will be used to deliver a notification. + + If ``backends`` is a list, only the specified backends will be used. + + :param name: The yell to send + :param backends: A list of backends to be used or ``None`` to use all associated backends + """ + assert name in registry.yells, "'{0}' is not a valid yell.".format(repr(name)) + + backends = kwargs.pop('backends', None) + + if backends is None: + backends = registry.yells[name] + + results = [] + + for Backend in backends: + backend = Backend() + results.append(backend.yell(*args, **kwargs)) + + return results + + diff --git a/yell/backends/__init__.py b/yell/backends/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/yell/backends/celery.py b/yell/backends/celery.py new file mode 100644 index 0000000..e97eeaf --- /dev/null +++ b/yell/backends/celery.py @@ -0,0 +1,68 @@ +from __future__ import absolute_import +from celery.task import Task +from yell import Yell, yell, registry + +class CeleryYellingTask(Task): + """ Dispatch and run the yelling """ + def run(self, name=None, yeller=None, *args, **kwargs): + """ + The Celery task. + + Delivers the notification via all backends returned by :param:`yeller`. + """ + assert name is not None, "No 'name' specified to yell" + assert yeller is not None, "No 'yeller' specified to yell with" + + backends = yeller().get_backends(*args, **kwargs) + yell(name, backends=backends, *args, **kwargs) + +class CeleryYell(Yell): + """ + Delivers notifications through Celery. + + :example: + + :: + + from yell import yell, Yell + + class EmailYell(Yell): + yell = 'async' + def yell(self, *args, **kwargs): + # Deliver email + + class DBYell(Yell): + yell = 'async' + def yell(self, *args, **kwargs): + # Save to database + + class AsyncYell(CeleryYell): + yell = 'async' + + yell('async', backends = [AsyncYell], + text = "This notification is routed through Celery before being sent and saved") + + In the above example when calling :attr:`yell.yell` will invoke ``EmailYell`` and + ``DBYell`` once the task was delivered through Celery. + + """ + name = None + """ + The name of this notification. Override in subclasses. + """ + + def get_backends(self, *args, **kwargs): + """ + Return all backends the task should use to deliver notifications. + By default all backends with the same :attr:`name` except for subclasses + of :class:`CeleryYell` will be used. + """ + return filter(lambda cls: not isinstance(cls, self.__class__), registry.yells[self.yell]) + + def yell(self, *args, **kwargs): + """ + Dispatches the notification to Celery + """ + return CeleryYellingTask.delay(name=self.name, yeller=self.__class__, *args, **kwargs) + + diff --git a/yell/backends/django.py b/yell/backends/django.py new file mode 100644 index 0000000..6214573 --- /dev/null +++ b/yell/backends/django.py @@ -0,0 +1,123 @@ +from __future__ import absolute_import + +from django.conf import settings +from django import template +from django.core.mail import send_mail, EmailMultiAlternatives +from yell import Yell +import mimetypes + + +class EmailBackend(Yell): + """ + Send emails via :attr:`django.core.mail.send_mail` + """ + + subject = None + """ Email subject """ + body = None + """ Email body """ + + + def get_subject(self, *args, **kwargs): + """ + Return a subject. Override if you need templating or such. + """ + return self.subject + + def get_body(self, *args, **kwargs): + """ + Return a body. Override if you need templating or such. + """ + return self.body + + def get_from(self, *args, **kwargs): + return settings.DEFAULT_FROM_EMAIL + + def get_to(self, *args, **kwargs): + return kwargs.get('to') + + def yell(self, *args, **kwargs): + + return send_mail( + self.get_subject(*args, **kwargs), + self.get_body(*args, **kwargs), + self.get_from(*args, **kwargs), + self.get_to(*args, **kwargs), + ) + +class MultipartEmailBackend(EmailBackend): + """ + Send emails via :class:`django.core.mail.EmailMultiAlternatives` + """ + default_content_type = 'text/plain' + """ + The default content type. + """ + + body = {} + """ + Email body mapping content type to message. Requires at least a key for + :attr:`default_content_type`. + """ + + + def get_body(self, *args, **kwargs): + assert self.default_content_type in self.body, "No message body for default content type '%s'" % self.default_content_type + return self.body + + def get_default_body(self, *args, **kwargs): + return self.get_body(*args, **kwargs)[self.default_content_type] + + def yell(self, *args, **kwargs): + message = EmailMultiAlternatives( + self.get_subject(*args, **kwargs), + self.get_default_body(*args, **kwargs), + self.get_from(*args, **kwargs), + self.get_to(*args, **kwargs) + ) + + for content_type, body in self.get_body(*args, **kwargs): + if content_type == self.default_content_type: continue + message.attach_alternative(body, content_type) + + return message.send() + +class TemplatedEmailBackend(MultipartEmailBackend): + """ + Generates email bodies from templates. + + :example: + + :: + + class SignupMessage(TemplatedEmailBackend): + name = 'signup' + subject = "Welcome to %s" % Site.objects.get_current().name + content_types = ['text/plain', 'text/html'] + + The `SignupMessage` class would look up following templates for the email body: + + * `yell/signup.txt` + * `yell/signup.html` + + """ + content_types = ['text/plain', 'text/html'] + """ + Default content types to render + """ + + # Memoize + _body = None + + def get_body(self, *args, **kwargs): + """ + Render message bodies by guessing the file extension from + :attr:`content_types` + """ + if self._body is None: + self._body = {} + for ctype in self.content_types: + tpl = template.loader.get_template('yell/%s%s' % (self.name, mimetypes.guess_extension(ctype))) + self._body[ctype] = tpl.render(template.Context(kwargs)) + return self._body + diff --git a/yell/decorators.py b/yell/decorators.py new file mode 100644 index 0000000..b158930 --- /dev/null +++ b/yell/decorators.py @@ -0,0 +1,72 @@ +from yell import Yell, yell + +class DecoratedYell(Yell): + func = None + """ + The function that has been decorated. + """ + + def yell(self, *args, **kwargs): + return self.func(*args, **kwargs) + +def yelling(name=None, backends=None): + """ + Decorator to simplify creation of notification backends. + + :example: + + :: + + from yell.decorators import notification + from yell import yell + + @notification('like') + def like_email(user, obj): + send_mail("%s liked %s" % (user, obj), "No/Text", "noreply@example.com", + [obj.user.email]) + + @notification('like') + def like_db(user, obj): + DBNotification.objects.create(user = user, obj = obj, type = 'like') + + @notification('like') + def like(*args, **kwargs): + pass + + # Use all backends + yell('like', user = user, obj = obj) + like.yell(user = user, obj = obj) + + # Only use the email backend + like_email.yell_once(user = user, obj = obj) + + """ + + def wrapper(func): + def funcwrapper(self, *args, **kwargs): + """ Wrapping the yelling function so it doesn't receive `self` """ + return func(*args, **kwargs) + + YellCls = type('%sYell' % name.lower().title(), (DecoratedYell,), { + 'func': funcwrapper, + 'name': name + }) + + def yell_all(*args, **kwargs): + """ + Sends this yell off to every backend with the configured name. + """ + return yell(name, *args, **kwargs) + + def yell_once(*args, **kwargs): + """ + Sends this yell off only to the current backend. + """ + return yell(name, backends=[YellCls], *args, **kwargs) + + func.yell = yell_all + func.yell_once = yell_once + + return func + + return wrapper diff --git a/yell/registry.py b/yell/registry.py new file mode 100644 index 0000000..a59f0f2 --- /dev/null +++ b/yell/registry.py @@ -0,0 +1,2 @@ +yells = {} +""" Registry mapping yell names to backends """ diff --git a/yell/tests.py b/yell/tests.py new file mode 100644 index 0000000..f92e472 --- /dev/null +++ b/yell/tests.py @@ -0,0 +1,75 @@ +from yell import yell, Yell +from yell.decorators import yelling + + +try: + import unittest2 as unittest +except ImportError: + import unittest + +@yelling(name='decorator') +def decorator_yell0(*args, **kwargs): + return 'Decorator 0', args, kwargs + +@yelling(name='decorator') +def decorator_yell1(*args, **kwargs): + return 'Decorator 1', args, kwargs + +class ClassYell0(Yell): + name = 'class' + + def yell(self, *args, **kwargs): + return 'Class 0', args, kwargs + +class ClassYell1(Yell): + name = 'class' + + def yell(self, *args, **kwargs): + return 'Class 1', args, kwargs + +class AssertMixin(object): + retval = None + def _assert_results(self, results): + for i, result in enumerate(results): + self.assertTrue('%s %s' % (self.retval, i) == result[0], """ Return value '%s %s' not equal to '%s' """ % (self.retval, i, result[0])) + + self.assertTrue('Arg1' == result[1][0], """ Expected value 'Arg1' does not match received value '%s' """ % result[1][0]) + self.assertTrue('Arg2' == result[1][1], """ Expected value 'Arg2' does not match received value '%s' """ % result[1][1]) + + self.assertTrue('Kwarg1' in result[2].values()) + self.assertTrue('Kwarg2' in result[2].values()) + + +class TestDecoratorYell(AssertMixin, unittest.TestCase): + retval = 'Decorator' + + def test_yelling_with_decorator(self): + results = yell('decorator', 'Arg1', 'Arg2', kwarg1='Kwarg1', kwarg2='Kwarg2') + self.assertEqual(2, len(results)) + self._assert_results(results) + + results = decorator_yell0.yell('Arg1', 'Arg2', kwarg1='Kwarg1', kwarg2='Kwarg2') + self._assert_results(results) + self.assertEqual(2, len(results)) + + + def test_yelling_once_with_decorator(self): + results = decorator_yell0.yell_once('Arg1', 'Arg2', kwarg1='Kwarg1', kwarg2='Kwarg2') + self.assertEqual(1, len(results)) + self._assert_results(results) + + +class TestClassYell(AssertMixin, unittest.TestCase): + retval = 'Class' + + def test_yelling_with_class(self): + results = yell('class', 'Arg1', 'Arg2', kwarg1='Kwarg1', kwarg2='Kwarg2') + self.assertEqual(2, len(results)) + self._assert_results(results) + + def test_yelling_once_with_class(self): + results = yell('class', 'Arg1', 'Arg2', kwarg1='Kwarg1', kwarg2='Kwarg2', backends=[ClassYell0]) + self.assertEqual(1, len(results)) + self._assert_results(results) + +