birb-scheduler-teller/birb_scheduler_teller/views/assignment_view.py

72 lines
2.1 KiB
Python
Raw Normal View History

2021-12-10 21:59:56 +01:00
#!/usr/bin/env python3
2021-12-10 23:04:41 +01:00
from typing import Optional
from flask import jsonify, request, abort, current_app
from utils import json_required, redis_client
2021-12-10 21:59:56 +01:00
from flask_classful import FlaskView
2021-12-10 23:04:41 +01:00
import json
2021-12-10 21:59:56 +01:00
2021-12-10 22:02:30 +01:00
class AssignmentView(FlaskView):
2021-12-10 23:04:41 +01:00
@staticmethod
def _resolve_response(site: Optional[str]) -> dict:
site_url_map = redis_client.get("SITEURLMAP")
if site_url_map:
site_url_map = json.loads(site_url_map.decode('utf-8'))
if not site_url_map:
return {
"site": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][0],
"url": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][1],
"hard_default": True
}
if not site:
return {
"site": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][0],
"url": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][1],
"hard_default": True
}
if site not in site_url_map.keys():
# This should be an internal server error instead
return {
"site": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][0],
"url": current_app.config['DEFAULT_WHILE_NOT_DEFINED'][1],
"hard_default": True
}
return {
"site": site,
"url": site_url_map[site],
"hard_default": False
}
@json_required
def post(self):
device_id = request.json['device_id']
schedule_store_key = f"SCHEDULED:{device_id}"
target_site = redis_client.get(schedule_store_key)
if target_site:
target_site = target_site.decode('utf-8')
if not target_site:
default_target = redis_client.get('DEFAULT:SCHEDULED')
if default_target:
target_site = default_target.decode('utf-8')
redis_client.set(schedule_store_key, default_target)
# Update (or set) TTL
redis_client.expire(
schedule_store_key,
current_app.config['DEVICE_TIMEOUT']
)
return jsonify(self._resolve_response(target_site))