~kf5jwc/sms-printer

ref: 88d91e19f2499a3933341a270f81e30ebc048ac3 sms-printer/sms_printer/application.py -rw-r--r-- 1.2 KiB
88d91e19 — Kyle Jones Refactor for adding JSON schema based parsing 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import logging

from flask import Flask, Response, json, request

from .sms import NoMatchingSchema, parse_sms
from .utils import log_request, allowed_sender, log_request, print_message


APP = Flask(__name__)
logging.basicConfig(level=logging.DEBUG)


@APP.route("/", methods=['GET'])
def main():
    return Response(status=204)


@APP.route("/sms-printer", methods=['POST'])
def sms_printer() -> Response:
    # If this throws, flask takes care of it
    sms_input = request.get_json(force=True)

    try:
        sms_list = parse_sms(sms_input)
        log_request(sms_input)

    except NoMatchingSchema:
        logging.error("Unrecognized message format!")
        logging.debug(json.dumps(sms_input))
        return Response(status=415)

    for sms in sms_list:

        logging.info("Recieved sms from %s", sms.sender)
        if not allowed_sender(sms.sender):
            logging.warn("Unauthorized sender %s", sms.sender)
            return Response(status=401)

        logging.info("Printing sms from %s", sms.sender)
        logging.debug("Text: %s", sms.text)
        if not print_message(sms.text):
            logging.error("Error printing sms")
            return Response(status=500)

        return Response(status=200)