Home > Enterprise >  How can i access current session data outside django view function?
How can i access current session data outside django view function?

Time:01-20

I am using SessionStore object to store session data, how can i get current session data from Session table without using pk as we dont know pk of record stored in table.

Here is the code

ldap.py

from django.contrib.sessions.backends.db import SessionStore
s = SessionStore()

class LDAPPBackend(ModelBackend):
    def authenticate(self, *args, **kwargs):
        **s['memberOf']** = "Star Group" #**setting session**
        s.create()

serializer.py

from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from django.contrib.sessions.models import Session
**s = Session.objects.get(pk="")** #**how can i know current logged in user session pk???**
class TokenObtainPairPatchedSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data['attr'] = attrs
        **data['memberOf'] = s** # **How can i get current session data here??**
        return data

How can i achieve this???

CodePudding user response:

You can access the request in serializer because generic view passes request to serializer through context:

class TokenObtainPairPatchedSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data['attr'] = attrs
        session = self.context.get('request').session 
        # rest of the code
        return data

You can access it because TokenObtainPairView is derived from GenericAPIView.

  • Related