Beispiel #1
0
 def get(self, request, format=None, resource_id=None):
     try:
         p = Persons.objects.get(pk=resource_id)
         data = vbPerson(p).data
         u = request.user
         if u and u.is_authenticated():
             data = vbPerson(p, user=u).data
         return Response(data, status=status.HTTP_200_OK)
     except:
         return Response(status=status.HTTP_404_NOT_FOUND)
Beispiel #2
0
 def get(self, request, format=None, resource_id=None):
     try:
         p = Persons.objects.get(pk=resource_id)
         data = vbPerson(p).data
         u = request.user
         if u and u.is_authenticated():
             data = vbPerson(p, user=u).data
         return Response(data, status=status.HTTP_200_OK)
     except:
         return Response(status=status.HTTP_404_NOT_FOUND)
Beispiel #3
0
    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)
Beispiel #4
0
    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)
Beispiel #5
0
    def post(self, request, format=None, resource_id=None):
        extend = request.DATA.get('extend', '')
        if extend.lower() == 'true':
            extend = True
        else:
            extend = False

        try:
            p = Persons.objects.get(pk=resource_id)
            data = vbPerson(p, extend=extend).data
            u = request.user
            if u and u.is_authenticated():
                data = vbPerson(p, extend=True, user=u).data
            return Response(data, status=status.HTTP_200_OK)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)
    def get(self, request, film_id, format=None, *args, **kwargs):
        self.get_copy = request.GET.copy()
        form = PersonApiForm(data=self.get_copy)

        if form.is_valid():
            cleaned_data = form.cleaned_data
            person_list = self.__get_object(film_id, cleaned_data)
            if type(person_list) == Response:
                return person_list

            filter = {
                'filter': {
                    'pk__in': person_list
                },
                'offset': cleaned_data['top'],
            }

            if cleaned_data['limit']:
                filter.update(
                    {'limit': cleaned_data['limit'] + cleaned_data['top']})

            o_person = Persons.get_sorted_persons_by_name(**filter)
            serializer = vbPerson(o_person, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

        return Response(form.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #7
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:
            ptype = persons_type[type_]
        except KeyError as e:
            return Response({'e': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        persons = Persons.objects.filter(up_persons_rel__user=user, pf_persons_rel__p_type__in=ptype)
        try:
            page = Paginator(persons, per_page).page(page)
        except Exception as e:
            return Response({'e': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        serializer = vbPerson(page.object_list, user=user, many=True)
        result = {
            'page': page.number,
            'per_page': page.paginator.per_page,
            'items': serializer.data,
            'total_cnt': page.paginator.count,
        }

        return Response(result, status=status.HTTP_200_OK)
Beispiel #8
0
    def post(self, request, format=None, resource_id=None):
        extend = request.DATA.get('extend', '')
        if extend.lower() == 'true':
            extend = True
        else:
            extend = False

        try:
            p = Persons.objects.get(pk=resource_id)
            data = vbPerson(p, extend=extend).data
            u = request.user
            if u and u.is_authenticated():
                data = vbPerson(p, extend=True, user=u).data
            return Response(data, status=status.HTTP_200_OK)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)
    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:
            ptype = persons_type[type_]
        except KeyError as e:
            return Response({'e': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        persons = Persons.objects.filter(up_persons_rel__user=user,
                                         pf_persons_rel__p_type__in=ptype)
        try:
            page = Paginator(persons, per_page).page(page)
        except Exception as e:
            return Response({'e': str(e)}, status=status.HTTP_400_BAD_REQUEST)

        serializer = vbPerson(page.object_list, user=user, many=True)
        result = {
            'page': page.number,
            'per_page': page.paginator.per_page,
            'items': serializer.data,
            'total_cnt': page.paginator.count,
        }

        return Response(result, status=status.HTTP_200_OK)
Beispiel #10
0
 def test_person_api_view_post(self):
     """В силу невозможности расширить PersonFactory нестандартными полями, несуществующими в модели,
     делаем сравнение с сериализованными полями vbPerson, т.к. такие поля возвращаются оттуда(по специф-и).
     """
     UsersApiSessions.objects.create(token=self.s_token)
     headers = self.s_token.key
     response = self.client.post(reverse(
         'person_api_view',
         kwargs={
             'resource_id': self.person_filmography.person.id,
             'format': 'json'
         }),
                                 data={'extend': True},
                                 HTTP_X_MI_SESSION=headers)
     self.assertEqual(response.data['id'],
                      self.person_filmography.person.id)
     self.assertEqual(response.data['photo'],
                      self.person_filmography.person.photo)
     self.assertEqual(response.data['name'],
                      self.person_filmography.person.name)
     self.assertEqual(response.data['birthdate'],
                      self.person_filmography.person.birthdate)
     vbdata = vbPerson(self.person_filmography.person,
                       user=self.user,
                       extend=True).data
     self.assertEqual(response.data['relation'], vbdata['relation'])
     self.assertEqual(response.data['birthplace'], vbdata['birthplace'])
     self.assertEqual(response.data['bio'], vbdata['bio'])
     self.assertEqual(response.data['roles'], vbdata['roles'])
Beispiel #11
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}))
Beispiel #12
0
    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}))
Beispiel #13
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())