platypush/platypush/backend/http/poll/__init__.py

76 lines
2.4 KiB
Python
Raw Normal View History

2018-01-09 18:44:45 +01:00
import importlib
import time
2018-01-10 03:14:27 +01:00
from threading import Thread
2018-01-09 18:44:45 +01:00
from platypush.bus import Bus
from platypush.backend import Backend
from platypush.backend.http.request import HttpRequest
2018-01-11 19:31:44 +01:00
from platypush.message.request import Request
class HttpPollBackend(Backend):
"""
This backend will poll multiple HTTP endpoints/services and return events
the bus whenever something new happened. Example configuration:
backend.http.poll:
2018-01-09 18:44:45 +01:00
requests:
-
2018-01-09 18:44:45 +01:00
method: GET
type: platypush.backend.http.request.JsonHttpRequest
args:
2018-01-10 03:14:27 +01:00
url: https://host.com/api/v1/endpoint
2018-01-09 18:44:45 +01:00
headers:
2018-01-10 03:14:27 +01:00
Token: TOKEN
2018-01-09 18:44:45 +01:00
params:
2018-01-10 03:14:27 +01:00
updatedSince: 1m
timeout: 5 # Times out after 5 seconds (default)
poll_seconds: 60 # Check for updates on this endpoint every 60 seconds (default)
path: ${response['items']} # Path in the JSON to check for new items.
# Python expressions are supported.
# Note that 'response' identifies the JSON root.
# Default value: JSON root.
"""
2018-01-09 18:44:45 +01:00
def __init__(self, requests, *args, **kwargs):
"""
Params:
2018-01-09 18:44:45 +01:00
requests -- List/iterable of HttpRequest objects
"""
super().__init__(*args, **kwargs)
2018-01-09 18:44:45 +01:00
self.requests = []
for request in requests:
if isinstance(request, dict):
type = request['type']
(module, name) = ('.'.join(type.split('.')[:-1]), type.split('.')[-1])
module = importlib.import_module(module)
2018-01-10 03:14:27 +01:00
request = getattr(module, name)(**request)
elif not isinstance(request, HttpRequest):
2018-01-09 18:44:45 +01:00
raise RuntimeError('Request should either be a dict or a ' +
'HttpRequest object, {} found'.format(type(request)))
2018-01-10 03:14:27 +01:00
request.bus = self.bus
2018-01-09 18:44:45 +01:00
self.requests.append(request)
def run(self):
super().run()
2018-01-09 18:44:45 +01:00
while not self.should_stop():
for request in self.requests:
2018-01-10 03:14:27 +01:00
if time.time() - request.last_request_timestamp > request.poll_seconds:
request.execute()
time.sleep(0.1) # Prevent a tight loop
2018-01-09 18:44:45 +01:00
def send_message(self, msg):
2018-01-10 03:14:27 +01:00
pass
# vim:sw=4:ts=4:et: