Added support for custom webhooks

This commit is contained in:
Fabio Manganiello 2019-05-17 14:55:29 +00:00
parent 7ea65cf90e
commit 1ad86428c8
3 changed files with 84 additions and 1 deletions

View file

@ -21,7 +21,13 @@ def execute():
""" Endpoint to execute commands """ """ Endpoint to execute commands """
if not authentication_ok(request): return authenticate() if not authentication_ok(request): return authenticate()
msg = json.loads(request.data.decode('utf-8')) try:
msg = json.loads(request.data.decode('utf-8'))
except Exception as e:
logger().error('Unable to parse JSON from request {}: {}'.format(
request.data, str(e)))
abort(400, str(e))
logger().info('Received message on the HTTP backend: {}'.format(msg)) logger().info('Received message on the HTTP backend: {}'.format(msg))
try: try:

View file

@ -0,0 +1,49 @@
import json
from flask import Blueprint, abort, request, Response
from platypush.backend.http.app import template_folder
from platypush.backend.http.app.utils import authenticate, authentication_ok, \
logger, send_message
from platypush.message.event.http.hook import WebhookEvent
hook = Blueprint('hook', __name__, template_folder=template_folder)
# Declare routes list
__routes__ = [
hook,
]
@hook.route('/hook/<hook_name>', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'])
def hook(hook_name):
""" Endpoint for custom webhooks """
if not authentication_ok(request): return authenticate()
event_args = {
'hook': hook_name,
'method': request.method,
'args': dict(request.args or {}),
'data': request.data.decode(),
}
if event_args['data']:
try:
event_args['data'] = json.loads(event_args['data'])
except:
pass
event = WebhookEvent(**event_args)
try:
response = send_message(event)
return Response(json.dumps({'status': 'ok', **event_args}),
mimetype='application/json')
except Exception as e:
logger().error('Error while dispatching webhook event {}: {}'.
format(event, str(e)))
abort(500, str(e))
# vim:sw=4:ts=4:et:

View file

@ -0,0 +1,28 @@
from platypush.message.event import Event
class WebhookEvent(Event):
"""
Event triggered when a custom webhook is called.
"""
def __init__(self, hook, method, data=None, args=None, *argv, **kwargs):
"""
:param hook: Name of the invoked web hook, from http://host:port/hook/<hook>
:type hook: str
:param method: HTTP method (in uppercase)
:type method: str
:param data: Extra data passed over POST/PUT/DELETE
:type data: str or dict/list from JSON
:param args: Extra query string arguments
:type args: dict
"""
super().__init__(hook=hook, method=method, data=data,
args=args or {}, *argv, **kwargs)
# vim:sw=4:ts=4:et: