def post(self) -> ({str: str}, HTTPStatus):
        """
        Rename an existing Theme
        :post_argument  current_name: name of SubTheme
        :post_argument new_name: new name of SubTheme
        :post_type  current_name: str
        :post_type  new_name: str
        :returns: A JSON of the changes made to the theme with a http status code of 200, otherwise
                  a JSON of the error details and the appropriate http status code
        """
        if not get_jwt_claims()['admin']:
            return {
                "error": "administration privileges required"
            }, HTTPStatus.FORBIDDEN

        # Get arguments
        args = self.reqparser.parse_args()

        # Check the current theme name and the new theme name  is not empty, abort if it is empty
        if not args["current_name"] or not args["new_name"]:
            return ({
                'error': 'Theme name cannot be empty',
                'name': args["current_name"],
                'new_name': args["new_name"]
            }, HTTPStatus.BAD_REQUEST)

        theme = Theme.get_by_name(args["current_name"])

        if not theme:
            # cannot rename a theme that does not exist.
            return {
                'error': 'Theme does not exists.',
                'id': " ",
                'name': args["current_name"]
            }, HTTPStatus.BAD_REQUEST

        # Does the new name for theme exist?
        if Theme.get_by_name(args["new_name"]):
            return {
                'error':
                'Cannot rename theme to {} ; Theme {} already exists.'.format(
                    args["new_name"], args["new_name"]),
                'id':
                "",
                'name':
                args["current_name"]
            }, HTTPStatus.BAD_REQUEST

        # rename the new theme
        theme.name = args["new_name"]
        theme.save()
        theme.commit()

        return ({
            "message": "Theme renamed",
            "id": theme.id,
            "old_name": args["current_name"],
            "new_name": theme.name
        }, HTTPStatus.OK)
Beispiel #2
0
    def post(self) -> ({str: str}, HTTPStatus):
        """
        Delete an existing Theme.
        :param  name:   name of Theme to delete.
        :param id:      id of Theme to delete.
        :type  name:    str
        :type  id:      str
        :returns: A no content with a http status code of 204, otherwise a JSON of the error details
                  and the appropriate http status code
        """
        if not get_jwt_claims()['admin']:
            return {"error": "administration privileges required"}, HTTPStatus.FORBIDDEN

        # Get arguments
        args = self.reqparser.parse_args()

        # does the theme exist?
        theme = Theme.get_by_name(args["name"]) if "name" in args else Theme.get_by_id(args["id"])
        if not theme:
            # cannot delete a theme that does not exist.
            return {'error': 'Theme does not exists.', 'id': " ", 'name': args["name"]}, HTTPStatus.BAD_REQUEST

        sub_themes = SubTheme.get_by_theme_id(theme.id)
        for sub_theme in sub_themes:
            sub_theme.delete()
            sub_theme.commit()

        # delete the theme
        theme.delete()
        theme.commit()

        return "", HTTPStatus.NO_CONTENT
 def create_dummy_theme(self) -> Theme:
     """
     Create a Theme
     :return: a Theme
     """
     theme = Theme.get_by_name("_test_add_theme_")
     if not theme:
         theme = Theme("_test_add_theme_")
         theme.save()
         theme.commit()
         return theme
     return theme
Beispiel #4
0
 def create_dummy_theme(self) -> Theme:
     """
     Create a Theme
     :return: a Theme instance
     """
     theme = Theme.get_by_name("_test_add_theme_")
     if not theme:
         theme = Theme("_test_add_theme_")
         theme.save()
         theme.commit()
         self.dummy_ids.append(theme.id)
         return theme
     return theme
def create_theme(name: str = 'Environment') -> Theme:
    """
    Create a Theme
    :param name: Themes name
    :raises ValueError: If the new Theme is not persisted to the dB
    :return: A new Theme
    """
    theme = Theme.get_by_name(name)
    if not theme:
        theme = Theme(name)
        theme.save()
        theme.commit()
    if not theme:
        logger.critical('ValueError raised while creating Theme')
        raise ValueError
    return theme
