advances in TrackUserViewTest

This commit is contained in:
Sam
2021-03-03 12:25:54 +00:00
parent 884fe1e2b5
commit ef5771461c
2 changed files with 49 additions and 22 deletions

View File

@@ -3,9 +3,10 @@ import logging
# Create your views here.
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny
from ipware import get_client_ip
from django.contrib.gis.geoip2 import GeoIP2
@@ -26,13 +27,14 @@ class StatsLogViewSet(viewsets.ModelViewSet):
@api_view(['POST'])
@permission_classes([AllowAny,])
def track_user(request):
"""Track user actions on the site
Params:
{
action: view,
object: {
action_object: {
model: name,
id: 1,
},
@@ -44,21 +46,23 @@ def track_user(request):
# geoip stuff
client_ip, is_routable = get_client_ip(request)
g = GeoIP2()
geo = None
if client_ip != '127.0.0.1':
geo = g.geos(client_ip)
# gather instance data
instance_data = {
'action': data.get('action'),
'user': request.user,
'action_object': data.get('action_object'),
'user': None if request.user.is_anonymous else request.user,
'anonymous': request.user.is_anonymous,
'ip_address': client_ip,
'geo': g.geos(client_ip),
# 'contact' ???
'geo': geo,
}
if data['object'].get('name') == 'product':
instance_data['action_object'] = Product.objects.get(id=data['object'].get('id'))
elif data['object'].get('name') == 'company':
instance_data['action_object'] = Company.objects.get(id=data['object'].get('id'))
if data['action_object'].get('model') == 'product':
instance_data['action_object'] = Product.objects.get(id=data['action_object'].get('id'))
elif data['action_object'].get('model') == 'company':
instance_data['action_object'] = Company.objects.get(id=data['action_object'].get('id'))
if instance_data['action_object'].shop is True:
instance_data['shop'] = True
@@ -66,5 +70,7 @@ def track_user(request):
new_stat = StatsLog.objects.create(**instance_data)
return Response(status=status.HTTP_201_CREATED)
except Exception as e:
import ipdb; ipdb.set_trace()
logging.error(f"Stats could not be created: {str(e)}")
return Response(f"Process could not be registered: {str(type(e))}")
return Response(f"Process could not be registered: {str(type(e))}", status=status.HTTP_406_NOT_ACCEPTABLE)