Exemplo n.º 1
0
def comment_post(request):
    if request.POST:
        anime_id = utils.try_get_from_request(request, utils.POST, 'anime_id')
        text = utils.try_get_from_request(request, utils.POST, 'text')

        author = auth_manager.get_by_id(request.session['viewer_id'])
        anime = anime_manager.get_by_id(anime_id)
        if author is None or anime is None:
            logger.write(
                'В методе comment_post() отсутствует author или anime. Author = '
                + str(author) + ' | ' + str(anime), logger.DAO)
            code = 0
            return HttpResponse(code)
        comment = AnimeCommentsManager.create(author, anime, text)

        publish_date = comment.publish_date.astimezone(
            pytz.timezone("Asia/Almaty")).strftime("%d %B %Y %H:%M")

        obj = {
            'id': comment.id,
            'author': {
                'id': str(comment.author.id),
                'image_url': str(comment.author.image.url),
                'username': str(comment.author.base_user.username),
                'role': str(comment.author.role.value)
            },
            'publish_date': str(publish_date),
            'text': comment.text
        }
        comment_json = json.dumps(obj)
        return HttpResponse(comment_json, content_type='application/json')
    code = 0
    return HttpResponse(code)
Exemplo n.º 2
0
def get_context(module_name):
    """" Возвращает контекст в зависимости от названия модуля """

    SETTINGS = settings.A_SETTINGS
    CONSTANTS = settings.A_CONSTANTS
    if module_name == 'watch':
        watch_context = Dictionary()
        watch_context.add('xsearch_form', XSearchForm())
        watch_context.add('anime_cover_width', CONSTANTS['anime_cover_width'])
        watch_context.add('anime_cover_height',
                          CONSTANTS['anime_cover_height'])
        return watch_context
    elif module_name == 'cms':
        cms_context = Dictionary()
        cms_context.add('cms_navigation_links',
                        cms_navigation_links_manager.get_all())
        cms_context.add('notifications',
                        CmsMainInfoManager.get_notifications())
        return cms_context
    elif module_name == 'auth':
        auth_context = Dictionary()
        return auth_context
    elif module_name == 'feedback':
        feedback_context = Dictionary()
        return feedback_context
    else:
        if module_name is None:
            logger.write('Был произведен запрос в безмодульный режим',
                         logger.MODULE)
        else:
            logger.write('Модуля "' + module_name + '" нет', logger.MODULE)
    return None
Exemplo n.º 3
0
 def get_by_id(self, pk: int):
     try:
         record = self._model_type.objects.get(pk=pk)
     except Exception as error:
         logger.write('Ошибка поиска модели "' + str(self._model_type) + '". Сообщение: ' + str(error), logger.DAO)
         record = None
     return record
Exemplo n.º 4
0
 def delete(pk):
     try:
         comment = AnimeComment.objects.get(pk=pk)
         comment.delete()
     except Exception as error:
         logger.write('Не получилось удалить комментарий с ID: ' + str(pk) + '. Message: ' + str(error), logger.HTTP)
         return False
     return True
Exemplo n.º 5
0
def elastic_fill_get(request, data_type):
    logger.write(
        'Пользователь запросил пересоздание актуального индекса "' +
        str(data_type) + '"', logger.ELASTIC)
    es_manager.create_index(data_type)
    es_manager.fill_index(data_type)

    return redirect_elastic()
Exemplo n.º 6
0
def raise_exception(exception, logger_type):
    """ вызывает эксепшн если мы в режиме дебаггера """

    if SETTINGS['debug']:
        if type('') is type(exception):
            raise Exception(exception)
        raise exception

    logger.write(str(exception), logger_type)
Exemplo n.º 7
0
 def search_anime(self, query):
     """ поиск аниме """
     anime_list = self.searcher.search_anime(query)
     if anime_list is not None:
         anime_list = AnimeManager.prepare_anime_list(anime_list)
         result_quantity = str(len(anime_list))
         logger.write(
             'Пользователь запросил поиск по запросу "' + query +
             '"\nКол-во результатов: ' + result_quantity, logger.ELASTIC)
     return anime_list
