Files
PORTAL_COD2/src/watcher/views.py
T

54 lines
2.2 KiB
Python

from django.forms import model_to_dict
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from .models import *
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from django.views.generic import ListView
from .serializers import *
from datetime import date
from django.db.models import Sum
from userauth.models import *
import pandas as pd
# Create your views here. visitdate__year='2023', visitdate__month='01', visitdate__day='21'
class Counter(ListAPIView):
permission_classes = (AllowAny,)
serializer_class = CountSerializer
def get(self, request):
res = CountVisitor.objects.filter(visitdate__range=['2023-01-01', '2023-12-31']).annotate(Sum('count'))
result = CountSerializer(res, many=True).data
return Response(result)
def post(self, request):
myfullPath = request.data['fullPath']
if "?" in myfullPath:
myfullPath= myfullPath.split("?")[0]
page, create = Pages.objects.get_or_create(page=request.data['page'], fullPath=myfullPath, ico=request.data['ico'])
if request.data['user__id'] is not None:
watch,create = CountVisitor.objects.get_or_create(user = User(id=request.data['user__id']),pages=page, visitdate=date.today())
else:
watch,create = CountVisitor.objects.get_or_create(user__id__isnull=True, pages=page, visitdate=date.today())
watch.count+=1
watch.save()
res = {"totalvisit": CountVisitor.objects.filter(pages=page.id).aggregate(Sum('count'))['count__sum'],
"visittoday":CountVisitor.objects.filter(visitdate=date.today(), pages=page.id).aggregate(Sum('count'))['count__sum'],
"uniqtoday" : CountVisitor.objects.filter(visitdate=date.today(), pages=page.id).count()
}
return Response(res)
class SelectedLinksAPIView(ListAPIView):
def get(self, request):
user = User.objects.get(username=self.request.user)
res = CountVisitor.objects.values('pages__page','pages__fullPath','pages__ico').filter(user_id=user).annotate(Sum('count')).exclude(pages__fullPath='/')
sort = res.order_by('-count__sum')[:20]
return Response(sort)