legacy/pairent_backend/pairent_app/views.py

154 lines
5.8 KiB
Python
Raw Normal View History

from rest_framework import viewsets
2023-05-07 11:48:53 +02:00
from rest_framework.response import Response
2023-05-11 01:52:32 +02:00
from rest_framework.views import APIView, View
from rest_framework.request import Request
2023-05-15 13:01:57 +02:00
from django.http import HttpResponseBadRequest, HttpResponse
2023-05-15 06:54:30 +02:00
from django.db.models.query import QuerySet
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
2023-05-09 10:32:18 +02:00
from .models import Apartament, User
from .serializer import (ApartamentListSerializer,
ApartamentDetailSerializer,
2023-05-15 05:12:05 +02:00
PsychTestAddResultSerializer,
2023-05-15 06:54:30 +02:00
PublicUserSerializer)
2023-05-01 12:39:34 +02:00
2023-05-15 13:01:57 +02:00
import json, math, random, re, requests
2023-05-01 12:39:34 +02:00
class ApartamentViewSet(viewsets.ReadOnlyModelViewSet):
"""Вывод списка квартир или отдельной квартиры"""
2023-05-01 12:39:34 +02:00
def get_queryset(self):
2023-05-01 12:39:34 +02:00
apartaments = Apartament.objects.all()
return apartaments
def get_serializer_class(self):
if self.action == 'list':
return ApartamentListSerializer
elif self.action == "retrieve":
2023-05-07 11:48:53 +02:00
return ApartamentDetailSerializer
class ApartamentGetManyViewSet(viewsets.ReadOnlyModelViewSet):
2023-05-07 11:48:53 +02:00
"""Вывод отдельных квартир для сравнения"""
2023-05-09 13:03:37 +02:00
def get_queryset(self): # получение id квартир для избранного или сравнения
2023-05-09 10:32:18 +02:00
pk = self.request.query_params.get("pk", None) # получение id пользователя
if self.action == "retrieve": # если для страницы сравнения
apartaments_id = User.objects.get(pk=pk).apartaments_for_comparison.split(',') # получение id квартир
elif self.action == "list": # если для страницы избранного
apartaments_id = User.objects.get(pk=pk).favorites_apartaments.split(',') # получение id квартир
2023-05-09 13:03:37 +02:00
queryset = []
for i in apartaments_id:
queryset.append(Apartament.objects.get(pk=i))
return queryset
2023-05-09 10:32:18 +02:00
2023-05-09 11:05:47 +02:00
def retrieve(self, request, *args, **kwargs):
2023-05-09 13:03:37 +02:00
queryset = self.get_queryset()
2023-05-09 11:05:47 +02:00
apartaments = []
2023-05-09 13:03:37 +02:00
for i in queryset:
apartaments.append(ApartamentDetailSerializer(i).data)
return Response({'results': apartaments})
def list(self, request, *args, **kwargs):
queryset = self.get_queryset()
apartaments = []
for i in queryset:
apartaments.append(ApartamentListSerializer(i).data)
2023-05-09 11:05:47 +02:00
return Response({'results': apartaments})
2023-05-11 01:52:32 +02:00
class ApartmentFilter(viewsets.ViewSet):
"""Вывод списка квартир или отдельной квартиры"""
def list(self, req: Request):
filters = dict(req.data);
2023-05-11 15:11:38 +02:00
unfiltered = Apartament.objects.all();
2023-05-11 01:52:32 +02:00
filtered = [];
2023-05-11 15:11:38 +02:00
# TODO: Some better converting practice?
filters['price_range']['from'] = int(filters['price_range']['from']);
filters['price_range']['to'] = int(filters['price_range']['to']);
filters['area_range']['from'] = int(filters['area_range']['from']);
filters['area_range']['to'] = int(filters['area_range']['to']);
filters['rooms'] = int(filters['rooms'])
2023-05-11 01:52:32 +02:00
for entry in unfiltered:
2023-05-11 15:11:38 +02:00
if (filters['price_range']['from'] >= entry.price and (filters['price_range']['to'] != -1 and filters['price_range']['to'] <= entry.price)):
2023-05-11 01:52:32 +02:00
continue;
2023-05-11 15:11:38 +02:00
if (filters['area_range']['from'] >= entry.perimetrs and (filters['area_range']['to'] != -1 and filters['area_range']['to'] <= entry.perimetrs)):
2023-05-11 01:52:32 +02:00
continue;
2023-05-11 15:11:38 +02:00
if (filters['rooms'] != -1 and entry.rooms != filters['rooms']):
2023-05-11 01:52:32 +02:00
continue;
filtered.append(entry);
return Response(ApartamentListSerializer(filtered, many=True).data);
class PsychTestAddResultViewSet(viewsets.ViewSet):
2023-05-12 15:01:55 +02:00
def get_object(self, pk):
return User.objects.filter(pk=pk)
def update(self, request, pk):
user = self.get_object(pk)
result = request.query_params.get("result", None)
user.update(psych_test_result=result)
2023-05-12 15:01:55 +02:00
return Response(PsychTestAddResultSerializer(User.objects.get(pk=pk)).data)
2023-05-15 05:12:05 +02:00
class CompatibleUsersView(viewsets.ViewSet):
def list(self, req: Request):
user_data = dict(req.data);
2023-05-15 06:54:30 +02:00
# TODO: Verify auth
vvsu_login = user_data['openid'];
# Exclude already viewed users
exclude = [];
if ('exclude' in user_data.keys()):
exclude = user_data['exclude'];
try:
validate_email(vvsu_login);
except ValidationError:
return Request({'error': 'bad login'}, 400);
try:
this_user = User.objects.get(openid_addr=vvsu_login);
except User.DoesNotExist:
return Response({'error': 'user not found'}, 404);
score = this_user.psych_test_result;
users_query = User.objects.all();
users = [];
for user in users_query:
if (abs(user.psych_test_result - score) < 20):
users.append(PublicUserSerializer(user).data);
random.shuffle(users);
users = users[:7];
for i in range(3):
users.append(PublicUserSerializer(random.choice(users_query)).data);
random.shuffle(users);
2023-05-15 13:01:57 +02:00
return Response(users);
def VVSUAuthProxy(req: Request):
proxy = 'https://vvsu.ru/connect' + req.path[len('/api/auth/vvsu'):];
preq = requests.request(req.method, proxy, headers={
'User-Agent': 'OIDC Client / Pairent',
'Origin': 'http://pairent.vvsu.ru',
'Referer': 'http://pairent.vvsu.ru'
});
resp = HttpResponse(preq.content);
resp.headers['Content-Type'] = preq.headers['Content-Type'];
return resp;