Skip to content
Snippets Groups Projects
Select Git revision
  • bbddb10f1c4239093c06cc4fcba9a4e07c30c070
  • master default protected
  • 51-docker
  • 40-return-match-when-edit-salamander
  • 36-email-verification
  • 23-add-object-detection
  • 22-run-branch
7 results

location.py

Blame
  • Code owners
    Assign users and groups as approvers for specific file changes. Learn more.
    location.py 7.27 KiB
    from flask import request, jsonify
    from flask_restful import Resource
    from flask_jwt_extended import jwt_required, get_jwt_identity
    from api import db, limiter
    from api.models.dbmodels import Location, Salamander, User
    import re
    import os
    from api.endpoints.matchsalamander import sanitize_int_str
    from path_constants import _ACCESS_DATABASE
    LATITUDE_REGEX = "^(\\+|-)?(?:90(?:(?:\\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\\.[0-9]{1,6})?))$"
    LONGITUDE_REGEX = "^(\\+|-)?(?:180(?:(?:\\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\\.[0-9]{1,6})?))$"
    
    
    """
    Endpoint for creating, updating, getting and deleting locations in the system.
    GET: Returns all data about all locations to the user.
    POST: Creates a new location with radius, name, longitude and latitude.
    PUT: For editing a location. Change its name or radius.
    DELETE: For deleting a specific location. This can only be done if the location does not contain a salamander.
    """
    
    
    class LocationEndpoint(Resource):
        decorators = [limiter.limit("60/minute")]
    
        @staticmethod
        @jwt_required
        def post():
            data = request.form
            if "name" in data and "radius" in data and "latitude" in data and "longitude" in data:
                with _ACCESS_DATABASE:
                    location = db.session.query(Location).filter_by(name=data['name'].lower()).first()
                    if location is None and re.search(LATITUDE_REGEX, data['latitude']) and re.search(LONGITUDE_REGEX,
                                                                                                      data['longitude']):
                        new_location = Location(name=data['name'].lower(), longitude=data['longitude'],
                                                latitude=data['latitude'], radius=sanitize_int_str(str(data['radius'])))
                        db.session.add(new_location)
                        db.session.commit()
                        create_directory_folders(data['name'].lower())
                        return jsonify({"message": "new location registered", "status": 200})
                    else:
                        return jsonify({"message": "this location name already in use or bad coordinates", "status": 400})
            else:
                return jsonify({"message": "wrong data", "status": 400})
    
        @staticmethod
        @jwt_required
        def get():
            locations = db.session.query(Location).all()
            location_list = []
            for location in locations:
                loc = {"id": location.id, "radius": location.radius, "name": location.name, "latitude": location.latitude,
                       "longitude": location.longitude}
                location_list.append(loc)
            return jsonify({"locations": location_list, "status": 200})
    
        @staticmethod
        @jwt_required
        def delete():
            user_id = get_jwt_identity()
            user = db.session.query(User).filter_by(id=user_id).first()
            data = request.form
            if user.admin:
                if "id" in data:
                    with _ACCESS_DATABASE:
                        salamanders = db.session.query(Salamander).filter_by(location_id=data['id']).all()
                        if salamanders is not None:
                            if len(salamanders) == 0:
                                location = db.session.query(Location).filter_by(id=data['id']).first()
                                if location:
                                    db.session.delete(location)
                                    db.session.commit()
                                    path = os.path.join("images", location.name)
                                    dir_list = os.listdir(path)
                                    for directory in dir_list:
                                        species_path = os.path.join(path, directory)
                                        gender_dir_list = os.listdir(species_path)
                                        for gender in gender_dir_list:
                                            os.rmdir(os.path.join(species_path, gender))
                                        os.rmdir(species_path)
                                    os.rmdir(path)
                                    return jsonify({"message": location.name + " deleted.", "status": 200})
                                else:
                                    return jsonify({"message": "location doesn't exist", "status": 400})
                            else:
                                return jsonify(
                                    {"message": "location needs to be empty." + " There are " + str(len(salamanders))
                                                + " salamanders in this location.", "status": 400})
                        else:
                            return jsonify({"message": "query failed", "status": 400})
                else:
                    return jsonify({"message": "wrong data", "status": 400})
            else:
                return jsonify({"message": "user not admin", "status": 400})
    
        @staticmethod
        @jwt_required
        def put():
            user_id = get_jwt_identity()
            user = db.session.query(User).filter_by(id=user_id).first()
            data = request.form
            if user.admin:
                if "id" in data:
                    with _ACCESS_DATABASE:
                        location = db.session.query(Location).filter_by(id=data['id']).first()
                        if location:
                            if "new_radius" in data:
                                location.radius = sanitize_int_str(str(data['new_radius']))
                                db.session.commit()
                            if "new_name" in data:
                                folder_path = os.path.join(os.path.abspath("./images"), location.name.lower())
                                if os.path.isdir(folder_path):
                                    new_path = os.path.join(os.path.abspath("./images"), data['new_name'].lower())
                                    if not os.path.isdir(new_path):
                                        os.rename(folder_path, new_path)
                                        location.name = data['new_name'].lower()
                                        db.session.commit()
                                    return jsonify({"message": "location updated", "status": 200})
                                else:
                                    return jsonify({"message": "location folder was not found", "status": 400})
                            return jsonify({"location": location.id, "status": 200})
                        else:
                            return jsonify({"message": "location doesn't exist", "status": 400})
                else:
                    return jsonify({"message": "wrong data", "status": 400})
            else:
                return jsonify({"message": "user not admin", "status": 400})
    
    
    # creates the folder structure when a location is registered
    def create_directory_folders(location):
        dir_smooth_male = "images/" + location + "/smooth_newt/" + "male/"
        dir_smooth_female = "images/" + location + "/smooth_newt/" + "female/"
        dir_smooth_juvenile = "images/" + location + "/smooth_newt/" + "juvenile/"
        dir_northern_male = "images/" + location + "/northern_crested_newt/" + "male/"
        dir_northern_female = "images/" + location + "/northern_crested_newt/" + "female/"
        dir_northern_juvenile = "images/" + location + "/northern_crested_newt/" + "juvenile/"
        os.makedirs(dir_smooth_male)
        os.makedirs(dir_smooth_female)
        os.makedirs(dir_smooth_juvenile)
        os.makedirs(dir_northern_male)
        os.makedirs(dir_northern_female)
        os.makedirs(dir_northern_juvenile)