Search code examples
pythondjangodjango-authenticationdjango-sessions

Django: Is it okay to generate session_key even when no user is logged in?


Hi just wanna ask: Is it a good practice to generate Django's session_key (sessionid cookie) manually, outside Django's authentication layer?

I am implementing a post hit/page views and post comment mechanism, and I wanna use the sessionid to use for the session field in PostHit and PostComment models. Reason being, I don't wanna create an entire logic for generating custom-made session keys for this purpose since I think Django's session_key is pretty straightforward and is enough to cater the recording of web visitor sessions.

But I suddenly thought maybe the sessionid is appropriate only for logged-in users and shouldn't be generated for unauthenticated visitors. If it is not good anyway, do you have any better ways to generate session keys for both logged-in and anonymous visitors?

Much thanks!

SAMPLE IMPLEMENTATION OF session_key:

class APIDetail__Post(generics.RetrieveUpdateDestroyAPIView):
  queryset           = Post.objects.all().order_by('-publish_date')
  serializer_class   = PostSerializer
  lookup_field       = 'slug'
  permission_classes = [permissions.IsAuthenticatedOrReadOnly]

  def get_queryset(self):
    post_slug = self.request.resolver_match.kwargs['slug']
    post = Post.objects.get(slug=post_slug)
    if post:
        if post.published and post.approved:
            if not self.request.session.session_key:
                self.request.session.create()
                if not PostHit.objects.filter(post=post, session=self.request.session.session_key):
                    view = PostHit(
                        post=post,
                        ip=self.request.META['REMOTE_ADDR'],
                        created=datetime.now(),
                        session=self.request.session.session_key)
                    view.save()
            else:
                if not PostHit.objects.filter(post=post, session=self.request.session.session_key):
                    view = PostHit(
                        post=post,
                        ip=self.request.META['REMOTE_ADDR'],
                        created=datetime.now(),
                        session=self.request.session.session_key)
                    view.save()
    return self.queryset

Solution

  • Session IDs are something that can be used irrespective of an authentication. Don't confuse it with the Auth Token.