Source code for server.views_api.datafiles
from flask import Blueprint, jsonify, send_from_directory
from werkzeug.utils import secure_filename
from .. import tempdirs_devices
from ..resources import entities
from ..protections import user_required, user_authorized_for_device
from ..events.update_frontend import emit_full_update
bp = Blueprint("datafiles_api", __name__, url_prefix="/api")
[docs]
@bp.route("/datafiles/<id_>", methods=["GET"])
@user_required
def get_datafile(id_):
if not id_ in entities["datafile"]:
return jsonify(message="File not found."), 404
device_id = id_.rpartition(".")[0]
if not user_authorized_for_device(device_id):
return jsonify(message="User is not authorized for this device."), 401
filename = entities["datafile"][id_]["filename"]
if not filename or filename != secure_filename(filename):
return jsonify(message="Invalid filename."), 400
return send_from_directory(tempdirs_devices[device_id], filename)
[docs]
@bp.route("/datafiles/<id_>", methods=["DELETE"])
@user_required
def delete_datafile(id_):
if not id_ in entities["datafile"]:
return jsonify(message="File not found."), 404
device_id = id_.rpartition(".")[0]
if not user_authorized_for_device(device_id):
return jsonify(message="User is not authorized for this device."), 401
filename = entities["datafile"][id_]["filename"]
del entities["datafile"][id_]
# The file is not deleted from temporary folder, since it is not necessary,
# just removing the references is enough
emit_full_update()
return jsonify(message="File '{}' has been deleted".format(filename)), 200