コード例 #1
0
def index_view(request):
    # Выбираем 4 новых фильма, у которых есть локации
    NEW_FILMS_CACHE_KEY = 'new_films'
    resp_dict_serialized = cache.get(NEW_FILMS_CACHE_KEY)
    # Расчитываем новинки, если их нет в кеше
    if resp_dict_serialized is None:
        o_film = film_model.Films.get_newest_films()

        # Фильмы показывались => ставим флаг просмотрено в true
        for film in o_film:
            film.was_shown = True
            film.save()

        # Сериализуем новинки и конвертируем результат в строку
        resp_dict_data = vbFilm(o_film,
                                require_relation=False,
                                extend=True,
                                many=True).data
        resp_dict_serialized = json.dumps(resp_dict_data,
                                          cls=DjangoJSONEncoder)

        # Положим результат в кеш
        cache.set(NEW_FILMS_CACHE_KEY, resp_dict_serialized, 86400)

    else:
        resp_dict_data = json.loads(resp_dict_serialized)

    # Найдем relation для фильмов, если пользователь авторизован
    if request.user.is_authenticated():
        o_user = film_model.UsersFilms.objects.filter(
            user=request.user,
            film__in=[item['id'] for item in resp_dict_data])
        o_user = reindex_by(o_user, 'film_id', True)

        for index, item in enumerate(resp_dict_data):
            if item['id'] in o_user:
                resp_dict_data[index]['relation'] = o_user[
                    item['id']].relation_for_vb_film

    # Выборка списка жанров из кеша, если есть
    genres_cache_key = film_model.Genres.get_cache_key()
    genres_data = cache.get(genres_cache_key)

    if genres_data is None:
        try:
            genres_data = list(film_model.Genres.get_grouped_genres())
            cache.set(genres_cache_key, genres_data, 86400)
        except:
            genres_data = []

    # Формируем ответ
    data = {
        'films_new': resp_dict_data,
        'filter_genres': genres_data,

        # Список рекомендуемых фильмов
        'films': get_recommend_film(request),
    }

    return HttpResponse(render_page('index', data), status.HTTP_200_OK)
