我使用SessionStore对象来存储会话数据,我如何从会话表中获取当前会话数据而不使用pk,因为我们不知道表中存储的记录的pk。
代码
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
我怎么能做到这一点??
可以在序列化器中访问请求,因为泛型视图通过上下文将请求传递给序列化器:
class TokenObtainPairPatchedSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data['attr'] = attrs
session = self.context.get('request').session
# rest of the code
return data
您可以访问它,因为TokenObtainPairView
派生自GenericAPIView
。