new seriliazer fields and views for blog with ip

This commit is contained in:
Parsa Nazer
2025-01-29 16:33:20 +03:30
parent 3909b6d21f
commit 0aaac1e9c8
2 changed files with 27 additions and 3 deletions
+25 -1
View File
@@ -45,10 +45,34 @@ class AllBlogView(APIView):
class BlogView(APIView):
authentication_classes = []
serializer_class = BlogSerilizer
def get_client_ip(self, request):
"""Helper function to get the client IP from request headers."""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip
def get(self, request, pk):
blog = get_object_or_404(BlogModel, pk=pk)
if blog.is_published:
# Track views using session
client_ip = self.get_client_ip(request)
session_key = f'viewed_blog_{pk}_{client_ip}'
if not request.session.get(session_key):
blog.views += 1
blog.save()
print(f'views {blog.views}')
print(session_key)
request.session[session_key] = True
request.session.set_expiry(3600)
blog_ser = self.serializer_class(instance=blog, context={'request': request})
return Response(blog_ser.data, status=status.HTTP_200_OK)
else:
return Response({'detail': 'object with the given id does not exiest or its not published yet'}, status=status.HTTP_404_NOT_FOUND)
return Response({'detail': 'object with the given id does not exist or is not published yet'},
status=status.HTTP_404_NOT_FOUND)