Beispiel #6
0
    def create_theme(self) -> None:
        """
        Create a Theme
        """
        self.theme = Theme.get_by_name("_test_theme_")
        if self.theme:
            return

        self.theme = Theme("_test_theme_")
        self.theme.save()
        try:
            self.theme.commit()

        except Exception as exp:
            logger.error(exp)
            self.tearDown()

        if not self.theme:
            self.fail()
    def get(self) -> ([Theme], HTTPStatus):
        """
        Fetch Themes
        Parameters can be passed using a POST request that contains a JSON with the following fields:
        :param limit:   the maximum number of entries to return
        :param name:    themes name
        :param id:      the themes identification number
        :type limit:    int
        :type name:     str
        :type id:       str

        :return: a list of Theme/s and an HTTPStatus code of 200 on success otherwise an JSON with an error message
                 and appropriate http status
        """
        # Get arguments passed in POST request
        args = self.reqparser.parse_args()

        # fetch themes using arguments passed in post request
        themes = []
        if "id" in args:
            theme = Theme.get_by_id(args["id"])
            if theme:
                themes.append(theme.json())
        elif "name" in args:
            theme = Theme.get_by_name(args["name"])
            if theme:
                themes.append(theme.json())
        else:
            [themes.append(theme.json()) for theme in Theme.get_all()]

        # were any themes found in the database?
        if len(themes) < 1:
            # no themes were found
            return [], HTTPStatus.OK

        if "limit" in args:
            try:
                themes = themes[:int(args["limit"])]
            except ValueError:
                return {"error": "Limit parsed is not an int"}, HTTPStatus.BAD_REQUEST

        # themes were found
        return themes, HTTPStatus.OK
    def post(self) -> ({str: str}, HTTPStatus):
        """
        Creates a new theme
        :post_argument  name: the name of the new theme
        :post_type  name: str
        :returns: A JSON with a message, theme id, and new themes name with a http status of 200 (OK) otherwise,
                  A JSON with an appropriate error message and http status applicable to the error
        """
        if not get_jwt_claims()['admin']:
            return {
                "error": "administration privileges required"
            }, HTTPStatus.FORBIDDEN

        # Get arguments
        args = self.reqparser.parse_args()

        # Check the theme name is not empty, abort if it is empty
        if not args["name"]:
            return {
                'error': 'Theme cannot be empty',
                'name': "''"
            }, HTTPStatus.BAD_REQUEST

        # Check theme does not exist (avoid duplicates)
        if Theme.get_by_name(args["name"]):
            return {
                'error': 'Theme already exists.',
                'id': " ",
                'name': args["name"]
            }, HTTPStatus.BAD_REQUEST

        # Create the new theme
        theme = Theme(args["name"])
        theme.save()
        theme.commit()

        return {
            "message": "New theme created",
            "id": theme.id,
            "name": theme.name
        }, HTTPStatus.OK
Beispiel #9
0
    def post(self) -> (dict, HTTPStatus):
        """
        Get dummy data from CSV. Store dummy data in database
        :param file_name: File name to extract data from.
        :return: A Status Report detailing the dB Entries created and an HTTP
        Status code 200 on success otherwise, a JSON error message is returned
        with the appropriate HTTPStatus code
        """
        args = self.reqparser.parse_args()
        # Get size of tables before import
        self.loc_stats["before"] = db.session.query(func.count(
            LocationData.id)).scalar()
        self.tracker_stats["before"] = db.session.query(func.count(
            Tracker.id)).scalar()

        # Fetch Data from CSV
        try:
            df = pd.read_csv(args['file_name'])
        except IOError as ioe:
            logger.error("Unable to parse CSV data to dataframe",
                         ioe.with_traceback(ioe.__traceback__))
            return dict(error="Unable to parse CSV data to dataframe",
                        trackback=ioe.with_traceback(
                            ioe.__traceback__)), HTTPStatus.BAD_REQUEST

        moving_theme = Theme.get_by_name("Moving_Sensors")
        if moving_theme:
            moving_sensor_theme_id = moving_theme.id
        else:
            moving_sensor_theme = Theme("Moving_Sensors")
            moving_sensor_theme.save()
            moving_sensor_theme.commit()
            moving_sensor_theme_id = moving_sensor_theme.id

        moving_subtheme = SubTheme.get_by_name("Moving_Airquality")
        if moving_subtheme:
            moving_sensor_subtheme_id = moving_subtheme.id
        else:
            moving_sensor_subtheme = SubTheme(moving_sensor_theme_id,
                                              "Moving_Airquality")
            moving_sensor_subtheme.save()
            moving_sensor_subtheme.commit()
            moving_sensor_subtheme_id = moving_sensor_subtheme.id

        # Trackers must be unique, Fetch trackers and make dB entries for
        # each unique tracker
        unique_tracker_ids = df["tracker"].unique()

        for tracker_id in unique_tracker_ids:
            self.t_ids[self.create_trackers(str(tracker_id),
                                            moving_sensor_subtheme_id)] = 0

        # Define Location data Pandas DataFrame Column names
        loc_df = df[[
            'tracker', 'datetime', 'latitude', 'longitude', 'speed', 'heading',
            'elevation', 'charger', 'battery', 'signalquality', 'satcnt'
        ]]

        # Drop all entries that are incomplete have NaN or None/ Null values
        loc_df = loc_df.dropna()

        # Store Location Data in the dB
        for index, row in loc_df.iterrows():
            self.add_location_data(row['tracker'], row['datetime'],
                                   row['latitude'], row['longitude'],
                                   row['speed'], row['heading'],
                                   row['elevation'], row['charger'],
                                   row['battery'], row['signalquality'],
                                   row['satcnt'])

        self.loc_stats["after"] = db.session.query(func.count(
            LocationData.id)).scalar()
        self.tracker_stats["after"] = db.session.query(func.count(
            Tracker.id)).scalar()

        return self.status_report(), 200