コード例 #2
0
ファイル: users_films.py プロジェクト: tumani1/vsevi
    def get(self, request, user_id, format=None, *args, **kwargs):
        try:
            user = User.objects.get(pk=user_id)
        except Exception as e:
            return Response({'e': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        page = request.QUERY_PARAMS.get('page', APP_USERS_API_DEFAULT_PAGE)
        per_page = request.QUERY_PARAMS.get('per_page', APP_USERS_API_DEFAULT_PER_PAGE)
        type_ = request.QUERY_PARAMS.get('type', 'all')
        try:
            ftype = films_type[type_]
        except KeyError as e:
            return Response({'e': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        films = Films.objects.filter(uf_films_rel__user=user, type__in=ftype,
                                     uf_films_rel__subscribed=APP_USERFILM_SUBS_TRUE)
        try:
            page = Paginator(films, per_page).page(page)
        except Exception as e:
            return Response({'e': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        serializer = vbFilm(page.object_list, request=self.request, many=True)

        result = {
            'per_page': page.paginator.per_page,
            'page': page.number,
            'total_cnt': page.paginator.count,
            'items': serializer.data,
        }

        return Response(result, status=status.HTTP_200_OK)
コード例 #3
0
    def get(self, request, user_id, format=None, *args, **kwargs):
        try:
            user = User.objects.get(pk=user_id)
        except Exception as e:
            return Response({'e': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        page = request.QUERY_PARAMS.get('page', APP_USERS_API_DEFAULT_PAGE)
        per_page = request.QUERY_PARAMS.get('per_page',
                                            APP_USERS_API_DEFAULT_PER_PAGE)
        type_ = request.QUERY_PARAMS.get('type', 'all')
        try:
            ftype = films_type[type_]
        except KeyError as e:
            return Response({'e': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        films = Films.objects.filter(
            uf_films_rel__user=user,
            type__in=ftype,
            uf_films_rel__subscribed=APP_USERFILM_SUBS_TRUE)
        try:
            page = Paginator(films, per_page).page(page)
        except Exception as e:
            return Response({'e': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        serializer = vbFilm(page.object_list, request=self.request, many=True)

        result = {
            'per_page': page.paginator.per_page,
            'page': page.number,
            'total_cnt': page.paginator.count,
            'items': serializer.data,
        }

        return Response(result, status=status.HTTP_200_OK)
コード例 #4
0
ファイル: tasks.py プロジェクト: tumani1/vsevi
def personal_newsletter():
    # Основные параметры рассылки и контекст
    params_email = {
        'subject': APP_FILMS_PERSON_SUB_EMAIL,
        'tpl_name': u'mail/personal_newsletter.html',
        'context': {},
    }

    # Все пользователи у которых есть email и выбрана недельная рассылка
    o_users = User.objects.filter(is_staff=True).prefetch_related('profile__user')

    # .filter(
    #     email__isnull=False,
    #     profile__ntf_frequency=APP_USERPROFILE_NOTIFICATION_DAY,
    #     profile__confirm_email=True,
    # ).prefetch_related('profile__user')

    for item in o_users:
        # Init data
        feeds = []

        # Выборка ленты друзей
        user_friends = UsersRels.get_all_friends_user(user_id=item.id, flat=True)

        # Проверка длинны
        if len(user_friends):
            # Собираем типы фидов из профиля
            type_film_feed = []

            if item.profile.ntf_frnd_rate:
                type_film_feed.append(FILM_RATE)

            if item.profile.ntf_frnd_comment:
                type_film_feed.append(FILM_COMMENT)

            if item.profile.ntf_frnd_subscribe:
                type_film_feed.append(FILM_SUBSCRIBE)

            if len(type_film_feed):
                feeds = Feed.objects.filter(user__in=user_friends, type__in=type_film_feed)
                feeds = vbFeedElement(feeds, many=True).data

        # Выборка фильмов
        films = Films.objects.filter(uf_films_rel__user=item.id, uf_films_rel__subscribed=APP_USERFILM_SUBS_TRUE)

        # Проверка длинны
        if len(films):
            films = vbFilm(films, many=True).data
        else:
            films = []

        # Update
        params_email['to'] = item.email
        params_email['context'] = {
            'feeds': feeds,
            'films': films,
        }

        # Отправляем email в очередь
        send_template_mail.s(**params_email).apply_async()
コード例 #5
0
    def get(self, request, resource_id, format=None):
        form = PersonFilmographyApiForm(data=request.GET.copy())
        if form.is_valid():
            try:
                c_d = form.cleaned_data
                pfs = PersonsFilms.objects.filter(person__id=resource_id)
                if c_d['type'] != 'all':
                    pfs = pfs.filter(
                        p_type=dict(APP_FILM_PERSON_TYPES_OUR)[c_d['type']])
                films = [pf.film for pf in pfs]
                page = Paginator(films,
                                 per_page=c_d['per_page']).page(c_d['page'])
                data = vbFilm(page.object_list,
                              request=self.request,
                              many=True).data
                result = {
                    'total_cnt': page.paginator.count,
                    'per_page': page.paginator.per_page,
                    'page': page.number,
                    'items': data,
                }
                return Response(result, status=status.HTTP_200_OK)
            except Exception as e:
                return Response(DEFAULT_REST_API_RESPONSE,
                                status=status.HTTP_400_BAD_REQUEST)

        return Response(DEFAULT_REST_API_RESPONSE,
                        status=status.HTTP_400_BAD_REQUEST)
コード例 #6
0
ファイル: views.py プロジェクト: tumani1/vsevi
    def get(self, *args, **kwargs):
        # Выбираем 4 новых фильма, у которых есть локации
        NEW_FILMS_CACHE_KEY = 'new_films'
        resp_dict_serialized = cache.get(NEW_FILMS_CACHE_KEY)
        # Расчитываем новинки, если их нет в кеше
        if resp_dict_serialized is None:
            o_film = film_model.Films.get_newest_films()

            # Фильмы показывались => ставим флаг просмотрено в true
            for film in o_film:
                film.was_shown = True
                film.save()

            # Сериализуем новинки и конвертируем результат в строку
            resp_dict_data = vbFilm(o_film, require_relation=False, extend=True, many=True).data
            resp_dict_serialized = json.dumps(resp_dict_data, cls=DjangoJSONEncoder)

            # Положим результат в кеш
            cache.set(NEW_FILMS_CACHE_KEY, resp_dict_serialized, 86400)

        else:
            resp_dict_data = json.loads(resp_dict_serialized)

        # Найдем relation для фильмов, если пользователь авторизован
        if self.request.user.is_authenticated():
            o_user = film_model.UsersFilms.objects.filter(
                user=self.request.user, film__in=[item['id'] for item in resp_dict_data]
            )
            o_user = reindex_by(o_user, 'film_id', True)

            for index, item in enumerate(resp_dict_data):
                if item['id'] in o_user:
                    resp_dict_data[index]['relation'] = o_user[item['id']].relation_for_vb_film

        # Топ комментариев к фильмам  пользователей
        comments = content_model.Comments.get_top_comments_with_rating(struct=True)

        # Выборка списка жанров из кеша, если есть
        genres_cache_key = film_model.Genres.get_cache_key()
        genres_data = cache.get(genres_cache_key)

        if genres_data is None:
            try:
                genres_data = list(film_model.Genres.get_grouped_genres())
                cache.set(genres_cache_key, genres_data, 86400)
            except:
                genres_data = []

        # Формируем ответ
        data = {
            'films_new': resp_dict_data,
            'filter_genres': genres_data,
            'comments': comments,
            'films': get_recommend_film(self.request),
        }

        return HttpResponse(render_page('index', data), status.HTTP_200_OK)
コード例 #7
0
ファイル: views.py プロジェクト: andrewFisherUa/videobase
def get_film_description(**kwargs):

    NEW_FILMS_CACHE_KEY = 'new_films'

    cached_films = cache.get(NEW_FILMS_CACHE_KEY)

    # Расчитываем новинки, если их нет в кеше
    if cached_films is None:
        films = Films.get_newest_films()

        for film in films:
            # Фильмы показывались => ставим флаг просмотрено в true
            film.was_shown = True
            film.save()

        # Сериализуем новинки и конвертируем результат в строку
        dict_data = vbFilm(films, require_relation=False, extend=True, many=True).data
        json_dict_serialized = json.dumps(dict_data, cls=DjangoJSONEncoder)

        # Положим результат в кеш
        cache.set(NEW_FILMS_CACHE_KEY, json_dict_serialized, 86400)

    else:
        dict_data = json.loads(cached_films)

    list_cost = []
    list_genres = []
    list_poster = []
    list_trailer = []
    list_actor = []
    list_director = []
    list_scriptwriter = []
    list_films = []

    for index, item in enumerate(dict_data):
        film = Films.objects.get(id=item['id'])
        list_films.append(film)
        cost = get_price(film)
        genres = get_genres(film)
        poster, trailer = get_extras(film, **kwargs)
        list_persons_by_film = get_person(film)

        # Add Cost and genres
        list_cost.append(cost)
        list_genres.append(genres)

        # Add persons
        list_actor.append(list_persons_by_film[0])
        list_director.append(list_persons_by_film[1])
        list_scriptwriter.append(list_persons_by_film[2])

        # Add poster and trailer
        list_poster.append(poster)
        list_trailer.append(trailer)

    return zip(list_films, list_actor, list_director, list_poster, list_trailer, list_scriptwriter, list_cost, list_genres)
コード例 #8
0
ファイル: tasks.py プロジェクト: tumani1/vsevi
def best_of_the_best_this_week():
    curr_dt = datetime.now()

    # Выборка фильмов
    new_films = Films.get_newest_films(limit=10)
    new_films = vbFilm(new_films, many=True, require_relation=False).data

    # Выборка сериалов
    serials = []

    # Основные параметры рассылки и контекст
    params_email = {
        'jade_render': True,
        'subject': APP_FILMS_WEEK_SUB_EMAIL,
        'tpl_name': 'week_newsletter',
        'context': {
            'films': new_films,
            'serials': serials,
            'casts': {
                'old': [],
                'future': [],
            },
        },
    }

    # Все пользователи у которых есть email и выбрана недельная нотификация
    o_users = User.objects.filter(is_staff=True).prefetch_related('profile__user')

    # .filter(
    #     email__isnull=False,
    #     profile__ntf_frequency=APP_USERPROFILE_NOTIFICATION_WEEK,
    #     profile__confirm_email=True,
    # ).prefetch_related('profile__user')

    # Вычисляем воскресенье вечер
    start_dt = curr_dt - timedelta(days=7)
    end_dt = curr_dt + timedelta(days=6 - curr_dt.weekday())
    end_dt.replace(hour=23, minute=59, second=59)

    # Вставка параметров трансляции
    params_email['context']['casts']['old'] = vbCast(Casts.best_old_casts(start_dt=start_dt, end_dt=curr_dt), many=True).data
    params_email['context']['casts']['future'] = vbCast(Casts.best_future_casts(start_dt=curr_dt, end_dt=end_dt), many=True).data

    if settings.DEBUG:
        data_json = json.dumps(params_email, cls=DjangoJSONEncoder)
        file = open('data.json', 'w')
        file.write(data_json)
        file.close()

    for item in o_users:
        params_email.update({'to': [item.email,]})

        # Отправляем email в очередь
        send_template_mail.s(**params_email).apply_async()
コード例 #9
0
def playlist_view(request, film_id=None, *args, **kwargs):
    if not film_id:
        film_id = 1

    if request.user.is_authenticated():
        # Init data
        film_data = {}
        playlist = {'id': 0}
        film_id = int(film_id)

        # Выборка плейлиста
        playlist_data = film_model.Films.objects.\
            filter(uf_films_rel__user=request.user.id, uf_films_rel__status=APP_USERFILM_STATUS_PLAYLIST).\
            order_by('uf_films_rel__created')

        # Обработка плейлиста
        len_playlist = len(playlist_data)
        if len_playlist > 0:
            if film_id > len(playlist_data) or film_id < 1:
                return redirect('playlist_film_view', film_id=1)

            def arrow_data(data, f_id):
                return {'id': f_id, 'name': data.name}

            if film_id < len(playlist_data):
                playlist['next'] = arrow_data(playlist_data[film_id],
                                              film_id + 1)

            if film_id > 1:
                playlist['previous'] = arrow_data(playlist_data[film_id - 2],
                                                  film_id - 1)

            film = playlist_data[film_id - 1]
            film_data, o_film = film_to_view(film.id)

        # Update playlist
        playlist.update({
            'id': film_id,
            'film': film_data,
            'total_cnt': len_playlist,
            'items': vbFilm(playlist_data, many=True).data,

            # Список рекомендуемых фильмов
            'films': get_recommend_film(request),
        })

        return HttpResponse(
            render_page('playlist', {
                'playlist': playlist,
                'film': film_data
            }))

    return redirect('login_view')
コード例 #10
0
ファイル: views.py プロジェクト: tumani1/vsevi
def film_to_view(film_id, similar=False):
    o_film = film_model.Films.objects.filter(pk=film_id).prefetch_related('genres', 'countries')

    if not len(o_film):
        raise Http404

    o_film = o_film[0]
    resp_dict = vbFilm(o_film, extend=True)

    try:
        resp_dict = resp_dict.data
    except Exception, e:
        raise Http404
コード例 #11
0
def film_to_view(film_id):
    o_film = film_model.Films.objects.filter(pk=film_id).prefetch_related(
        'genres', 'countries')

    if not len(o_film):
        raise Http404

    o_film = o_film[0]
    resp_dict = vbFilm(o_film, extend=True)

    try:
        resp_dict = resp_dict.data
    except Exception, e:
        raise Http404
コード例 #12
0
ファイル: views.py プロジェクト: andrewFisherUa/videobase
    def get(self, *args, **kwargs):
        try:
            user_id = self.kwargs['user_id']
        except KeyError:
            return HttpResponseBadRequest()

        try:
            user = User.objects.get(pk=user_id)
        except User.DoesNotExist:
            raise Http404

        try:
            uvb = vbUser(user, extend=True, genres=True, friends=True)
            days = (timezone.now() - uvb.data['regdate']).days
            how_long = numeral.get_plural(days, (u'день', u'дня', u'дней'))

            default_user = uvb.data
            default_user.update({
                'regdate': uvb.data['regdate'].strftime("%Y-%m-%d"),
                'how_long': how_long
            })

            films = Films.objects.filter(uf_films_rel__user=user, uf_films_rel__subscribed=APP_USERFILM_SUBS_TRUE)
            films = Paginator(films, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vbf = vbFilm(films.object_list, many=True)

            actors = Persons.objects.filter(up_persons_rel__user=user, pf_persons_rel__p_type=APP_PERSON_ACTOR).distinct('id')
            actors = Paginator(actors, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vba = vbPerson(actors.object_list, many=True)

            directors = Persons.objects.filter(up_persons_rel__user=user, pf_persons_rel__p_type=APP_PERSON_DIRECTOR).distinct()
            directors = Paginator(directors, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vbd = vbPerson(directors.object_list, many=True)

            # Сериализуем
            o_feed = vbFeedElement(calc_feed(user.id), many=True).data

            default_user.update({
                'films': vbf.data,
                'actors': vba.data,
                'feed': o_feed,
                'directors': vbd.data,
            })

            return HttpResponse(render_page('user', {'user': default_user}))

        except Exception as e:
            return HttpResponseServerError(e)
コード例 #13
0
ファイル: views.py プロジェクト: tumani1/vsevi
    def get(self, *args, **kwargs):
        try:
            user_id = self.kwargs['user_id']
        except KeyError:
            return HttpResponseBadRequest()

        try:
            user = User.objects.get(pk=user_id)
        except User.DoesNotExist:
            raise Http404

        try:
            uvb = vbUser(user, extend=True, genres=True, friends=True)
            days = (timezone.now() - uvb.data['regdate']).days
            how_long = numeral.get_plural(days, (u'день', u'дня', u'дней'))

            default_user = uvb.data
            default_user.update({
                'regdate': uvb.data['regdate'].strftime("%Y-%m-%d"),
                'how_long': how_long
            })

            films = Films.objects.filter(uf_films_rel__user=user, uf_films_rel__subscribed=APP_USERFILM_SUBS_TRUE)
            films = Paginator(films, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vbf = vbFilm(films.object_list, many=True)

            actors = Persons.objects.filter(up_persons_rel__user=user, pf_persons_rel__p_type=APP_PERSON_ACTOR).distinct('id')
            actors = Paginator(actors, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vba = vbPerson(actors.object_list, many=True)

            directors = Persons.objects.filter(up_persons_rel__user=user, pf_persons_rel__p_type=APP_PERSON_DIRECTOR).distinct()
            directors = Paginator(directors, APP_USERS_API_DEFAULT_PER_PAGE).page(APP_USERS_API_DEFAULT_PAGE)
            vbd = vbPerson(directors.object_list, many=True)

            # Сериализуем
            o_feed = vbFeedElement(calc_feed(user.id), many=True).data

            default_user.update({
                'films': vbf.data,
                'actors': vba.data,
                'feed': o_feed,
                'directors': vbd.data,
            })

            return HttpResponse(render_page('user', {'user': default_user}))

        except Exception as e:
            return HttpResponseServerError(e)
コード例 #14
0
ファイル: views.py プロジェクト: tumani1/vsevi
    def get(self, *args, **kwargs):
        film_id = kwargs.get('film_id', 1)
        if self.request.user.is_authenticated():
            # Init data
            film_data = {}
            playlist = {'id': 0}
            film_id = int(film_id)

            # Выборка плейлиста
            playlist_data = film_model.Films.objects.\
                filter(uf_films_rel__user=self.request.user.id, uf_films_rel__status=APP_USERFILM_STATUS_PLAYLIST).\
                order_by('uf_films_rel__created')

            # Обработка плейлиста
            len_playlist = len(playlist_data)
            if len_playlist > 0:
                if film_id > len(playlist_data) or film_id < 1:
                    return redirect('playlist_film_view', film_id=1)

                def arrow_data(data, f_id):
                    return {'id': f_id, 'name': data.name}

                if film_id < len(playlist_data):
                    playlist['next'] = arrow_data(playlist_data[film_id], film_id+1)

                if film_id > 1:
                    playlist['previous'] = arrow_data(playlist_data[film_id-2], film_id-1)

                film = playlist_data[film_id-1]
                film_data = film_to_view(film.id)

            # Update playlist
            playlist.update({
                'id': film_id,
                'film': film_data,
                'total_cnt': len_playlist,
                'items': vbFilm(playlist_data, many=True).data,

                # Список рекомендуемых фильмов
                'films': get_recommend_film(self.request),
            })

            return HttpResponse(render_page('playlist', {'playlist': playlist, 'film': film_data}))

        return redirect('login_view')
コード例 #15
0
ファイル: persons_filmography.py プロジェクト: tumani1/vsevi
    def get(self, request, resource_id, format=None):
        form = PersonFilmographyApiForm(data=request.GET.copy())
        if form.is_valid():
            try:
                c_d = form.cleaned_data
                pfs = PersonsFilms.objects.filter(person__id=resource_id)
                if c_d['type'] != 'all':
                    pfs = pfs.filter(p_type=dict(APP_FILM_PERSON_TYPES_OUR)[c_d['type']])
                films = [pf.film for pf in pfs]
                page = Paginator(films, per_page=c_d['per_page']).page(c_d['page'])
                data = vbFilm(page.object_list, request=self.request, many=True).data
                result = {
                    'total_cnt': page.paginator.count,
                    'per_page': page.paginator.per_page,
                    'page': page.number,
                    'items': data,
                }
                return Response(result, status=status.HTTP_200_OK)
            except Exception as e:
                return Response(DEFAULT_REST_API_RESPONSE, status=status.HTTP_400_BAD_REQUEST)

        return Response(DEFAULT_REST_API_RESPONSE, status=status.HTTP_400_BAD_REQUEST)
コード例 #16
0
ファイル: views.py プロジェクト: tumani1/vsevi
    def get(self, *args, **kwargs):
        try:
            person = film_model.Persons.objects.get(pk=kwargs['resource_id'])
        except film_model.Persons.DoesNotExist:
            raise Http404

        crutch = vbPerson(person, extend=True).data

        # костыль, до починки парсинга этих данных роботом.
        if not crutch.get('birthdate', False):
            d1 = date(1960, 1, 1)
            d2 = date(1980, 12, 12)
            delta = d2 - d1
            delta = delta.days*24*60*60
            seconds = randrange(delta)
            birthdate = (d1 + timedelta(seconds=seconds))
            crutch['birthdate'] = birthdate.strftime('%d %B %Y')
            crutch['years_old'] = date.today().year - birthdate.year

        # Выбираем фильмографию
        pfs = film_model.PersonsFilms.objects.filter(person=person)[:12]
        crutch['filmography'] = vbFilm([pf.film for pf in pfs], many=True).data

        return HttpResponse(render_page('person', {'person': crutch}))
コード例 #17
0
def person_view(request, resource_id):
    try:
        person = film_model.Persons.objects.get(pk=resource_id)
    except film_model.Persons.DoesNotExist:
        raise Http404

    vbp = vbPerson(person, extend=True)
    crutch = vbp.data  # костыль, до починки парсинга этих данных роботом.
    if not vbp.data['birthdate']:
        d1 = date(1960, 1, 1)
        d2 = date(1980, 12, 12)
        delta = d2 - d1
        delta = delta.days * 24 * 60 * 60
        seconds = randrange(delta)
        birthdate = (d1 + timedelta(seconds=seconds))
        crutch['birthdate'] = birthdate.strftime('%d %B %Y')
        crutch['years_old'] = date.today().year - birthdate.year

    pfs = film_model.PersonsFilms.objects.filter(
        person=person)[:12]  # почему-то 12 первых фильмов. Был пагинатор
    vbf = vbFilm([pf.film for pf in pfs], many=True)
    crutch['filmography'] = vbf.data

    return HttpResponse(render_page('person', {'person': crutch}))
コード例 #18
0
def calc_similar(o_film):
    result = []
    try:
        result = vbFilm(film_model.Films.similar_api(o_film), many=True).data
    except Exception, e:
        print "Caught exception {} in calc_similar".format(e)
コード例 #19
0
    def get(self,
            request,
            format=None,
            recommend=False,
            use_thread=False,
            *args,
            **kwargs):
        # Копируем запрос, т.к. в форме его изменяем
        self.get_copy = request.GET.copy()

        if recommend or self.get_copy.get('recommend'):
            self.get_copy['recommend'] = True

        if use_thread:
            self.request = get_current_request()

        # Валидируем форму
        form = SearchForm(data=self.get_copy)

        if form.is_valid():
            # Init data
            filter = self.validation_pagination(self.get_copy.get('page'),
                                                self.get_copy.get('per_page'),
                                                form.cleaned_data)

            self.flag_price = True if (
                'price' in filter and not filter['price'] is None) else False
            location_group = 1 if self.flag_price or filter.get(
                'instock') else 0

            # Init cache params
            use_cache = self.use_cache()
            cache_key = u'{0}({1})'.format(
                self.__class__.__name__, ':'.join([
                    i if isinstance(i, basestring) else str(i)
                    for i in filter.values()
                ]))

            # Проверим, есть ли результат в кеше
            result = cache.get(cache_key) if use_cache else None

            if result is None:
                # Наложение условий фильтрации на фильмы
                o_search = self.search_by_films(filter)

                if location_group > 0:
                    # Список фильмов удовлетворяющий условиям локации
                    list_films_by_content = self.search_by_location(
                        filter, o_search)

                    # Наложение списка локации на выборку фильмов
                    o_search = o_search.filter(id__in=list_films_by_content)

                try:
                    page = Paginator(o_search, per_page=filter['per_page']).\
                        page(filter['page'])
                except Exception, e:
                    return Response({'error': str(e)},
                                    status=status.HTTP_400_BAD_REQUEST)

                # Формируем ответ
                result = {
                    'total_cnt':
                    page.paginator.count,
                    'per_page':
                    page.paginator.per_page,
                    'page':
                    page.number,
                    'items':
                    vbFilm(page.object_list, request=self.request,
                           many=True).data,
                }

                if use_cache:
                    try:
                        cache.set(cache_key, result, 300)
                    except Exception, e:
                        pass
コード例 #20
0
ファイル: views.py プロジェクト: tumani1/vsevi
def calc_similar(film_id, actors, directors, genres, **kwargs):
    result = []
    list_films = []
    exclude_films = []
    cursor = connection.cursor()

    ############################################################################
    # Если авторизован, то список исключающих фильмов
    request = get_current_request()
    if request.user.is_authenticated():
        sql = """
        "films"."id" NOT IN (SELECT "users_films"."film_id" FROM "users_films"
        WHERE "users_films"."user_id" = %s AND ("users_films"."status" = %s OR
        "users_films"."rating" IS NOT NULL))
        """

        exclude_films = film_model.Films.objects.extra(
            where=[sql],
            params=[request.user.id, APP_USERFILM_STATUS_NOT_WATCH],
        ).values_list('id', flat=True)

        exclude_films = list(exclude_films)

    # Исключаем текущий фильм
    exclude_films.append(film_id)

    ############################################################################
    # 4 фильма по рейтингу от режисера и сценариста
    if len(directors):
        list_films = film_model.Films.objects.\
            filter(
                pf_films_rel__person__in=directors,
                pf_films_rel__p_type__in=[APP_PERSON_DIRECTOR, APP_PERSON_SCRIPTWRITER],
                type=APP_FILM_FULL_FILM
            ).exclude(id__in=exclude_films).\
            order_by('-rating_sort').\
            values_list('id', flat=True)[:4]

        list_films = list(list_films)

    ############################################################################
    # 4 фильма по рейтингу от актера
    if len(actors):
        sql = """
        SELECT t1.film_id FROM films AS t0 JOIN first_3_actor_by_film AS t1 ON t0.id=t1.film_id
        WHERE t0.type='{}' AND t1.person_id IN ({}) AND NOT (t0.id IN ({}))
        ORDER BY t0.rating_sort DESC LIMIT 4;
        """.format(APP_FILM_FULL_FILM,
            u','.join([str(i['id']) for i in actors]),
            u','.join([str(i) for i in set(list_films + exclude_films)])
        )

        # Исполнение запроса
        cursor.execute(sql)

        list_films += [row[0] for row in cursor.fetchall()]

    ############################################################################
    # 4 фильма по рейтингу от жанров
    if len(genres):
        sql = ""
        len_genres = len(genres)
        template = "SELECT films_id FROM films_genres where genres_id={}"

        for k, v in enumerate((i['id'] for i in genres), 1):
            sql += template.format(v)
            if k != len_genres:
                sql += " AND films_id IN ("

        if len_genres > 1:
            sql += ')' * (len_genres - 1)

        sql = """
        SELECT films.id FROM films WHERE films.id IN ({}) AND NOT (films.id IN ({}))
        ORDER BY films.rating_sort DESC LIMIT {};
        """.format(
            sql,
            ','.join([str(i) for i in set(list_films + exclude_films)]),
            12 - len(list_films)
        )

        cursor.execute(sql)

        list_films += [row[0] for row in cursor.fetchall()]

    ############################################################################
    # Финальная обработка

    # Закрытие курсора
    cursor.close()

    required_films = 12 - len(list_films)
    films_to_str = ','.join([str(i) for i in list_films])

    sql = ""
    if len(films_to_str):
        sql = "SELECT * FROM films WHERE films.id IN ({})".format(films_to_str)

    # Добираем фильмы, если необходимо
    if required_films:
        if len(films_to_str):
            sql += """ UNION (SELECT * FROM films WHERE films.id NOT IN ({})
             ORDER BY films.rating_sort DESC LIMIT {})
            """.format(films_to_str, required_films)
        else:
            sql = """SELECT * FROM films
            ORDER BY films.rating_sort DESC LIMIT {}""".format(required_films)

    ############################################################################
    # Преобразование данных
    try:
        result = vbFilm(film_model.Films.objects.raw(sql), many=True).data
    except Exception, e:
        print "Caught exception {} in calc_similar".format(e)
コード例 #21
0
ファイル: films_search.py プロジェクト: tumani1/vsevi
    def get(self, request, format=None, recommend=False, use_thread=False, *args, **kwargs):
        # Копируем запрос, т.к. в форме его изменяем
        self.get_copy = request.GET.copy()

        if recommend or self.get_copy.get('recommend'):
            self.get_copy['recommend'] = True

        if use_thread:
            self.request = get_current_request()

        # Валидируем форму
        form = SearchForm(data=self.get_copy)

        if form.is_valid():
            # Init data
            filter = self.validation_pagination(
                self.get_copy.get('page'), self.get_copy.get('per_page'), form.cleaned_data
            )

            self.flag_price = True if ('price' in filter and not filter['price'] is None) else False
            location_group = 1 if self.flag_price or filter.get('instock') else 0

            # Init cache params
            use_cache = self.use_cache()
            cache_key = u'{0}({1})'.format(
                self.__class__.__name__,
                ':'.join([i if isinstance(i, basestring) else str(i) for i in filter.values()])
            )

            # Проверим, есть ли результат в кеше
            result = cache.get(cache_key) if use_cache else None

            if result is None:
                # Наложение условий фильтрации на фильмы
                o_search = self.search_by_films(filter)

                if location_group > 0:
                    # Список фильмов удовлетворяющий условиям локации
                    list_films_by_content = self.search_by_location(filter, o_search)

                    # Наложение списка локации на выборку фильмов
                    o_search = o_search.filter(id__in=list_films_by_content)

                try:
                    page = Paginator(o_search, per_page=filter['per_page']).\
                        page(filter['page'])
                except Exception, e:
                    return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)

                # Формируем ответ
                result = {
                    'total_cnt': page.paginator.count,
                    'per_page': page.paginator.per_page,
                    'page': page.number,
                    'items': vbFilm(page.object_list, request=self.request, many=True).data,
                }

                if use_cache:
                    try:
                        cache.set(cache_key, result, 300)
                    except Exception, e:
                        pass
コード例 #22
0
# coding: utf-8
"""Сценарий позволяет просмотреть в удобном форматированном виде страничку,
которую формирует шаблонизатор jade для определенного человека, Можно переделать на другие сериализаторы.
"""

import os
import sys
from pprint import pprint as pp
from bs4 import BeautifulSoup as BS

sys.path.append(os.path.abspath('../..'))
os.environ["DJANGO_SETTINGS_MODULE"] = "videobase.settings"

from apps.films.models import Persons, PersonsFilms
from apps.films.api.serializers import vbPerson, vbFilm
from noderender import render_page

os.chdir('..')

p = Persons.objects.get(pk=875)
vbp = vbPerson(p, extend=True)
pfs = PersonsFilms.objects.filter(person=p)[:12]
vbf = vbFilm([pf.film for pf in pfs], many=True)

res = render_page('person', {'person': vbp.data, 'filmography': vbf.data})
soup = BS(res)
print(soup.prettify())
コード例 #23
0
    def __get_result(self, film_id, cleaned_data, **kwargs):
        o_film = self.__get_object(film_id, cleaned_data)
        if type(o_film) == Response:
            raise Http404

        return vbFilm(o_film, request=self.request, **cleaned_data)