def post(self, request, uidb64, token, *args, **kwargs): user = self.get_user(uidb64) if self.check_user_and_token(user, token): form = SetPasswordForm(user, request.POST) if form.is_valid(): form.save() if len(user.email): # Формируем параметры email param_email = { 'to': [user.email], 'context': { 'user': model_to_dict(user, fields=[field.name for field in user._meta.fields]), }, 'subject': APP_SUBJECT_TO_RESTORE_PASSWORD, 'tpl_name': 'mail/password_email_confirm.html', } # Отправляем email send_template_mail.apply_async(kwargs=param_email) return HttpResponseRedirect(reverse('reset_confirm')) else: return HttpResponse(render_page('confirm_passwd', {'error': dict(((i[0], i[1][0]) for i in form.errors.items()))})) return HttpResponse(render_page('confirm_passwd', {'error': {'token': True}}))
def get(self, *args, **kwargs): today = timezone.datetime.now() data = {} casts = casts_models.Casts.objects.filter(start__gte=today - timezone.timedelta(hours=3)).order_by('start')[:12] data['casts'] = vbCast(casts).data data['casts_tags'] = [] return HttpResponse(render_page('casts_list', data))
def post(self, request, *args, **kwargs): form = PasswordResetForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email', False) active_users = User.objects.filter(username__iexact=email, email__isnull=False, is_active=True) for user in active_users: # Save hash o_hash = UsersHash(user=user, hash_type=APP_USER_HASH_PASSWD) o_hash.save() # Формируем параметры email param_email = { 'to': [user.email], 'context': { 'url': 'http://{host}{url}'.format( host=HOST, url=reverse('reset_pwd', args=(urlsafe_base64_encode(str(user.id)), o_hash.hash_key)), ), 'user': model_to_dict(user, fields=[field.name for field in user._meta.fields]), }, 'subject': APP_SUBJECT_TO_RESTORE_PASSWORD, 'tpl_name': 'mail/password_email_restore.html', } # Отправляем email send_template_mail.apply_async(kwargs=param_email) return HttpResponseRedirect(reverse('reset_done')) else: HttpResponse(render_page('reset_passwd', {'error': u'Введите корректный email'}))
def get(self, request, **kwargs): resp_dict = { 'user': vbUserProfile(request.user.profile).data, 'error': request.GET.get('e', None) } return HttpResponse(render_page('profile', resp_dict))
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)
def post(self, *args, **kwargs): register_form = CustomRegisterForm(data=self.request.POST) if register_form.is_valid(): user = register_form.save() kw = { 'token': user.auth_token.key, '_': timezone.now().date().strftime("%H%M%S"), } url_redirect = url_with_querystring(reverse('tokenize'), **kw) # url = "http://{host}{url}".format(host=self.request.get_host(), url=url_redirect) # context = {'user': user, 'redirect_url': url} # # kw = dict(subject=APP_SUBJECT_TO_CONFIRM_REGISTER, # tpl_name='confirmation_register.html', # context=context, # to=[user.email]) # send_template_mail.apply_async(kwargs=kw) transaction.commit() return redirect(url_redirect) else: transaction.rollback() resp_dict = {'error': dict(((i[0], i[1][0]) for i in register_form.errors.items()))} return HttpResponse(render_page('register', resp_dict))
def post(self, request, **kwargs): uprofile_form = UsersProfileForm(data=request.POST, instance=request.user) if uprofile_form.is_valid(): try: uprofile_form.save() except Exception as e: return HttpResponse(render_page('profile', {'error': e})) return redirect('profile_view')
def feed_view(request): if request.user.is_authenticated(): # Сериализуем try: o_feed = vbFeedElement(calc_feed(request.user.id), many=True).data except Exception, e: raise Http404 return HttpResponse(render_page('feed', {'feed': o_feed}))
def send_template_mail(subject, tpl_name, context, to, jade_render=False): if jade_render: tpl = render_page(tpl_name, context, False) else: tpl = render_to_string(tpl_name, context) msg = EmailMultiAlternatives(subject=subject, to=to) msg.attach_alternative(tpl, 'text/html') msg.send()
def get(self, *args, **kwargs): if self.request.user.is_authenticated(): # Сериализуем try: o_feed = vbFeedElement(calc_feed(self.request.user.id), many=True).data except Exception, e: raise Http404 return HttpResponse(render_page('feed', {'feed': o_feed}))
def get(self, *args, **kwargs): resp_dict = film_to_view(kwargs['film_id'], similar=True) # Trailer trailer = film_model.FilmExtras.get_trailer_by_film(kwargs['film_id'], first=True) if not trailer is None: resp_dict['trailer'] = trailer.url return HttpResponse(render_page('film', {'film': resp_dict}))
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)
def film_view(request, film_id, *args, **kwargs): resp_dict, o_film = film_to_view(film_id) resp_dict['similar'] = calc_similar(o_film) # Trailer trailer = film_model.FilmExtras.get_trailer_by_film(film_id, first=True) if not trailer is None: resp_dict['trailer'] = trailer.url return HttpResponse(render_page('film', {'film': resp_dict}))
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')
def post(self, request, **kwargs): form = UsersProfileForm(data=request.POST, files=request.FILES, instance=request.user) if form.is_valid(): profile = form.save(commit=False, send_email=True) image = form.cleaned_data['avatar'] if isinstance(profile, dict): t = vbUserProfile(request.user.profile).data t.update(request.POST.dict()) return HttpResponse(render_page('profile', {'user': t, 'error': profile})) if image: up = UsersPics.objects.create(user=request.user, type=APP_USER_PIC_TYPE_LOCAL) up.image = image # чтобы в имени был id up.save() profile.userpic_id = up.pk profile.save() return HttpResponse(render_page('profile', {'user': vbUserProfile(profile).data})) return redirect('profile_view')
def get(self, request, *args, **kwargs): key = request.GET.get(APP_USER_ACTIVE_KEY, None) if key is None: raise Http404 user_hash = UsersHash.get_by_hash(hash_key=key, hash_type=[APP_USER_HASH_EMAIL, APP_USER_HASH_REGISTR]) if user_hash is None: raise Http404 profile = user_hash.user.profile profile.confirm_email = True profile.save() return HttpResponse(render_page('confirm_email', {}))
def post(self, *args, **kwargs): login_form = AuthenticationForm(data=self.request.POST) if login_form.is_valid(): user = login_form.get_user() kw = { 'token': user.auth_token.key, '_': timezone.now().date().strftime("%H%M%S") } if self.request.META['HTTP_HOST'] == HOST and not HOST+'/login' in self.request.META['HTTP_REFERER']: kw.update(back_url=self.request.META['HTTP_REFERER']) url = url_with_querystring(reverse('tokenize'), **kw) return HttpResponseRedirect(url) else: return HttpResponse(render_page('login', {'error': u'Введите корректный логин или пароль'}))
def get(self, *args, **kwargs): cast_id = int(kwargs.get('cast_id', None)) today = timezone.datetime.now() data = {} cast = casts_models.Casts.objects.get(id=cast_id) chat_items = casts_models.CastsChatsMsgs.objects.filter(cast_id=cast_id) msgs_list = [] for item in chat_items: user = {'id': item.user.id, 'name': u' '.join([item.user.first_name, item.user.last_name]), 'avatar': ""} msgs_list.append({'user': user, 'text': item.text}) other_casts = casts_models.Casts.objects.filter(start__gte=today - timezone.timedelta(hours=3)).order_by('start').exclude(id=cast_id)[:12] data['cast'] = vbCast(cast).data data['cast']['chat_items'] = msgs_list data['online_casts'] = vbCast(other_casts).data return HttpResponse(render_page('cast', data))
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)
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')
def get(self, *args, **kwargs): back_url = self.request.GET['back_url'] if 'back_url' in self.request.GET else reverse('index_view') token = self.request.GET['token'] if 'token' in self.request.GET else self.request.user.auth_token.key try: user = Token.objects.get(key=token).user except Token.DoesNotExist: return HttpResponse(render_page('login', {'error': u'Неверный токен пользователя'})) session = create_new_session(user) response = HttpResponseRedirect(back_url) max_age = 30 * 24 * 60 * 60 # two weeks expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT") response.set_cookie('x-token', token, max_age=max_age, expires=expires) response.set_cookie('x-session', session.token.key, max_age=max_age, expires=expires) response.delete_cookie('sessionid') return response
def post(self, *args, **kwargs): data = self.request.POST login_form = AuthenticationForm(data=data) if login_form.is_valid(): user = login_form.get_user() kw = { 'token': user.auth_token.key, '_': timezone.now().date().strftime("%H%M%S") } if self.request.META['HTTP_HOST'] == HOST and not HOST+'/login' in self.request.META['HTTP_REFERER']: kw.update(back_url=self.request.META['HTTP_REFERER']) url = url_with_querystring(reverse('tokenize'), **kw) return HttpResponseRedirect(url) else: return HttpResponse(render_page('login', {'error': u'Введите корректный логин или пароль'}))
def post(self, *args, **kwargs): register_form = CustomRegisterForm(data=self.request.POST) if register_form.is_valid(): committed = False try: user = register_form.save(send_email=True) url_redirect = url_with_querystring( reverse('tokenize'), **{ 'token': user.auth_token.key, '_': timezone.now().date().strftime("%H%M%S"), } ) transaction.commit() committed = True return redirect(url_redirect) except Exception, e: resp_dict = {'error': 'Ошибка в сохранении данных.'} return HttpResponse(render_page('register', resp_dict)) finally:
def get(self, *args, **kwargs): back_url = self.request.GET['back_url'] if 'back_url' in self.request.GET else reverse('index_view') token = self.request.GET['token'] if 'token' in self.request.GET else self.request.user.auth_token.key try: user = Token.objects.get(key=token).user except Token.DoesNotExist: return HttpResponse(render_page('login', {'error': u'Неверный токен пользователя'})) session = create_new_session(user) # 30 days in the seconds max_age = 30 * 86400 # Set expires expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age) expires = datetime.datetime.strftime(expires, "%a, %d-%b-%Y %H:%M:%S GMT") # Set Response response = HttpResponseRedirect(back_url) response.set_cookie('x-token', token, max_age=max_age, expires=expires) response.set_cookie('x-session', session.key, max_age=max_age, expires=expires) response.delete_cookie('sessionid') return response
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}))
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}))
def get(self, *args, **kwargs): return HttpResponse(render_page('register', {}))
def get(self, *args, **kwargs): response = HttpResponse(render_page('login', {})) response.delete_cookie("x-session") response.delete_cookie("x-token") return response
def password_reset_confirm(request): return HttpResponse(render_page('confirm_passwd', {'confirm': True}))
def password_reset_done(request): return HttpResponse(render_page('reset_passwd', {'send': True}))
return redirect('index_view') def search_view(request, *args, **kwargs): # Устанавливаем ответ по умолчанию и вызываем сериализатор поиска resp_dict = { 'films': [], } if request.REQUEST.get('text'): try: resp_dict['films'] = SearchFilmsView.as_view()( request, use_thread=True).data resp_dict['search_text'] = request.REQUEST.get('text') except Exception, e: pass return HttpResponse(render_page('search', resp_dict)) def get_recommend_film(request): try: o_recommend = SearchFilmsView.as_view()(request, use_thread=True, recommend=True).data o_recommend = o_recommend['items'] except Exception, e: o_recommend = [] return o_recommend
def get(self, request, uidb64, token, *args, **kwargs): user = self.get_user(uidb64) if self.check_user_and_token(user, token): return HttpResponse(render_page('confirm_passwd', {})) return HttpResponse(render_page('confirm_passwd', {'error': {'token': True}}))
def get(self, request, **kwargs): if isinstance(request.user, AnonymousUser): return redirect("login_view") resp_dict = {'user': vbUserProfile(request.user.profile).data, 'error': request.GET.get('e', None)} return HttpResponse(render_page('profile', resp_dict))
def get(self, request, *args, **kwargs): if not request.user.is_authenticated(): return HttpResponse(render_page('reset_passwd', {})) raise Http404
def get(self, *args, **kwargs): return HttpResponse(render_page('restore_password', {}))
return redirect(url_redirect) except Exception, e: resp_dict = {'error': 'Ошибка в сохранении данных.'} return HttpResponse(render_page('register', resp_dict)) finally: if not committed: transaction.rollback() else: transaction.rollback() resp_dict = {'error': dict(((i[0], i[1][0]) for i in register_form.errors.items()))} return HttpResponse(render_page('register', resp_dict)) class LoginUserView(View): def get(self, *args, **kwargs): response = HttpResponse(render_page('login', {})) response.delete_cookie("x-session") response.delete_cookie("x-token") return response def post(self, *args, **kwargs): data = self.request.POST login_form = AuthenticationForm(data=data) if login_form.is_valid(): user = login_form.get_user()