platypush/platypush/backend/http/__init__.py

74 lines
2.1 KiB
Python
Raw Normal View History

2018-01-04 02:45:23 +01:00
import logging
import json
2018-01-04 17:20:35 +01:00
import time
2018-01-04 02:45:23 +01:00
from multiprocessing import Process
from flask import Flask, abort, jsonify, request
2018-01-04 17:20:35 +01:00
from platypush.config import Config
2018-01-04 02:45:23 +01:00
from platypush.message import Message
from platypush.message.request import Request
from .. import Backend
class HttpBackend(Backend):
""" Example interaction with the HTTP backend to make requests:
$ curl -XPOST -H 'Content-Type: application/json' -H "X-Token: your_token" \
-d '{"type":"request","target":"nodename","action":"tts.say","args": {"phrase":"This is a test"}}' \
http://localhost:8008/execute """
2018-01-04 02:45:23 +01:00
def __init__(self, port=8008, token=None, **kwargs):
super().__init__(**kwargs)
self.port = port
self.token = token
2018-01-04 17:20:35 +01:00
self.server_proc = None
2018-01-04 02:45:23 +01:00
def send_message(self, msg):
2018-01-04 17:20:35 +01:00
logging.warning('Use cURL or any HTTP client to query the HTTP backend')
2018-01-04 02:45:23 +01:00
2018-01-04 17:20:35 +01:00
def stop(self):
logging.info('Received STOP event on HttpBackend')
if self.server_proc:
self.server_proc.terminate()
self.server_proc.join()
2018-01-04 02:45:23 +01:00
2018-01-04 17:20:35 +01:00
def run(self):
super().run()
2018-01-04 02:45:23 +01:00
2018-01-04 17:20:35 +01:00
app = Flask(__name__)
2018-01-04 02:45:23 +01:00
@app.route('/execute', methods=['POST'])
2018-01-04 17:20:35 +01:00
def index():
args = json.loads(request.data.decode('utf-8'))
token = request.headers['X-Token'] if 'X-Token' in request.headers else None
if token != self.token: abort(401)
2018-01-04 02:45:23 +01:00
msg = Message.build(args)
2018-01-04 17:20:35 +01:00
logging.info('Received message on the HTTP backend: {}'.format(msg))
2018-01-04 02:45:23 +01:00
2018-01-04 17:20:35 +01:00
if isinstance(msg, Request):
response = msg.execute(async=False)
logging.info('Processing response on the HTTP backend: {}'.format(msg))
return str(response)
2018-01-04 02:45:23 +01:00
2018-01-04 17:20:35 +01:00
return jsonify({ 'status': 'ok' })
logging.info('Initialized HTTP backend on port {}'.format(self.port))
self.server_proc = Process(target=app.run, kwargs={
'debug':True, 'host':'0.0.0.0', 'port':self.port, 'use_reloader':False
2018-01-04 17:20:35 +01:00
})
time.sleep(1)
2018-01-04 02:45:23 +01:00
self.server_proc.start()
self.server_proc.join()
# vim:sw=4:ts=4:et: