├── .coveralls ├── .gitignore ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── demo ├── demo │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py ├── djwebhooks ├── __init__.py ├── admin.py ├── decorators.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── senders │ ├── __init__.py │ ├── orm.py │ ├── redislog.py │ └── redisq.py ├── static │ ├── css │ │ └── djwebhooks.css │ ├── img │ │ └── .gitignore │ └── js │ │ └── djwebhooks.js ├── templates │ └── djwebhooks │ │ └── base.html ├── utils.py └── views.py ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── history.rst ├── index.rst ├── installation.rst ├── make.bat ├── readme.rst └── usage.rst ├── requirements-test.txt ├── requirements.txt ├── runtests.py ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── test_models.py ├── test_sender_orm.py ├── test_sender_redis_log.py └── test_sender_redisq.py └── tox.ini /.coveralls: -------------------------------------------------------------------------------- 1 | service_name: travis-pro 2 | repo_token: zBY7qrQiwtyc2WU14mPmUs5bmczBo5SBM -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | nosetests.xml 28 | 29 | # Translations 30 | *.mo 31 | 32 | # Mr Developer 33 | .mr.developer.cfg 34 | .project 35 | .pydevproject 36 | 37 | # Complexity 38 | output/*.html 39 | output/*/index.html 40 | 41 | # Sphinx 42 | docs/_build -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Config file for automatic testing at travis-ci.org 2 | 3 | language: python 4 | services: 5 | - redis 6 | 7 | python: 8 | - "3.3" 9 | - "2.7" 10 | - "pypy" 11 | 12 | # command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors 13 | install: pip install -r requirements-test.txt 14 | 15 | # command to run tests using coverage, e.g. python setup.py test 16 | script: make test 17 | 18 | # report coverage to coveralls.io 19 | # after_success: coveralls -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Credits 3 | ======= 4 | 5 | Development Lead 6 | ---------------- 7 | 8 | * Daniel Greenfeld 9 | 10 | Contributors 11 | ------------ 12 | 13 | None yet. Why not be the first? -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Contributing 3 | ============ 4 | 5 | Contributions are welcome, and they are greatly appreciated! Every 6 | little bit helps, and credit will always be given. 7 | 8 | You can contribute in many ways: 9 | 10 | Types of Contributions 11 | ---------------------- 12 | 13 | Report Bugs 14 | ~~~~~~~~~~~ 15 | 16 | Report bugs at https://github.com/pydanny/dj-webhooks/issues. 17 | 18 | If you are reporting a bug, please include: 19 | 20 | * Your operating system name and version. 21 | * Any details about your local setup that might be helpful in troubleshooting. 22 | * Detailed steps to reproduce the bug. 23 | 24 | Fix Bugs 25 | ~~~~~~~~ 26 | 27 | Look through the GitHub issues for bugs. Anything tagged with "bug" 28 | is open to whoever wants to implement it. 29 | 30 | Implement Features 31 | ~~~~~~~~~~~~~~~~~~ 32 | 33 | Look through the GitHub issues for features. Anything tagged with "feature" 34 | is open to whoever wants to implement it. 35 | 36 | Write Documentation 37 | ~~~~~~~~~~~~~~~~~~~ 38 | 39 | dj-webhooks could always use more documentation, whether as part of the 40 | official dj-webhooks docs, in docstrings, or even on the web in blog posts, 41 | articles, and such. 42 | 43 | Submit Feedback 44 | ~~~~~~~~~~~~~~~ 45 | 46 | The best way to send feedback is to file an issue at https://github.com/pydanny/dj-webhooks/issues. 47 | 48 | If you are proposing a feature: 49 | 50 | * Explain in detail how it would work. 51 | * Keep the scope as narrow as possible, to make it easier to implement. 52 | * Remember that this is a volunteer-driven project, and that contributions 53 | are welcome :) 54 | 55 | Get Started! 56 | ------------ 57 | 58 | Ready to contribute? Here's how to set up `dj-webhooks` for local development. 59 | 60 | 1. Fork the `dj-webhooks` repo on GitHub. 61 | 2. Clone your fork locally:: 62 | 63 | $ git clone git@github.com:your_name_here/dj-webhooks.git 64 | 65 | 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: 66 | 67 | $ mkvirtualenv dj-webhooks 68 | $ cd dj-webhooks/ 69 | $ python setup.py develop 70 | 71 | 4. Create a branch for local development:: 72 | 73 | $ git checkout -b name-of-your-bugfix-or-feature 74 | 75 | Now you can make your changes locally. 76 | 77 | 5. When you're done making changes, check that your changes pass flake8 and the 78 | tests, including testing other Python versions with tox:: 79 | 80 | $ flake8 djwebhooks tests 81 | $ python setup.py test 82 | $ tox 83 | 84 | To get flake8 and tox, just pip install them into your virtualenv. 85 | 86 | 6. Commit your changes and push your branch to GitHub:: 87 | 88 | $ git add . 89 | $ git commit -m "Your detailed description of your changes." 90 | $ git push origin name-of-your-bugfix-or-feature 91 | 92 | 7. Submit a pull request through the GitHub website. 93 | 94 | Pull Request Guidelines 95 | ----------------------- 96 | 97 | Before you submit a pull request, check that it meets these guidelines: 98 | 99 | 1. The pull request should include tests. 100 | 2. If the pull request adds functionality, the docs should be updated. Put 101 | your new functionality into a function with a docstring, and add the 102 | feature to the list in README.rst. 103 | 3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy. Check 104 | https://travis-ci.org/pydanny/dj-webhooks/pull_requests 105 | and make sure that the tests pass for all supported Python versions. 106 | 107 | Tips 108 | ---- 109 | 110 | To run a subset of tests:: 111 | 112 | $ python -m unittest tests.test_djwebhooks -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | History 4 | ------- 5 | 6 | 0.2.2 (2014-05-22) 7 | +++++++++++++++++++ 8 | 9 | * Added redislog_hook. This synchronous hook saves the hook results to redis lists. 10 | * Added identifier field to WebhookTarget 11 | * Added identifier argument to orm and redisq senders. 12 | * Added South migrations for Django=<1.6. 13 | * Declared coding in all Python modules. 14 | * Added verbose names to models 15 | 16 | 0.2.1 (2014-05-17) 17 | ++++++++++++++++++ 18 | 19 | * Removed conf.py file as it just added abstraction. 20 | * Created exlicitly importable hooks. Makes settings management easier. 21 | * Removed utils.py since we no longer do fancy dynamic imports (see previous bullet). 22 | * Coverage now at 100% 23 | 24 | 25 | 0.2.0 (2014-05-15) 26 | ++++++++++++++++++ 27 | 28 | * Refactored the senders to be very extendable. 29 | * Added an ORM based sender. 30 | * Added a redis based sender that uses django-rq. 31 | * Added a `redis-hook` decorator. 32 | * Added admin views. 33 | * Ramped up test coverage to 89%. 34 | * setup.py now includes all dependencies. 35 | 36 | 37 | 0.1.0 (2014-05-12) 38 | ++++++++++++++++++ 39 | 40 | * First release on PyPI. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014, Daniel Greenfeld 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | 8 | * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 9 | 10 | * Neither the name of dj-webhooks nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | recursive-include djwebhooks *.html *.png *.gif *js *.css *jpg *jpeg *svg *py -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build docs 2 | 3 | help: 4 | @echo "clean-build - remove build artifacts" 5 | @echo "clean-pyc - remove Python file artifacts" 6 | @echo "lint - check style with flake8" 7 | @echo "test - run tests quickly with the default Python" 8 | @echo "testall - run tests on every Python version with tox" 9 | @echo "coverage - check code coverage quickly with the default Python" 10 | @echo "docs - generate Sphinx HTML documentation, including API docs" 11 | @echo "release - package and upload a release" 12 | @echo "sdist - package" 13 | 14 | clean: clean-build clean-pyc 15 | 16 | clean-build: 17 | rm -fr build/ 18 | rm -fr dist/ 19 | rm -fr *.egg-info 20 | 21 | clean-pyc: 22 | find . -name '*.pyc' -exec rm -f {} + 23 | find . -name '*.pyo' -exec rm -f {} + 24 | find . -name '*~' -exec rm -f {} + 25 | 26 | lint: 27 | flake8 dj-webhooks tests 28 | 29 | test: 30 | python runtests.py 31 | 32 | test-all: 33 | tox 34 | 35 | coverage: 36 | coverage run --source djwebhooks runtests.py 37 | coverage report -m --omit=djwebhooks/admin.py,djwebhooks/migrations/* 38 | coverage html --omit=djwebhooks/admin.py,djwebhooks/migrations/* 39 | open htmlcov/index.html 40 | 41 | docs: 42 | rm -f docs/dj-webhooks.rst 43 | rm -f docs/modules.rst 44 | sphinx-apidoc -o docs/ dj-webhooks 45 | $(MAKE) -C docs clean 46 | $(MAKE) -C docs html 47 | open docs/_build/html/index.html 48 | 49 | release: clean 50 | python setup.py sdist upload 51 | python setup.py bdist_wheel upload 52 | 53 | sdist: clean 54 | python setup.py sdist 55 | ls -l dist -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ============================= 2 | dj-webhooks 3 | ============================= 4 | 5 | .. image:: https://img.shields.io/pypi/dm/dj-webhooks.svg 6 | :target: https://pypi.python.org/pypi/dj-webhooks 7 | 8 | .. image:: https://badge.fury.io/py/dj-webhooks.png 9 | :target: https://badge.fury.io/py/dj-webhooks 10 | 11 | .. image:: https://img.shields.io/pypi/wheel/dj-webhooks.svg 12 | :target: https://pypi.python.org/pypi/dj-webhooks/ 13 | :alt: Wheel Status 14 | 15 | .. image:: https://travis-ci.org/pydanny/dj-webhooks.png?branch=master 16 | :target: https://travis-ci.org/pydanny/dj-webhooks 17 | 18 | Django + Webhooks Made Easy 19 | 20 | The full documentation is at https://dj-webhooks.readthedocs.org. 21 | 22 | Requirements 23 | ------------ 24 | 25 | * Python 2.7.x or 3.3.2 or higher 26 | * django>=1.5.5 27 | * django-jsonfield>=0.9.12 28 | * django-model-utils>=2.0.2 29 | * django-rq>=0.6.1 30 | * webhooks>=0.3.1 31 | 32 | Quickstart 33 | ---------- 34 | 35 | Install dj-webhooks:: 36 | 37 | pip install dj-webhooks 38 | 39 | Configure some webhook events: 40 | 41 | .. code-block:: python 42 | 43 | # settings.py 44 | WEBHOOK_EVENTS = ( 45 | "purchase.paid", 46 | "purchase.refunded", 47 | "purchase.fulfilled" 48 | ) 49 | 50 | Add some webhook targets: 51 | 52 | .. code-block:: python 53 | 54 | from django.contrib.auth import get_user_model 55 | User = get_user_model() 56 | user = User.objects.get(username="pydanny") 57 | 58 | from webhooks.models import Webhook 59 | WebhookTarget.objects.create( 60 | owner=user, 61 | event="purchase.paid", 62 | target_url="https://mystorefront.com/webhooks/", 63 | identifier="User or system defined string", 64 | header_content_type=Webhook.CONTENT_TYPE_JSON, 65 | ) 66 | 67 | Then use it in a project: 68 | 69 | .. code-block:: python 70 | 71 | from django.contrib.auth import get_user_model 72 | User = get_user_model() 73 | user = User.objects.get(username="pydanny") 74 | 75 | from djwebhooks.decorators import hook 76 | 77 | from myproject.models import Purchase 78 | 79 | # Event argument helps identify the webhook target 80 | @hook(event="purchase.paid") 81 | def send_purchase_confirmation(purchase, owner, identifier): 82 | return { 83 | "order_num": purchase.order_num, 84 | "date": purchase.confirm_date, 85 | "line_items": [x.sku for x in purchase.lineitem_set.filter(inventory__gt=0)] 86 | } 87 | 88 | for purchase in Purchase.objects.filter(status="paid"): 89 | send_purchase_confirmation( 90 | purchase=purchase, 91 | owner=user, 92 | identifier="User or system defined string" 93 | ) 94 | 95 | Storing Redis delivery logs 96 | --------------------------- 97 | 98 | **Note:** The only difference between this and the previous example is the use of the redislog_hook. 99 | 100 | .. code-block:: python 101 | 102 | from django.contrib.auth import get_user_model 103 | User = get_user_model() 104 | user = User.objects.get(username="pydanny") 105 | 106 | from djwebhooks.decorators import redislog_hook 107 | 108 | from myproject.models import Purchase 109 | 110 | # Event argument helps identify the webhook target 111 | @redislog_hook(event="purchase.paid") 112 | def send_purchase_confirmation(purchase, owner, identifier): 113 | return { 114 | "order_num": purchase.order_num, 115 | "date": purchase.confirm_date, 116 | "line_items": [x.sku for x in purchase.lineitem_set.filter(inventory__gt=0)] 117 | } 118 | 119 | for purchase in Purchase.objects.filter(status="paid"): 120 | send_purchase_confirmation( 121 | purchase=purchase, 122 | owner=user, 123 | identifier="User or system defined string" 124 | ) 125 | 126 | 127 | In a queue using django-rq 128 | ---------------------------- 129 | 130 | **Warning:** In practice I've found it's much more realistic to use the ORM or Redislib webhooks and define seperate asynchronous jobs then to rely on the ``djwebhooks.redisq_hook decorator``. Therefore, this functionality is deprecated. 131 | 132 | 133 | 134 | Features 135 | -------- 136 | 137 | * Synchronous webhooks 138 | * Delivery tracking via Django ORM. 139 | * Options for asynchronous webhooks. 140 | 141 | Planned Features 142 | ----------------- 143 | 144 | * Delivery tracking via Redis and other write-fast datastores. 145 | -------------------------------------------------------------------------------- /demo/demo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pydanny/dj-webhooks/88e245bfe2020e96279af261d88bf8469ba469e5/demo/demo/__init__.py -------------------------------------------------------------------------------- /demo/demo/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for demo project. 3 | 4 | For more information on this file, see 5 | https://docs.djangoproject.com/en/1.6/topics/settings/ 6 | 7 | For the full list of settings and their values, see 8 | https://docs.djangoproject.com/en/1.6/ref/settings/ 9 | """ 10 | 11 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 12 | import os 13 | BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 14 | 15 | 16 | # Quick-start development settings - unsuitable for production 17 | # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ 18 | 19 | # SECURITY WARNING: keep the secret key used in production secret! 20 | SECRET_KEY = 'k#6zf3rky+396(#dcwe*t=j(+#r(4eq+jox$4e!mxrz_+jt-4j' 21 | 22 | # SECURITY WARNING: don't run with debug turned on in production! 23 | DEBUG = True 24 | 25 | TEMPLATE_DEBUG = True 26 | 27 | ALLOWED_HOSTS = [] 28 | 29 | 30 | # Application definition 31 | 32 | INSTALLED_APPS = ( 33 | 'django.contrib.admin', 34 | 'django.contrib.auth', 35 | 'django.contrib.contenttypes', 36 | 'django.contrib.sessions', 37 | 'django.contrib.messages', 38 | 'django.contrib.staticfiles', 39 | ) 40 | 41 | MIDDLEWARE_CLASSES = ( 42 | 'django.contrib.sessions.middleware.SessionMiddleware', 43 | 'django.middleware.common.CommonMiddleware', 44 | 'django.middleware.csrf.CsrfViewMiddleware', 45 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 46 | 'django.contrib.messages.middleware.MessageMiddleware', 47 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 48 | ) 49 | 50 | ROOT_URLCONF = 'demo.urls' 51 | 52 | WSGI_APPLICATION = 'demo.wsgi.application' 53 | 54 | 55 | # Database 56 | # https://docs.djangoproject.com/en/1.6/ref/settings/#databases 57 | 58 | DATABASES = { 59 | 'default': { 60 | 'ENGINE': 'django.db.backends.sqlite3', 61 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 62 | } 63 | } 64 | 65 | # Internationalization 66 | # https://docs.djangoproject.com/en/1.6/topics/i18n/ 67 | 68 | LANGUAGE_CODE = 'en-us' 69 | 70 | TIME_ZONE = 'UTC' 71 | 72 | USE_I18N = True 73 | 74 | USE_L10N = True 75 | 76 | USE_TZ = True 77 | 78 | 79 | # Static files (CSS, JavaScript, Images) 80 | # https://docs.djangoproject.com/en/1.6/howto/static-files/ 81 | 82 | STATIC_URL = '/static/' 83 | -------------------------------------------------------------------------------- /demo/demo/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import patterns, include, url 2 | 3 | from django.contrib import admin 4 | admin.autodiscover() 5 | 6 | urlpatterns = patterns('', 7 | # Examples: 8 | # url(r'^$', 'demo.views.home', name='home'), 9 | # url(r'^blog/', include('blog.urls')), 10 | 11 | url(r'^admin/', include(admin.site.urls)), 12 | ) 13 | -------------------------------------------------------------------------------- /demo/demo/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for demo project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") 12 | 13 | from django.core.wsgi import get_wsgi_application 14 | application = get_wsgi_application() 15 | -------------------------------------------------------------------------------- /demo/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /djwebhooks/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.2.2' 2 | -------------------------------------------------------------------------------- /djwebhooks/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.contrib import admin 3 | from django.utils import six 4 | 5 | from .models import WebhookTarget, Delivery 6 | 7 | 8 | class DeliveryAdmin(admin.ModelAdmin): 9 | """ Add this so we can see the result in Python 3. 10 | Currently django-jsonfield hasn't been completely ported. 11 | """ 12 | if six.PY3: 13 | exclude = ('payload', ) 14 | 15 | admin.site.register(Delivery, DeliveryAdmin) 16 | admin.site.register(WebhookTarget) 17 | -------------------------------------------------------------------------------- /djwebhooks/decorators.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Where the hook function/decorator is stored. 4 | Unlike the standard webhooks.decorator, this doesn't 5 | have the developer specify the exact sender callable. 6 | 7 | Write a sender function that uses the Django ORM to: 8 | 9 | * Queries a WebHook model to find target URLS based on event 10 | name and WebHook record creator 11 | * Logs the result in a table. Not ideal for production, but 12 | just as a way to track simple results 13 | """ 14 | 15 | from functools import partial 16 | 17 | 18 | from webhooks.decorators import base_hook 19 | from webhooks.hashes import basic_hash_function 20 | 21 | 22 | from .senders import orm_callable, redisq_callable, redislog_hook 23 | 24 | 25 | # This is decorator that does all the lifting. 26 | hook = partial( 27 | base_hook, 28 | sender_callable=orm_callable, 29 | hash_function=basic_hash_function 30 | ) 31 | 32 | 33 | # alias the hook function 34 | webhook = hook 35 | 36 | 37 | # Make the redis queue hook work 38 | # This is decorator that does all the lifting. 39 | redisq_hook = partial( 40 | base_hook, 41 | sender_callable=redisq_callable, 42 | hash_function=basic_hash_function 43 | ) 44 | 45 | # alias the redis_hook function 46 | redisq_webhook = redisq_hook 47 | 48 | # alias the redis_hook function 49 | redislog_webhook = redislog_hook 50 | -------------------------------------------------------------------------------- /djwebhooks/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from south.utils import datetime_utils as datetime 3 | from south.db import db 4 | from south.v2 import SchemaMigration 5 | from django.db import models 6 | 7 | 8 | class Migration(SchemaMigration): 9 | 10 | def forwards(self, orm): 11 | # Adding model 'WebhookTarget' 12 | db.create_table('djwebhooks_webhooktarget', ( 13 | ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), 14 | ('created', self.gf('model_utils.fields.AutoCreatedField')(default=datetime.datetime.now)), 15 | ('modified', self.gf('model_utils.fields.AutoLastModifiedField')(default=datetime.datetime.now)), 16 | ('owner', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['users.User'], related_name='webhooks')), 17 | ('event', self.gf('django.db.models.fields.CharField')(max_length=255)), 18 | ('identifier', self.gf('django.db.models.fields.CharField')(blank=True, max_length=255)), 19 | ('target_url', self.gf('django.db.models.fields.URLField')(max_length=255)), 20 | ('header_content_type', self.gf('django.db.models.fields.CharField')(default='application/json', max_length=255)), 21 | )) 22 | db.send_create_signal('djwebhooks', ['WebhookTarget']) 23 | 24 | # Adding model 'Delivery' 25 | db.create_table('djwebhooks_delivery', ( 26 | ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), 27 | ('created', self.gf('model_utils.fields.AutoCreatedField')(default=datetime.datetime.now)), 28 | ('modified', self.gf('model_utils.fields.AutoLastModifiedField')(default=datetime.datetime.now)), 29 | ('webhook_target', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['djwebhooks.WebhookTarget'])), 30 | ('payload', self.gf('jsonfield.fields.JSONField')(default={})), 31 | ('success', self.gf('django.db.models.fields.BooleanField')(default=False)), 32 | ('attempt', self.gf('django.db.models.fields.IntegerField')()), 33 | ('hash_value', self.gf('django.db.models.fields.CharField')(blank=True, max_length=255)), 34 | ('notification', self.gf('django.db.models.fields.TextField')(blank=True)), 35 | ('response_message', self.gf('django.db.models.fields.TextField')(blank=True)), 36 | ('response_status', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)), 37 | ('response_content_type', self.gf('django.db.models.fields.CharField')(blank=True, max_length=255)), 38 | )) 39 | db.send_create_signal('djwebhooks', ['Delivery']) 40 | 41 | 42 | def backwards(self, orm): 43 | # Deleting model 'WebhookTarget' 44 | db.delete_table('djwebhooks_webhooktarget') 45 | 46 | # Deleting model 'Delivery' 47 | db.delete_table('djwebhooks_delivery') 48 | 49 | 50 | models = { 51 | 'auth.group': { 52 | 'Meta': {'object_name': 'Group'}, 53 | 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 54 | 'name': ('django.db.models.fields.CharField', [], {'max_length': '80', 'unique': 'True'}), 55 | 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True', 'symmetrical': 'False'}) 56 | }, 57 | 'auth.permission': { 58 | 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'object_name': 'Permission'}, 59 | 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 60 | 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 61 | 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 62 | 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) 63 | }, 64 | 'contenttypes.contenttype': { 65 | 'Meta': {'db_table': "'django_content_type'", 'unique_together': "(('app_label', 'model'),)", 'ordering': "('name',)", 'object_name': 'ContentType'}, 66 | 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 67 | 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 68 | 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 69 | 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) 70 | }, 71 | 'djwebhooks.delivery': { 72 | 'Meta': {'ordering': "['-created']", 'object_name': 'Delivery'}, 73 | 'attempt': ('django.db.models.fields.IntegerField', [], {}), 74 | 'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}), 75 | 'hash_value': ('django.db.models.fields.CharField', [], {'blank': 'True', 'max_length': '255'}), 76 | 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 77 | 'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}), 78 | 'notification': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 79 | 'payload': ('jsonfield.fields.JSONField', [], {'default': '{}'}), 80 | 'response_content_type': ('django.db.models.fields.CharField', [], {'blank': 'True', 'max_length': '255'}), 81 | 'response_message': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 82 | 'response_status': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 83 | 'success': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 84 | 'webhook_target': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['djwebhooks.WebhookTarget']"}) 85 | }, 86 | 'djwebhooks.webhooktarget': { 87 | 'Meta': {'ordering': "['-modified']", 'object_name': 'WebhookTarget'}, 88 | 'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}), 89 | 'event': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 90 | 'header_content_type': ('django.db.models.fields.CharField', [], {'default': "'application/json'", 'max_length': '255'}), 91 | 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 92 | 'identifier': ('django.db.models.fields.CharField', [], {'blank': 'True', 'max_length': '255'}), 93 | 'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}), 94 | 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.User']", 'related_name': "'webhooks'"}), 95 | 'target_url': ('django.db.models.fields.URLField', [], {'max_length': '255'}) 96 | }, 97 | 'users.user': { 98 | 'Meta': {'object_name': 'User'}, 99 | 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 100 | 'email': ('django.db.models.fields.EmailField', [], {'blank': 'True', 'max_length': '75'}), 101 | 'first_name': ('django.db.models.fields.CharField', [], {'blank': 'True', 'max_length': '30'}), 102 | 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True', 'related_name': "'user_set'"}), 103 | 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 104 | 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 105 | 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 106 | 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 107 | 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 108 | 'last_name': ('django.db.models.fields.CharField', [], {'blank': 'True', 'max_length': '30'}), 109 | 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 110 | 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True', 'related_name': "'user_set'"}), 111 | 'username': ('django.db.models.fields.CharField', [], {'max_length': '30', 'unique': 'True'}) 112 | } 113 | } 114 | 115 | complete_apps = ['djwebhooks'] -------------------------------------------------------------------------------- /djwebhooks/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pydanny/dj-webhooks/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/migrations/__init__.py -------------------------------------------------------------------------------- /djwebhooks/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from django.conf import settings 3 | from django.core.exceptions import ImproperlyConfigured 4 | from django.db import models 5 | from django.utils.encoding import python_2_unicode_compatible 6 | 7 | from jsonfield.fields import JSONField 8 | from model_utils.models import TimeStampedModel 9 | from multiselectfield import MultiSelectField 10 | 11 | 12 | CONTENT_TYPE_JSON = "application/json" 13 | CONTENT_TYPE_FORM = "application/x-www-form-urlencoded" 14 | 15 | 16 | def event_choices(events): 17 | """ Get the possible events from settings """ 18 | if events is None: 19 | msg = "Please add some events in settings.WEBHOOK_EVENTS." 20 | raise ImproperlyConfigured(msg) 21 | try: 22 | choices = [(x, x) for x in events] 23 | except TypeError: 24 | """ Not a valid iterator, so we raise an exception """ 25 | msg = "settings.WEBHOOK_EVENTS must be an iterable object." 26 | raise ImproperlyConfigured(msg) 27 | return choices 28 | 29 | WEBHOOK_EVENTS = getattr(settings, "WEBHOOK_EVENTS", None) 30 | WEBHOOK_EVENTS_CHOICES = event_choices(WEBHOOK_EVENTS) 31 | 32 | 33 | class EventableModel(models.Model): 34 | """Helps compose a model that connects to the WebhookTarget model""" 35 | events = MultiSelectField(choices=WEBHOOK_EVENTS_CHOICES, max_length=255) 36 | 37 | class Meta: 38 | abstract = True 39 | 40 | 41 | @python_2_unicode_compatible 42 | class WebhookTarget(TimeStampedModel): 43 | """ I would prefer the name 'target', but I worry it's confusing. 44 | 45 | TODO - make owner/event unique_together 46 | """ 47 | 48 | CONTENT_TYPE_JSON = CONTENT_TYPE_JSON 49 | CONTENT_TYPE_FORM = CONTENT_TYPE_FORM 50 | CONTENT_TYPE_CHOICES = ( 51 | (CONTENT_TYPE_JSON, CONTENT_TYPE_JSON), 52 | (CONTENT_TYPE_FORM, CONTENT_TYPE_FORM) 53 | ) 54 | 55 | WEBHOOK_EVENTS = WEBHOOK_EVENTS_CHOICES 56 | 57 | # TODO - add Webhook event choices as indivial attributes to this model, instantiated or not 58 | 59 | # represents the user who is responsible for this WT 60 | owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='webhooks') 61 | 62 | # The event name as set in WEBHOOK_EVENTS 63 | event = models.CharField(max_length=255, choices=WEBHOOK_EVENTS_CHOICES) 64 | 65 | # The custom identifier for this webhook as set by the project or the owner 66 | identifier = models.SlugField(max_length=255, blank=True) 67 | 68 | target_url = models.URLField(max_length=255) 69 | 70 | header_content_type = models.CharField("Header content-type", 71 | max_length=255, choices=CONTENT_TYPE_CHOICES, default=CONTENT_TYPE_JSON) 72 | 73 | def __str__(self): 74 | return "{}:{}:{}".format( 75 | self.event, 76 | self.target_url[:30], 77 | self.identifier 78 | ) 79 | 80 | class Meta: 81 | ordering = ["-modified"] 82 | get_latest_by = "modified" 83 | 84 | 85 | # Possibly replace with redis or something else better for writes 86 | @python_2_unicode_compatible 87 | class Delivery(TimeStampedModel): 88 | 89 | webhook_target = models.ForeignKey(WebhookTarget) 90 | 91 | payload = JSONField() 92 | 93 | success = models.BooleanField(default=False) 94 | attempt = models.IntegerField("How many times has this been attempted to be delivered") 95 | hash_value = models.CharField(max_length=255, blank=True) 96 | 97 | notification = models.TextField("Passed back from the Senderable object", blank=True) 98 | 99 | # response info 100 | response_message = models.TextField("Whatever is sent back", blank=True) 101 | response_status = models.IntegerField("HTTP status code", blank=True, null=True) 102 | response_content_type = models.CharField(max_length=255, blank=True) 103 | 104 | # TODO - add rest of recorded header infos 105 | 106 | def __str__(self): 107 | return "{}=>{}=>{}".format( 108 | self.success, 109 | self.created, 110 | self.webhook_target 111 | ) 112 | 113 | class Meta: 114 | ordering = ["-created"] 115 | get_latest_by = "created" 116 | verbose_name = 'Delivery' 117 | verbose_name_plural = 'Deliveries' 118 | -------------------------------------------------------------------------------- /djwebhooks/senders/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .orm import orm_callable 4 | from .redislog import redislog_hook 5 | from .redisq import redisq_callable -------------------------------------------------------------------------------- /djwebhooks/senders/orm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """djwebhooks.senders.orm.sender 3 | Decorator for 'hooking' a payload request to a foreign URL using 4 | `djwebhooks.senders.orm.sender`. A payload request is generated by the hooked 5 | function, which must return a JSON-serialized value. 6 | 7 | Note: Thanks to json232, the JSON-serialized data can include DateTime objects. 8 | 9 | :event: The name of the event as defined in settings.WEBHOOK_EVENTS 10 | :owner: Required for the payload function. This represents the user who 11 | created or manages the event. Is not normally request.user. 12 | 13 | Decorator Usage: 14 | 15 | # Define the payload function! 16 | @hook(event="order.ship") 17 | def order_ship(order, owner): 18 | return { 19 | "order_num": order.order_num, 20 | "shipping_address": order.shipping_address, 21 | "line_items": [x.sku for x in order.lineitem_set.all()] 22 | } 23 | 24 | # Call the payload function! 25 | def order_confirmation(request, order_num): 26 | order = get_object_or_404(Order, order_num=order_num) 27 | if order.is_valid(): 28 | order_ship(order=order, owner=order.merchant) 29 | 30 | return redirect("home") 31 | """ 32 | 33 | from django.conf import settings 34 | 35 | from webhooks.senders.base import Senderable 36 | 37 | from ..models import WebhookTarget, Delivery 38 | 39 | # For use with custom user models, this lets you define the owner field on a model 40 | WEBHOOK_OWNER_FIELD = getattr(settings, "WEBHOOK_OWNER_FIELD", "username") 41 | 42 | # List the attempts as an iterable of integers. 43 | # Each number represents the amount of time to be slept between attempts 44 | # The first number should always be 0 so no time is wasted. 45 | WEBHOOK_ATTEMPTS = getattr(settings, "WEBHOOK_EVENTS", (0, 15, 30, 60)) 46 | 47 | 48 | class DjangoSenderable(Senderable): 49 | 50 | def notify(self, message): 51 | if self.success: 52 | Delivery.objects.create( 53 | webhook_target=self.webhook_target, 54 | payload=self.payload, 55 | attempt=self.attempt, 56 | success=self.success, 57 | response_message=self.response_content, 58 | hash_value=self.hash_value, 59 | response_status=self.response.status_code, 60 | notification=message 61 | ) 62 | else: 63 | Delivery.objects.create( 64 | webhook_target=self.webhook_target, 65 | payload=self.payload, 66 | attempt=self.attempt, 67 | success=self.success, 68 | hash_value=self.hash_value, 69 | notification=message 70 | ) 71 | 72 | 73 | def orm_callable(wrapped, dkwargs, hash_value=None, *args, **kwargs): 74 | """ 75 | This is a synchronous sender callable that uses the Django ORM to store 76 | webhooks and the delivery log. Meant as proof of concept and not 77 | as something for heavy production sites. 78 | 79 | dkwargs argument requires the following key/values: 80 | 81 | :event: A string representing an event. 82 | 83 | kwargs argument requires the following key/values 84 | 85 | :owner: The user who created/owns the event 86 | """ 87 | 88 | if "event" not in dkwargs: 89 | msg = "djwebhooks.decorators.hook requires an 'event' argument in the decorator." 90 | raise TypeError(msg) 91 | event = dkwargs['event'] 92 | 93 | if "owner" not in kwargs: 94 | msg = "djwebhooks.senders.orm_callable requires an 'owner' argument in the decorated function." 95 | raise TypeError(msg) 96 | owner = kwargs['owner'] 97 | 98 | if "identifier" not in kwargs: 99 | msg = "djwebhooks.senders.orm_callable requires an 'identifier' argument in the decorated function." 100 | raise TypeError(msg) 101 | identifier = kwargs['identifier'] 102 | 103 | senderobj = DjangoSenderable( 104 | wrapped, dkwargs, hash_value, WEBHOOK_ATTEMPTS, *args, **kwargs 105 | ) 106 | 107 | # Add the webhook object just so it's around 108 | # TODO - error handling if this can't be found 109 | try: 110 | senderobj.webhook_target = WebhookTarget.objects.get( 111 | event=event, 112 | owner=owner, 113 | identifier=identifier 114 | ) 115 | except WebhookTarget.DoesNotExist: 116 | return {"error": "WebhookTarget not found"} 117 | 118 | # Get the target url and add it 119 | senderobj.url = senderobj.webhook_target.target_url 120 | 121 | # Get the payload. This overides the senderobj.payload property. 122 | senderobj.payload = senderobj.get_payload() 123 | 124 | # Get the creator and add it to the payload. 125 | senderobj.payload['owner'] = getattr(kwargs['owner'], WEBHOOK_OWNER_FIELD) 126 | 127 | # get the event and add it to the payload 128 | senderobj.payload['event'] = dkwargs['event'] 129 | 130 | return senderobj.send() 131 | -------------------------------------------------------------------------------- /djwebhooks/senders/redislog.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from functools import partial 3 | import json 4 | 5 | from django.conf import settings 6 | from django.utils import timezone 7 | 8 | from redis import StrictRedis 9 | 10 | from webhooks.decorators import base_hook 11 | from webhooks.hashes import basic_hash_function 12 | from webhooks.senders.base import Senderable, StandardJSONEncoder 13 | 14 | 15 | from ..models import WebhookTarget 16 | 17 | # For use with custom user models, this lets you define the owner field on a model 18 | WEBHOOK_OWNER_FIELD = getattr(settings, "WEBHOOK_OWNER_FIELD", "username") 19 | 20 | # List the attempts as an iterable of integers. 21 | # Each number represents the amount of time to be slept between attempts 22 | # The first number should always be 0 so no time is wasted. 23 | WEBHOOK_ATTEMPTS = getattr(settings, "WEBHOOK_EVENTS", (0, 15, 30, 60)) 24 | 25 | 26 | # Set up redis coonection 27 | # TODO - Use other Django redis-package settings names 28 | redis = StrictRedis( 29 | host=getattr(settings, "REDIS_HOST", 'localhost'), 30 | port=getattr(settings, "REDIS_PORT", 6379), 31 | db=getattr(settings, "REDIS_DB", 0)) 32 | 33 | 34 | def make_key(event, owner_name, identifier): 35 | return "{}:{}:{}".format(event, owner_name, identifier) 36 | 37 | 38 | class RedisLogSenderable(Senderable): 39 | 40 | def __init__(self, wrapped, dkwargs, hash_value, attempts, *args, **kwargs): 41 | """ 42 | :wrapped: Function that has been wrapped and whose payload is being sent 43 | """ 44 | 45 | self.event = dkwargs['event'] 46 | self.owner = kwargs['owner'] 47 | self.identifier = kwargs['identifier'] 48 | super(RedisLogSenderable, self).__init__(wrapped, dkwargs, hash_value, attempts, *args, **kwargs) 49 | 50 | def notify(self, message): 51 | """ 52 | TODO: Add code to lpush to redis stack 53 | rpop when stack hits size 'X' 54 | """ 55 | data = dict( 56 | payload=self.payload, 57 | attempt=self.attempt, 58 | success=self.success, 59 | response_message=self.response_content, 60 | hash_value=self.hash_value, 61 | response_status=self.response.status_code, 62 | notification=message, 63 | created=timezone.now() 64 | ) 65 | value = json.dumps(data, cls=StandardJSONEncoder) 66 | key = make_key(self.event, self.owner.username, self.identifier) 67 | redis.lpush(key, value) 68 | 69 | 70 | def redislog_callable(wrapped, dkwargs, hash_value=None, *args, **kwargs): 71 | """ 72 | This is a synchronous sender callable that uses the Django ORM to store 73 | webhooks and Redis for the delivery log. 74 | 75 | dkwargs argument requires the following key/values: 76 | 77 | :event: A string representing an event. 78 | 79 | kwargs argument requires the following key/values 80 | 81 | :owner: The user who created/owns the event 82 | """ 83 | 84 | if "event" not in dkwargs: 85 | msg = "djwebhooks.decorators.hook requires an 'event' argument in the decorator." 86 | raise TypeError(msg) 87 | event = dkwargs['event'] 88 | 89 | if "owner" not in kwargs: 90 | msg = "djwebhooks.senders.redislog_callable requires an 'owner' argument in the decorated function." 91 | raise TypeError(msg) 92 | owner = kwargs['owner'] 93 | 94 | if "identifier" not in kwargs: 95 | msg = "djwebhooks.senders.redislog_callable requires an 'identifier' argument in the decorated function." 96 | raise TypeError(msg) 97 | identifier = kwargs['identifier'] 98 | 99 | senderobj = RedisLogSenderable( 100 | wrapped, dkwargs, hash_value, WEBHOOK_ATTEMPTS, *args, **kwargs 101 | ) 102 | 103 | # Add the webhook object just so it's around 104 | # TODO - error handling if this can't be found 105 | try: 106 | senderobj.webhook_target = WebhookTarget.objects.get( 107 | event=event, 108 | owner=owner, 109 | identifier=identifier 110 | ) 111 | except WebhookTarget.DoesNotExist: 112 | return {"error": "WebhookTarget not found"} 113 | 114 | # Get the target url and add it 115 | senderobj.url = senderobj.webhook_target.target_url 116 | 117 | # Get the payload. This overides the senderobj.payload property. 118 | senderobj.payload = senderobj.get_payload() 119 | 120 | # Get the creator and add it to the payload. 121 | senderobj.payload['owner'] = getattr(kwargs['owner'], WEBHOOK_OWNER_FIELD) 122 | 123 | # get the event and add it to the payload 124 | senderobj.payload['event'] = dkwargs['event'] 125 | 126 | return senderobj.send() 127 | 128 | 129 | # Make the redis log hook work 130 | # This is decorator that does all the lifting. 131 | redislog_hook = partial( 132 | base_hook, 133 | sender_callable=redislog_callable, 134 | hash_function=basic_hash_function 135 | ) 136 | 137 | redislog_hook.func.__doc__ = """ 138 | Decorator for 'hooking' a payload request to a foreign URL using 139 | `djwebhooks.senders.orm.sender`. A payload request is generated by the hooked 140 | function, which must return a JSON-serialized value. 141 | 142 | Note: Thanks to standard, the JSON-serialized data can include DateTime objects. 143 | 144 | :event: The name of the event as defined in settings.WEBHOOK_EVENTS 145 | :owner: Required for the payload function. This represents the user who 146 | created or manages the event. Is not normally request.user. 147 | 148 | Decorator Usage: 149 | 150 | # Define the payload function! 151 | @redislog_hook(event="order.ship") 152 | def order_ship(order, owner): 153 | return { 154 | "order_num": order.order_num, 155 | "shipping_address": order.shipping_address, 156 | "line_items": [x.sku for x in order.lineitem_set.all()] 157 | } 158 | 159 | # Call the payload function! 160 | def order_confirmation(request, order_num): 161 | order = get_object_or_404(Order, order_num=order_num) 162 | if order.is_valid(): 163 | order_ship(order=order, owner=order.merchant) 164 | 165 | return redirect("home") 166 | """ 167 | -------------------------------------------------------------------------------- /djwebhooks/senders/redisq.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import logging 3 | 4 | from django.conf import settings 5 | 6 | from django_rq import job 7 | from webhooks.senders.base import Senderable 8 | 9 | from ..models import WebhookTarget 10 | 11 | # For use with custom user models, this lets you define the owner field on a model 12 | WEBHOOK_OWNER_FIELD = getattr(settings, "WEBHOOK_OWNER_FIELD", "username") 13 | 14 | # List the attempts as an iterable of integers. 15 | # Each number represents the amount of time to be slept between attempts 16 | # The first number should always be 0 so no time is wasted. 17 | WEBHOOK_ATTEMPTS = getattr(settings, "WEBHOOK_EVENTS", (0, 15, 30, 60)) 18 | 19 | logger = logging.getLogger(__name__) 20 | 21 | 22 | class DjangoRQSenderable(Senderable): 23 | 24 | def notify(self, message): 25 | logger.info(message) 26 | 27 | 28 | @job 29 | def worker(wrapped, dkwargs, hash_value=None, *args, **kwargs): 30 | """ 31 | This is an asynchronous sender callable that uses the Django ORM to store 32 | webhooks. Redis is used to handle the message queue. 33 | 34 | dkwargs argument requires the following key/values: 35 | 36 | :event: A string representing an event. 37 | 38 | kwargs argument requires the following key/values 39 | 40 | :owner: The user who created/owns the event 41 | """ 42 | 43 | if "event" not in dkwargs: 44 | msg = "djwebhooks.decorators.redis_hook requires an 'event' argument in the decorator." 45 | raise TypeError(msg) 46 | event = dkwargs['event'] 47 | 48 | if "owner" not in kwargs: 49 | msg = "djwebhooks.senders.redis_callable requires an 'owner' argument in the decorated function." 50 | raise TypeError(msg) 51 | owner = kwargs['owner'] 52 | 53 | if "identifier" not in kwargs: 54 | msg = "djwebhooks.senders.orm_callable requires an 'identifier' argument in the decorated function." 55 | raise TypeError(msg) 56 | identifier = kwargs['identifier'] 57 | 58 | senderobj = DjangoRQSenderable( 59 | wrapped, dkwargs, hash_value, WEBHOOK_ATTEMPTS, *args, **kwargs 60 | ) 61 | 62 | # Add the webhook object just so it's around 63 | # TODO - error handling if this can't be found 64 | senderobj.webhook_target = WebhookTarget.objects.get( 65 | event=event, 66 | owner=owner, 67 | identifier=identifier 68 | ) 69 | 70 | # Get the target url and add it 71 | senderobj.url = senderobj.webhook_target.target_url 72 | 73 | # Get the payload. This overides the senderobj.payload property. 74 | senderobj.payload = senderobj.get_payload() 75 | 76 | # Get the creator and add it to the payload. 77 | senderobj.payload['owner'] = getattr(kwargs['owner'], WEBHOOK_OWNER_FIELD) 78 | 79 | # get the event and add it to the payload 80 | senderobj.payload['event'] = dkwargs['event'] 81 | 82 | return senderobj.send() 83 | 84 | 85 | def redisq_callable(wrapped, dkwargs, hash_value=None, *args, **kwargs): 86 | logger.debug("Starting async") 87 | job = worker(wrapped, dkwargs, hash_value, *args, **kwargs) 88 | logger.debug("Ending async") 89 | return job 90 | -------------------------------------------------------------------------------- /djwebhooks/static/css/djwebhooks.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pydanny/dj-webhooks/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/static/css/djwebhooks.css -------------------------------------------------------------------------------- /djwebhooks/static/img/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pydanny/dj-webhooks/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/static/img/.gitignore -------------------------------------------------------------------------------- /djwebhooks/static/js/djwebhooks.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pydanny/dj-webhooks/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/static/js/djwebhooks.js -------------------------------------------------------------------------------- /djwebhooks/templates/djwebhooks/base.html: -------------------------------------------------------------------------------- 1 | 2 | {% comment %} 3 | As the developer of this package, don't place anything here if you can help it 4 | since this allows developers to have interoperability between your template 5 | structure and their own. 6 | 7 | Example: Developer melding the 2SoD pattern to fit inside with another pattern:: 8 | 9 | {% extends "base.html" %} 10 | {% load static %} 11 | 12 | 13 | {% block extra_js %} 14 | 15 | 16 | {% block javascript %} 17 | 18 | {% endblock javascript %} 19 | 20 | {% endblock extra_js %} 21 | {% endcomment %} 22 | -------------------------------------------------------------------------------- /djwebhooks/utils.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def always_string(value): 5 | """Regardless of the Python version, this always returns a string """ 6 | if sys.version > '3': 7 | return value.decode('utf-8') 8 | return value -------------------------------------------------------------------------------- /djwebhooks/views.py: -------------------------------------------------------------------------------- 1 | """ 2 | This are sample views which probably will not match your use case. 3 | """ 4 | 5 | from django.conf import settings 6 | from django.http import Http404 7 | from django.shortcuts import get_object_or_404 8 | from django.utils.functional import cached_property 9 | from django.views.generic import DetailView 10 | 11 | from redis import StrictRedis 12 | 13 | from .models import Delivery, WebhookTarget 14 | from .senders.redislog import make_key 15 | 16 | # Set up redis coonection 17 | # TODO - Use other Django redis-package settings names 18 | redis = StrictRedis( 19 | host=getattr(settings, "REDIS_HOST", 'localhost'), 20 | port=getattr(settings, "REDIS_PORT", 6379), 21 | db=getattr(settings, "REDIS_DB", 0)) 22 | 23 | 24 | class WebhookTargetDetailView(DetailView): 25 | 26 | max_deliveries_listed = 20 27 | 28 | @property 29 | def webhoot_target(self): 30 | return self.object 31 | 32 | @cached_property 33 | def object(self): 34 | return self.get_object() 35 | 36 | def get_object(self): 37 | if 'pk' in self.kwargs: 38 | return get_object_or_404( 39 | WebhookTarget, 40 | pk=self.kwargs['pk'] 41 | ) 42 | if 'identifier' in self.kwargs: 43 | return get_object_or_404( 44 | WebhookTarget, 45 | pk=self.kwargs['identifier'] 46 | ) 47 | raise Http404 48 | 49 | @cached_property 50 | def deliveries(self): 51 | return Delivery.objects.filter( 52 | webhoot_target=self.webhook_target 53 | )[:self.max_deliveries_listed] 54 | 55 | 56 | class ProtectedWebhookTargetDetailView(WebhookTargetDetailView): 57 | 58 | def get_object(self): 59 | if 'pk' in self.kwargs: 60 | return get_object_or_404( 61 | WebhookTarget, 62 | pk=self.kwargs['pk'], 63 | owner=self.request.user 64 | 65 | ) 66 | if 'identifier' in self.kwargs: 67 | return get_object_or_404( 68 | WebhookTarget, 69 | pk=self.kwargs['identifier'], 70 | owner=self.request.user 71 | ) 72 | raise Http404 73 | 74 | 75 | class WebhookTargetRedisDetailView(WebhookTargetDetailView): 76 | 77 | @cached_property 78 | def deliveries(self): 79 | """ Get delivery log from Redis""" 80 | key = make_key( 81 | event=self.object.event, 82 | owner_name=self.object.owner.username, 83 | identifier=self.object.identifier 84 | ) 85 | return redis.lrange(key, 0, 20) 86 | 87 | 88 | class ProtectedWebhookTargetRedisDetailView(WebhookTargetRedisDetailView): 89 | 90 | def get_object(self): 91 | if 'pk' in self.kwargs: 92 | return get_object_or_404( 93 | WebhookTarget, 94 | pk=self.kwargs['pk'], 95 | owner=self.request.user 96 | 97 | ) 98 | if 'identifier' in self.kwargs: 99 | return get_object_or_404( 100 | WebhookTarget, 101 | pk=self.kwargs['identifier'], 102 | owner=self.request.user 103 | ) 104 | raise Http404 105 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/complexity.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/complexity.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/complexity" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/complexity" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # complexity documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | #sys.path.insert(0, os.path.abspath('.')) 20 | 21 | cwd = os.getcwd() 22 | parent = os.path.dirname(cwd) 23 | sys.path.append(parent) 24 | 25 | import djwebhooks 26 | 27 | # -- General configuration ----------------------------------------------------- 28 | 29 | # If your documentation needs a minimal Sphinx version, state it here. 30 | #needs_sphinx = '1.0' 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be extensions 33 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 35 | 36 | # Add any paths that contain templates here, relative to this directory. 37 | templates_path = ['_templates'] 38 | 39 | # The suffix of source filenames. 40 | source_suffix = '.rst' 41 | 42 | # The encoding of source files. 43 | #source_encoding = 'utf-8-sig' 44 | 45 | # The master toctree document. 46 | master_doc = 'index' 47 | 48 | # General information about the project. 49 | project = u'dj-webhooks' 50 | copyright = u'2014, Daniel Greenfeld' 51 | 52 | # The version info for the project you're documenting, acts as replacement for 53 | # |version| and |release|, also used in various other places throughout the 54 | # built documents. 55 | # 56 | # The short X.Y version. 57 | version = djwebhooks.__version__ 58 | # The full version, including alpha/beta/rc tags. 59 | release = djwebhooks.__version__ 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | #language = None 64 | 65 | # There are two options for replacing |today|: either, you set today to some 66 | # non-false value, then it is used: 67 | #today = '' 68 | # Else, today_fmt is used as the format for a strftime call. 69 | #today_fmt = '%B %d, %Y' 70 | 71 | # List of patterns, relative to source directory, that match files and 72 | # directories to ignore when looking for source files. 73 | exclude_patterns = ['_build'] 74 | 75 | # The reST default role (used for this markup: `text`) to use for all documents. 76 | #default_role = None 77 | 78 | # If true, '()' will be appended to :func: etc. cross-reference text. 79 | #add_function_parentheses = True 80 | 81 | # If true, the current module name will be prepended to all description 82 | # unit titles (such as .. function::). 83 | #add_module_names = True 84 | 85 | # If true, sectionauthor and moduleauthor directives will be shown in the 86 | # output. They are ignored by default. 87 | #show_authors = False 88 | 89 | # The name of the Pygments (syntax highlighting) style to use. 90 | pygments_style = 'sphinx' 91 | 92 | # A list of ignored prefixes for module index sorting. 93 | #modindex_common_prefix = [] 94 | 95 | # If true, keep warnings as "system message" paragraphs in the built documents. 96 | #keep_warnings = False 97 | 98 | 99 | # -- Options for HTML output --------------------------------------------------- 100 | 101 | # The theme to use for HTML and HTML Help pages. See the documentation for 102 | # a list of builtin themes. 103 | html_theme = 'default' 104 | 105 | # Theme options are theme-specific and customize the look and feel of a theme 106 | # further. For a list of options available for each theme, see the 107 | # documentation. 108 | #html_theme_options = {} 109 | 110 | # Add any paths that contain custom themes here, relative to this directory. 111 | #html_theme_path = [] 112 | 113 | # The name for this set of Sphinx documents. If None, it defaults to 114 | # " v documentation". 115 | #html_title = None 116 | 117 | # A shorter title for the navigation bar. Default is the same as html_title. 118 | #html_short_title = None 119 | 120 | # The name of an image file (relative to this directory) to place at the top 121 | # of the sidebar. 122 | #html_logo = None 123 | 124 | # The name of an image file (within the static path) to use as favicon of the 125 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 126 | # pixels large. 127 | #html_favicon = None 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | html_static_path = ['_static'] 133 | 134 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 135 | # using the given strftime format. 136 | #html_last_updated_fmt = '%b %d, %Y' 137 | 138 | # If true, SmartyPants will be used to convert quotes and dashes to 139 | # typographically correct entities. 140 | #html_use_smartypants = True 141 | 142 | # Custom sidebar templates, maps document names to template names. 143 | #html_sidebars = {} 144 | 145 | # Additional templates that should be rendered to pages, maps page names to 146 | # template names. 147 | #html_additional_pages = {} 148 | 149 | # If false, no module index is generated. 150 | #html_domain_indices = True 151 | 152 | # If false, no index is generated. 153 | #html_use_index = True 154 | 155 | # If true, the index is split into individual pages for each letter. 156 | #html_split_index = False 157 | 158 | # If true, links to the reST sources are added to the pages. 159 | #html_show_sourcelink = True 160 | 161 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 162 | #html_show_sphinx = True 163 | 164 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 165 | #html_show_copyright = True 166 | 167 | # If true, an OpenSearch description file will be output, and all pages will 168 | # contain a tag referring to it. The value of this option must be the 169 | # base URL from which the finished HTML is served. 170 | #html_use_opensearch = '' 171 | 172 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 173 | #html_file_suffix = None 174 | 175 | # Output file base name for HTML help builder. 176 | htmlhelp_basename = 'dj-webhooksdoc' 177 | 178 | 179 | # -- Options for LaTeX output -------------------------------------------------- 180 | 181 | latex_elements = { 182 | # The paper size ('letterpaper' or 'a4paper'). 183 | #'papersize': 'letterpaper', 184 | 185 | # The font size ('10pt', '11pt' or '12pt'). 186 | #'pointsize': '10pt', 187 | 188 | # Additional stuff for the LaTeX preamble. 189 | #'preamble': '', 190 | } 191 | 192 | # Grouping the document tree into LaTeX files. List of tuples 193 | # (source start file, target name, title, author, documentclass [howto/manual]). 194 | latex_documents = [ 195 | ('index', 'dj-webhooks.tex', u'dj-webhooks Documentation', 196 | u'Daniel Greenfeld', 'manual'), 197 | ] 198 | 199 | # The name of an image file (relative to this directory) to place at the top of 200 | # the title page. 201 | #latex_logo = None 202 | 203 | # For "manual" documents, if this is true, then toplevel headings are parts, 204 | # not chapters. 205 | #latex_use_parts = False 206 | 207 | # If true, show page references after internal links. 208 | #latex_show_pagerefs = False 209 | 210 | # If true, show URL addresses after external links. 211 | #latex_show_urls = False 212 | 213 | # Documents to append as an appendix to all manuals. 214 | #latex_appendices = [] 215 | 216 | # If false, no module index is generated. 217 | #latex_domain_indices = True 218 | 219 | 220 | # -- Options for manual page output -------------------------------------------- 221 | 222 | # One entry per manual page. List of tuples 223 | # (source start file, name, description, authors, manual section). 224 | man_pages = [ 225 | ('index', 'dj-webhooks', u'dj-webhooks Documentation', 226 | [u'Daniel Greenfeld'], 1) 227 | ] 228 | 229 | # If true, show URL addresses after external links. 230 | #man_show_urls = False 231 | 232 | 233 | # -- Options for Texinfo output ------------------------------------------------ 234 | 235 | # Grouping the document tree into Texinfo files. List of tuples 236 | # (source start file, target name, title, author, 237 | # dir menu entry, description, category) 238 | texinfo_documents = [ 239 | ('index', 'dj-webhooks', u'dj-webhooks Documentation', 240 | u'Daniel Greenfeld', 'dj-webhooks', 'One line description of project.', 241 | 'Miscellaneous'), 242 | ] 243 | 244 | # Documents to append as an appendix to all manuals. 245 | #texinfo_appendices = [] 246 | 247 | # If false, no module index is generated. 248 | #texinfo_domain_indices = True 249 | 250 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 251 | #texinfo_show_urls = 'footnote' 252 | 253 | # If true, do not generate a @detailmenu in the "Top" node's menu. 254 | #texinfo_no_detailmenu = False -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. complexity documentation master file, created by 2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to dj-webhooks's documentation! 7 | ================================================================= 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | readme 15 | installation 16 | usage 17 | contributing 18 | authors 19 | history -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | ============ 2 | Installation 3 | ============ 4 | 5 | At the command line:: 6 | 7 | $ easy_install dj-webhooks 8 | 9 | Or, if you have virtualenvwrapper installed:: 10 | 11 | $ mkvirtualenv dj-webhooks 12 | $ pip install dj-webhooks -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\complexity.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\complexity.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | ======== 2 | Usage 3 | ======== 4 | 5 | To use dj-webhooks in a project:: 6 | 7 | import dj-webhooks -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | coverage 2 | django>=1.5.5 3 | django-jsonfield>=0.9.12 4 | django-model-utils>=2.0.2 5 | django-multiselectfield>=0.1.2 6 | django-rq>=0.6.1 7 | django-nose>=1.2 8 | flake8>=2.1.0 9 | mock>=1.0.1 10 | nose>=1.3.0 11 | standardjson 12 | tox>=1.7.0 13 | webhooks>=0.4.1 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | django>=1.5.5 2 | django-jsonfield>=0.9.12 3 | django-model-utils>=2.0.2 4 | django-multiselectfield>=0.1.2 5 | django-rq>=0.6.1 6 | standardjson 7 | webhooks>=0.4.1 8 | wheel>=0.23.0 -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | try: 4 | from django.conf import settings 5 | 6 | settings.configure( 7 | DEBUG=True, 8 | USE_TZ=True, 9 | DATABASES={ 10 | "default": { 11 | "ENGINE": "django.db.backends.sqlite3", 12 | } 13 | }, 14 | ROOT_URLCONF="djwebhooks.urls", 15 | INSTALLED_APPS=[ 16 | "django.contrib.auth", 17 | "django.contrib.contenttypes", 18 | "django.contrib.sites", 19 | "djwebhooks", 20 | ], 21 | SITE_ID=1, 22 | NOSE_ARGS=['-s'], 23 | WEBHOOK_ATTEMPTS=[0, 0, 0], 24 | WEBHOOK_EVENTS=['test.success', 'test.failure'], 25 | WEBHOOKS_SENDER="djwebhooks.senders.orm.sender", 26 | RQ_QUEUES={ 27 | 'default': { 28 | 'HOST': 'localhost', 29 | 'PORT': 6379, 30 | 'DB': 0, 31 | }, 32 | 'high': { 33 | 'HOST': 'localhost', 34 | 'PORT': 6379, 35 | 'DB': 0, 36 | }, 37 | 'low': { 38 | 'HOST': 'localhost', 39 | 'PORT': 6379, 40 | 'DB': 0, 41 | } 42 | } 43 | ) 44 | 45 | from django_nose import NoseTestSuiteRunner 46 | except ImportError: 47 | raise ImportError("To fix this error, run: pip install -r requirements-test.txt") 48 | 49 | 50 | def run_tests(*test_args): 51 | if not test_args: 52 | test_args = ['tests'] 53 | 54 | # Run tests 55 | test_runner = NoseTestSuiteRunner(verbosity=1) 56 | 57 | failures = test_runner.run_tests(test_args) 58 | 59 | if failures: 60 | sys.exit(failures) 61 | 62 | 63 | if __name__ == '__main__': 64 | run_tests(*sys.argv[1:]) 65 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [wheel] 2 | universal = 1 3 | 4 | [bdist_wheel] 5 | universal = 1 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | import sys 6 | 7 | import djwebhooks 8 | 9 | try: 10 | from setuptools import setup 11 | except ImportError: 12 | from distutils.core import setup 13 | 14 | version = djwebhooks.__version__ 15 | 16 | if sys.argv[-1] == 'publish': 17 | os.system('python setup.py sdist bdist_wheel upload') 18 | print("You probably want to also tag the version now:") 19 | print(" git tag -a %s -m 'version %s'" % (version, version)) 20 | print(" git push --tags") 21 | sys.exit() 22 | 23 | readme = open('README.rst').read() 24 | history = open('HISTORY.rst').read().replace('.. :changelog:', '') 25 | 26 | setup( 27 | name='dj-webhooks', 28 | version=version, 29 | description="""Django + Webhooks Made Easy""", 30 | long_description=readme + '\n\n' + history, 31 | author='Daniel Greenfeld', 32 | author_email='pydanny@gmail.com', 33 | url='https://github.com/pydanny/dj-webhooks', 34 | packages=[ 35 | 'djwebhooks', 36 | ], 37 | include_package_data=True, 38 | install_requires=[ 39 | "django>=1.5.5", 40 | "webhooks>=0.4.1", 41 | "django-jsonfield>=0.9.12", 42 | "django-model-utils>=2.0.2", 43 | "django-multiselectfield>=0.1.2", 44 | "standardjson", 45 | "django-rq>=0.6.1" 46 | ], 47 | license="BSD", 48 | zip_safe=False, 49 | keywords='dj-webhooks', 50 | classifiers=[ 51 | 'Development Status :: 3 - Alpha', 52 | 'Framework :: Django', 53 | 'Intended Audience :: Developers', 54 | 'License :: OSI Approved :: BSD License', 55 | 'Natural Language :: English', 56 | 'Programming Language :: Python :: 2.7', 57 | 'Programming Language :: Python :: 3.3', 58 | 'Programming Language :: Python :: 3.4', 59 | ], 60 | ) -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pydanny/dj-webhooks/88e245bfe2020e96279af261d88bf8469ba469e5/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_models.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | test_dj-webhooks 6 | ------------ 7 | 8 | Tests for `dj-webhooks` models module. 9 | """ 10 | 11 | from django.conf import settings 12 | from django.contrib.auth import get_user_model 13 | from django.core.exceptions import ImproperlyConfigured 14 | from django.test import TestCase 15 | 16 | from djwebhooks.models import WebhookTarget, Delivery, event_choices 17 | 18 | User = get_user_model() 19 | WEBHOOK_EVENTS = getattr(settings, "WEBHOOK_EVENTS", None) 20 | 21 | 22 | class TestWebhookTarget(TestCase): 23 | 24 | def setUp(self): 25 | self.user = User.objects.create_user( 26 | username="testuser", 27 | email="test@example.com", 28 | password="testpassword" 29 | ) 30 | 31 | def test_webhook_target(self): 32 | webhook = WebhookTarget.objects.create( 33 | owner=self.user, 34 | event=WEBHOOK_EVENTS[0], 35 | target_url="http://httpbin.com" 36 | ) 37 | self.assertEqual(WebhookTarget.objects.count(), 1) 38 | self.assertEqual(str(webhook), "testuser=>http://httpbin.com") 39 | 40 | 41 | class TestWebhookTarget(TestCase): 42 | 43 | def setUp(self): 44 | self.user = User.objects.create_user( 45 | username="testuser", 46 | email="test@example.com", 47 | password="testpassword" 48 | ) 49 | 50 | def test_delivery(self): 51 | webhook_target = WebhookTarget.objects.create( 52 | owner=self.user, 53 | event=WEBHOOK_EVENTS[0], 54 | target_url="http://httpbin.com" 55 | ) 56 | delivery = Delivery.objects.create( 57 | webhook_target=webhook_target, 58 | attempt=1, 59 | payload={}, 60 | ) 61 | self.assertTrue(str(delivery).startswith('False=>')) 62 | self.assertTrue(str(delivery).endswith("test.success:http://httpbin.com:")) 63 | 64 | 65 | class TestEventChoices(TestCase): 66 | 67 | def test_no_settings(self): 68 | self.assertRaises( 69 | ImproperlyConfigured, 70 | event_choices, 71 | None 72 | ) 73 | 74 | def test_bad_settings(self): 75 | self.assertRaises( 76 | ImproperlyConfigured, 77 | event_choices, 78 | 5 79 | ) 80 | -------------------------------------------------------------------------------- /tests/test_sender_orm.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.test import TestCase 3 | 4 | from django.contrib.auth import get_user_model 5 | 6 | from djwebhooks.decorators import webhook 7 | from djwebhooks.models import WebhookTarget, Delivery 8 | 9 | User = get_user_model() 10 | WEBHOOK_EVENTS = getattr(settings, "WEBHOOK_EVENTS", None) 11 | 12 | 13 | class BasicTest(TestCase): 14 | 15 | def setUp(self): 16 | self.user = User.objects.create_user( 17 | username="testuser", 18 | email="test@example.com", 19 | password="testpassword" 20 | ) 21 | 22 | self.identifier1 = 'afdasfjasd3485' 23 | self.identifier2 = 'vrefr9jqaw9efj' 24 | 25 | self.webook_target = WebhookTarget.objects.create( 26 | owner=self.user, 27 | event=WEBHOOK_EVENTS[0], 28 | identifier=self.identifier1, 29 | target_url="http://httpbin.org/post" 30 | ) 31 | self.fail_target = WebhookTarget.objects.create( 32 | owner=self.user, 33 | event=WEBHOOK_EVENTS[1], 34 | identifier=self.identifier2, 35 | target_url="http://httpbin.org/status/400" 36 | ) 37 | 38 | def test_webhook(self): 39 | 40 | @webhook(event=WEBHOOK_EVENTS[0]) 41 | def basic(owner, identifier): 42 | return {"what": "me worry?"} 43 | 44 | results = basic(owner=self.user, identifier=self.identifier1) 45 | 46 | self.assertEqual(results['what'], "me worry?") 47 | 48 | self.assertEqual(Delivery.objects.count(), 1) 49 | 50 | d = Delivery.objects.latest() 51 | 52 | self.assertEqual(d.success, True) 53 | 54 | def test_failed_webhook(self): 55 | 56 | @webhook(event=WEBHOOK_EVENTS[1]) 57 | def basic(owner, identifier): 58 | return {"what": "me worry?"} 59 | 60 | results = basic(owner=self.user, identifier=self.identifier2) 61 | 62 | self.assertEqual(results['what'], "me worry?") 63 | 64 | d = Delivery.objects.latest() 65 | 66 | self.assertEqual(d.success, False) 67 | 68 | def test_event_dkwarg(self): 69 | 70 | @webhook(number=123) 71 | def basic(owner, identifier): 72 | return {"what": "me worry?"} 73 | 74 | self.assertRaises(TypeError, basic, self.user) 75 | 76 | def test_owner_kwarg(self): 77 | 78 | @webhook(event=WEBHOOK_EVENTS[0]) 79 | def basic(): 80 | return {"what": "me worry?"} 81 | 82 | self.assertRaises(TypeError, basic) 83 | 84 | def test_identifier_kwarg(self): 85 | 86 | @webhook(event=WEBHOOK_EVENTS[0]) 87 | def basic(owner='pydanny'): 88 | return {"what": "me worry?"} 89 | 90 | with self.assertRaises(TypeError): 91 | basic(owner='danny') 92 | 93 | def test_cant_find_webhook_target(self): 94 | # TODO 95 | pass 96 | -------------------------------------------------------------------------------- /tests/test_sender_redis_log.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | 4 | from django.conf import settings 5 | from django.contrib.auth import get_user_model 6 | from django.test import TestCase 7 | 8 | from redis import StrictRedis 9 | 10 | from djwebhooks.decorators import redislog_hook 11 | from djwebhooks.models import WebhookTarget 12 | from djwebhooks.senders.redislog import make_key 13 | from djwebhooks.utils import always_string 14 | 15 | User = get_user_model() 16 | WEBHOOK_EVENTS = getattr(settings, "WEBHOOK_EVENTS", None) 17 | 18 | # Set up redis coonection 19 | # TODO - Use other Django redis-package settings names 20 | redis = StrictRedis( 21 | host=getattr(settings, "REDIS_HOST", 'localhost'), 22 | port=getattr(settings, "REDIS_PORT", 6379), 23 | db=getattr(settings, "REDIS_DB", 0)) 24 | 25 | 26 | class BasicTest(TestCase): 27 | 28 | def setUp(self): 29 | self.user = User.objects.create_user( 30 | username="testuser", 31 | email="test@example.com", 32 | password="testpassword" 33 | ) 34 | 35 | self.identifier1 = 'afdasfjasd3485' 36 | self.identifier2 = 'vrefr9jqaw9efj' 37 | 38 | self.key1 = make_key(WEBHOOK_EVENTS[0], self.user.username, self.identifier1) 39 | self.key2 = make_key(WEBHOOK_EVENTS[1], self.user.username, self.identifier2) 40 | 41 | self.webook_target = WebhookTarget.objects.create( 42 | owner=self.user, 43 | event=WEBHOOK_EVENTS[0], 44 | identifier=self.identifier1, 45 | target_url="http://httpbin.org/post" 46 | ) 47 | self.fail_target = WebhookTarget.objects.create( 48 | owner=self.user, 49 | event=WEBHOOK_EVENTS[1], 50 | identifier=self.identifier2, 51 | target_url="http://httpbin.org/status/400" 52 | ) 53 | 54 | def tearDown(self): 55 | 56 | redis.delete(self.key1) 57 | redis.delete(self.key2) 58 | 59 | def test_webhook(self): 60 | 61 | @redislog_hook(event=WEBHOOK_EVENTS[0]) 62 | def basic(owner, identifier): 63 | return {"what": "me worry?"} 64 | 65 | results = basic(owner=self.user, identifier=self.identifier1) 66 | 67 | self.assertEqual(results['what'], "me worry?") 68 | 69 | self.assertEqual(redis.llen(self.key1), 1) 70 | 71 | d = redis.lindex(self.key1, 0) 72 | d = always_string(d) 73 | data = json.loads(d) 74 | 75 | self.assertEqual(data['success'], True) 76 | 77 | def test_failed_webhook(self): 78 | 79 | @redislog_hook(event=WEBHOOK_EVENTS[1]) 80 | def basic(owner, identifier): 81 | return {"what": "me worry?"} 82 | 83 | results = basic(owner=self.user, identifier=self.identifier2) 84 | 85 | self.assertEqual(results['what'], "me worry?") 86 | 87 | self.assertEqual(redis.llen(self.key2), 1) 88 | 89 | d = redis.lindex(self.key2, 0) 90 | d = always_string(d) 91 | data = json.loads(d) 92 | 93 | self.assertEqual(data['success'], False) 94 | 95 | def test_event_dkwarg(self): 96 | 97 | @redislog_hook(number=123) 98 | def basic(owner, identifier): 99 | return {"what": "me worry?"} 100 | 101 | self.assertRaises(TypeError, basic, self.user) 102 | 103 | def test_owner_kwarg(self): 104 | 105 | @redislog_hook(event=WEBHOOK_EVENTS[0]) 106 | def basic(): 107 | return {"what": "me worry?"} 108 | 109 | self.assertRaises(TypeError, basic) 110 | 111 | def test_identifier_kwarg(self): 112 | 113 | @redislog_hook(event=WEBHOOK_EVENTS[0]) 114 | def basic(owner='pydanny'): 115 | return {"what": "me worry?"} 116 | 117 | with self.assertRaises(TypeError): 118 | basic(owner='danny') 119 | 120 | def test_cant_find_webhook_target(self): 121 | # TODO 122 | pass 123 | 124 | -------------------------------------------------------------------------------- /tests/test_sender_redisq.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import time 3 | 4 | from django.conf import settings 5 | from django.contrib.auth import get_user_model 6 | from django.test import TestCase 7 | from django.test.utils import override_settings 8 | 9 | 10 | from djwebhooks.decorators import redisq_hook 11 | from djwebhooks.models import WebhookTarget 12 | 13 | User = get_user_model() 14 | WEBHOOK_EVENTS = getattr(settings, "WEBHOOK_EVENTS", None) 15 | 16 | logger = logging.getLogger() 17 | 18 | 19 | @override_settings(WEBHOOKS_SENDER='djwebhooks.senders.redisq.sender') 20 | class BasicTest(TestCase): 21 | 22 | def setUp(self): 23 | self.user = User.objects.create_user( 24 | username="testuser", 25 | email="test@example.com", 26 | password="testpassword" 27 | ) 28 | 29 | self.identifier1 = 'afdasfjasd3485' 30 | self.identifier2 = 'vrefr9jqaw9efj' 31 | 32 | self.webook_target = WebhookTarget.objects.create( 33 | owner=self.user, 34 | event=WEBHOOK_EVENTS[0], 35 | identifier=self.identifier1, 36 | target_url="http://httpbin.org" 37 | ) 38 | self.fail_target = WebhookTarget.objects.create( 39 | owner=self.user, 40 | event=WEBHOOK_EVENTS[1], 41 | identifier=self.identifier2, 42 | target_url="http://httpbin.org/status/400" 43 | ) 44 | 45 | @override_settings(WEBHOOKS_SENDER='djwebhooks.senders.redisq.sender') 46 | def test_webhook(self): 47 | 48 | @redisq_hook(event=WEBHOOK_EVENTS[0]) 49 | def basic(owner, identifier): 50 | return {"what": "me worry?"} 51 | 52 | job = basic(owner=self.user, identifier=self.identifier1) 53 | for i in range(10): 54 | if isinstance(job, dict): 55 | result = job 56 | break 57 | logger.debug(i) 58 | time.sleep(1) 59 | if job.result is not None: 60 | result = job.result 61 | break 62 | 63 | self.assertEqual(result['what'], "me worry?") 64 | 65 | def test_failed_webhook(self): 66 | 67 | @redisq_hook(event=WEBHOOK_EVENTS[1]) 68 | def basic(owner, identifier): 69 | return {"what": "me worry?"} 70 | 71 | results = basic(owner=self.user, identifier=self.identifier2) 72 | 73 | self.assertEqual(results['what'], "me worry?") 74 | 75 | self.assertEqual(results['status_code'], 405) 76 | 77 | def test_event_dkwarg(self): 78 | 79 | @redisq_hook(number=123) 80 | def basic(owner, identifier): 81 | return {"what": "me worry?"} 82 | 83 | self.assertRaises(TypeError, basic, self.user) 84 | 85 | def test_owner_kwarg(self): 86 | 87 | @redisq_hook(event=WEBHOOK_EVENTS[0]) 88 | def basic(): 89 | return {"what": "me worry?"} 90 | 91 | self.assertRaises(TypeError, basic) 92 | 93 | def test_identifier_kwarg(self): 94 | 95 | @redisq_hook(event=WEBHOOK_EVENTS[0]) 96 | def basic(owner='pydanny'): 97 | return {"what": "me worry?"} 98 | 99 | with self.assertRaises(TypeError): 100 | basic(owner='danny') 101 | 102 | def test_cant_find_webhook_target(self): 103 | # TODO 104 | pass -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27, py33 3 | 4 | [testenv] 5 | setenv = 6 | PYTHONPATH = {toxinidir}:{toxinidir}/djwebhooks 7 | commands = python runtests.py 8 | deps = 9 | -r{toxinidir}/requirements-test.txt --------------------------------------------------------------------------------