def container() -> NoReturn:
    """
    Dependency initialize container.
    Please do not change initialization order.
    """
    # Utils classes
    injector.map(init_settings=InitialSettings(app=app))
    injector.map(utils=Utils())
    # Process services
    injector.map(graph_service=GraphService())
    injector.map(polynomial_service=PolynomialService(
        utils=injector.get('utils')))
    injector.map(calculation_service=CalculationService(
        utils=injector.get('utils'),
        graph_service=injector.get('graph_service')))
示例#2
0
 def decorated_view(*args, **kwargs):
     utils: Utils = injector.get('utils')
     calculation_id_cookie_exist: bool = utils.check_cookie_exists(
         cookie_value=request.cookies.get(
             Constants.CALCULATION_ID_COOKIE_NAME))
     counter_cookie_exist: bool = utils.check_cookie_exists(
         cookie_value=request.cookies.get(
             Constants.PAGE_COUNTER_COOKIE_NAME))
     if flask.request.method not in methods:
         return func(*args, **kwargs)
     elif calculation_id_cookie_exist and counter_cookie_exist:
         return func(*args, **kwargs)
     else:
         flash(
             u'Невозможно найти начальную запись. Заполните значения для 1 переменной заново.'
         )
         return redirect(url_for('main.index'))
    def remove_old_sessions_task():
        # Get service from DI container
        from app import injector
        utils: Utils = injector.get('utils')
        current_timestamp: int = int(utils.get_current_timestamp_millis())

        # Get files for check it on delete
        list_of_json_files: list = glob.glob(Constants.PATH_TO_CALC_STORAGE_FILE + ScheduledService.JSON_FILE_EXTENSION)
        list_of_images_files: list = glob.glob(Constants.PATH_SOLUTION_GRAPHS_IMAGE + ScheduledService.PNG_FILE_EXTENSION)
        list_of_filenames: list = [os.path.splitext(os.path.basename(path))[0] for path in list_of_json_files]
        list_of_petal_graphs: list = glob.glob(Constants.PATH_PETAL_GRAPHS_IMAGE + "*/")

        # Remove old files
        for index, filename in enumerate(list_of_filenames):
            if abs(current_timestamp - int(filename)) > ScheduledService.ONE_DAY_IN_MILLISECONDS:
                os.remove(list_of_json_files[index])
                try:
                    os.remove(list_of_images_files[index])
                    shutil.rmtree(list_of_petal_graphs[index])
                except IndexError:
                    pass
示例#4
0
        hotel_record["norm_tones"] = {
            tone_id: sum(scores) / len(scores)
            for tone_id, scores in norm_tones.items()
        }

        return doc_id, hotel_record

    def parse_save_value(self, value, val_type='na'):
        """Cast/Solve pandas values before indexing in the ElasticSearch

            Parameters:
            value (str/int/float/datetime): The value
            val_type (str): Type of the value

            Returns:
            value (str/int/float/datetime): The casted/solved value
        """
        if val_type == 'date':
            return pd.to_datetime(value) if not pd.isna(value) else datetime(
                1970, 1, 1, 0, 0)
        elif val_type == 'txt':
            return str(value) if not pd.isna(value) else "Other"
        elif val_type == "float":
            return float(value) if not pd.isna(value) else 0.0
        elif val_type == "int":
            return int(value) if not pd.isna(value) else 0
        return ""


elastic_instance = injector.get(Elastic)
示例#5
0
from services.watson import Watson
import logging

log = logging.getLogger(__name__)
tqdm.pandas()


class Review(object):
    @inject
    def __init__(self, csv_loader_object: CSVLoader, watson_object: Watson):
        self.csv_loader = csv_loader_object
        self.watson = watson_object

    def analyze_reviews_tones(self, hotel_name=None):
        """Get tones of a hotel reviews

            Parameters:
            hotel_name (str): Hotel name

            Returns:
            (dict): Hotel normalized tones
        """
        hotels_data = self.csv_loader.get_hotel_tones(hotel_name, self.watson)
        return {
            'name': hotel_name,
            'tones': hotels_data[hotel_name]['norm_tones']
        }, 200


review_instance = injector.get(Review)
            limited_recipes = [recipe for recipe in recipes][:kwargs['limit']]
        if 'sort'in kwargs:
            limited_recipes.sort(key=lambda x: int(x['id']), reverse=kwargs['sort'] == 'desc')

        return limited_recipes


    def rate_recipe(self, recipe_id: str, rate_recipe):

        found_recipe = self._db.find_by_id({'id': recipe_id})
        if not found_recipe:
            return ({"message": "Recipe not found"}, 404)

        user = rate_recipe['user']
        rate = rate_recipe['rate']
        review ={'user': user, 'rate':rate}

        find_user = self._db.find_by_id({'id': recipe_id, 'rating.user':user})
        if find_user:
            return {"message": "Rating already provided by the user"}, 200

        updatedExisting = self._db.add_rating({'id': recipe_id}, {'rating':review})
        if updatedExisting:
            return {"message": "Successfully updated rating"}, 201
        else:
            return {"message": "Failed to update Rating"},  500



class_instance = injector.get(Recipe)
示例#7
0
    def put_todo(self, todo_id: int, todo):
        todo['id'] = todo_id
        if 'created' not in todo:
            todo['created'] = datetime.utcnow()
        exists = self._db.update_or_create({'id': todo_id}, todo)
        return NoContent, (200 if exists else 201)

    def delete_todo(self, todo_id: int):
        was_deleted = self._db.delete_one({'id': todo_id})
        if was_deleted:
            return NoContent, 204
        else:
            return NoContent, 404

    def find_by_tags(self, tags: list):
        if len(tags) <= 0:
            return NoContent, 400
        return self._db.find_by_tags(tags), 200

    def find_by_status(self, status: list):
        if len(status) <= 0:
            return NoContent, 400
        return self._db.find_by_status(status), 200

    def create_todo(self, new_todo: dict):
        new_todo['status'] = 'active'
        return self._db.create(new_todo), 201


class_instance = injector.get(Todo)