Skip to content

Commit 4718f04

Browse files
committed
Server returns JSON response
1 parent de2de4b commit 4718f04

File tree

3 files changed

+34
-21
lines changed

3 files changed

+34
-21
lines changed

label_server/__init__.py

+33-17
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
from flask import Flask, request, redirect
1+
from flask import Flask, request, redirect, Response
2+
from werkzeug.exceptions import HTTPException
23
from .label_print import print_label
3-
import requests
44
import logging
55

6+
67
app = Flask(__name__, instance_relative_config=True)
78
logger = logging.Logger(__name__)
89

@@ -12,21 +13,36 @@
1213
app.logger.handlers = gunicorn_logger.handlers
1314
app.logger.setLevel(gunicorn_logger.level)
1415

15-
@app.route("/print")
16+
@app.errorhandler(Exception)
17+
def all_exception_handler(error):
18+
if isinstance(error, HTTPException):
19+
return error
20+
21+
res = {"error": str(error)}
22+
return res, 500
23+
24+
25+
@app.route("/print", methods=["POST", "OPTIONS"])
1626
def _print():
17-
label_id = request.args.get("id")
18-
return_url = request.args.get("return_url")
27+
if request.method == "OPTIONS":
28+
return {}
29+
30+
label_data = request.get_json()
31+
serial = label_data.get("id")
32+
name = label_data.get("name", "")
33+
expiry = label_data.get("expiry", "who knows?")
34+
caption = label_data.get("caption", "Invalid")
35+
36+
cut = True
1937
try:
20-
membership_url = app.config["MEMBERSHIP_URL"]
21-
r = requests.get(f'{membership_url}/api/labels/label/{label_id}')
22-
label_data = r.json()
23-
serial = label_data.get("id")
24-
name = label_data.get("name", "")
25-
expiry = label_data.get("expiry", "who knows?")
26-
caption = label_data.get("caption", "Invalid")
27-
28-
cut = True
2938
print_label(name, caption, expiry, serial, cut)
30-
except Exception as ex:
31-
logger.exception("Error printing label")
32-
return redirect(return_url)
39+
except FileNotFoundError:
40+
return {"error": "Printer not switched on"}, 500
41+
42+
return {"success": True}
43+
44+
@app.after_request
45+
def add_origin(response):
46+
response.headers["Access-Control-Allow-Origin"] = "*"
47+
response.headers["Access-Control-Allow-Headers"] = "origin, content-type, accept"
48+
return response

label_server/label_print.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,7 @@ def send_to_printer(image, cut=True):
7272
cut=cut
7373
)
7474

75-
try:
76-
send(instructions=instructions, printer_identifier=PRINTER, backend_identifier=BACKEND, blocking=True)
77-
except FileNotFoundError:
78-
logger.warn("Tried printing with printer unplugged")
75+
send(instructions=instructions, printer_identifier=PRINTER, backend_identifier=BACKEND, blocking=True)
7976
logger.info("printing done")
8077

8178
def print_label(name, description, expiry, serial=None, cut=True):

requirements.txt

-20 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)