Exemplo n.º 8
0
def feedback_send(request):
    code = 1
    if request.POST:
        try:
            text = utils.try_get_from_request(request, 'POST', 'text')
            appeal_manager.create(text, request.user)
        except Exception as error:
            code = 2
            logger.write(str(error), logger.MODULE)
    return HttpResponse(code)
Exemplo n.º 9
0
Arquivo: auth.py Projeto: Lowl11/anime
    def get_by_base_user(base_user):
        try:
            viewer = Viewer.objects.get(base_user=base_user)
        except Exception as error:
            viewer = None
            logger.write(
                'Поиск пользователя по базовому пользователю. ' + str(error),
                logger.AUTH)

        return viewer
Exemplo n.º 10
0
def handle_log(request):
    code = 1
    if request.POST:
        message = utils.try_get_from_request(request, 'POST', 'message')
        send_data = utils.try_get_from_request(request, 'POST', 'data')
        url = utils.try_get_from_request(request, 'POST', 'url')
        log_text = message + ' | URL: ' + url
        if send_data is not None:
            log_text += ' | Параметры: ' + str(send_data)
        logger.write(log_text, logger.FRONT)
    return HttpResponse(code)
Exemplo n.º 11
0
def index_anime():
    try:
        # TODO нужно вынести этот код отдельно и для каждого таска
        start = datetime.now()

        data_type = 'anime'
        es_manager = ElasticSearchManager()
        es_manager.create_index(data_type)
        es_manager.fill_index(data_type)

        end = datetime.now()
        run_time = end - start
        logger.write('Task "index_anime" отработал успешно за ' + str(run_time.seconds) + ' сек.', logger.TASK)
    except Exception as error:
        logger.write('Task "index_anime" отработала с ошибкой: \n' + str(error), logger.TASK)
Exemplo n.º 12
0
Arquivo: auth.py Projeto: Lowl11/anime
    def signin_user(request, dict):
        # проверяем есть ли пользователь с такими данными
        base_user = authenticate(username=dict['username'],
                                 password=dict['password'])

        if base_user is not None:
            viewer = Viewer.objects.get(base_user=base_user)
            if viewer is not None:
                # авторизуем пользователя
                login(request, base_user)
                viewer = Viewer.objects.get(base_user=base_user)
                request.session['role'] = viewer.role.value
                request.session['viewer_id'] = viewer.id
                logger.write(
                    'Пользователь ' + base_user.username + ' залогинился',
                    logger.AUTH)
Exemplo n.º 13
0
def try_get_from_request(request, request_type, name):
    """ пытатется вернуть значение с массива по названию с реквеста """

    try:
        if request_type == POST:
            return request.POST[name]
        elif request_type == GET:
            return request.GET[name]
        elif request_type == SESSION:
            return request.session[name]
        else:
            logger.write('Тип ' + request_type + ' не поддерживается',
                         logger.HTTP)
    except Exception as error:
        logger.write(
            'Неизвестная ошибка. Попытка взять значение по ключу "' + name +
            '" из "' + request_type + '". '
            '\nСообщение об ошибке: ' + str(error), logger.HTTP)
    return None
Exemplo n.º 14
0
Arquivo: auth.py Projeto: Lowl11/anime
 def logout(request):
     logger.write('Пользователь ' + request.user.username + ' вышел',
                  logger.AUTH)
     logout(request)
Exemplo n.º 15
0
def delete_folder(destination_path):
    shutil.rmtree(destination_path, ignore_errors=True)
    logger.write('Удаление папки "' + destination_path + '"', logger.FILE)
Exemplo n.º 16
0
def rename_folder(old, new):
    os.rename(old, new)
    logger.write('Перименование папки "' + old + '" -> "' + new + '".',
                 logger.FILE)
Exemplo n.º 17
0
 def delete_index(self, index_name):
     """ удаление индекса """
     logger.write(
         'Пользователь запросил удаление индекса "' + str(index_name) + '"',
         logger.ELASTIC)
     self.index_manager.delete_index_by_name(index_name)
Exemplo n.º 18
0
 def get_all_indices(self):
     """ возвращает все индексы в эластике """
     logger.write('Пользователь запросил Список всех индексов',
                  logger.ELASTIC)
     return self.index_manager.get_all()