我有一个用于移动应用程序的Django后端。
我正在使用django rest框架(django-rest-auth),但是我仍在编写自己的视图和逻辑,因为API端点不是基于模型的。
发送给我的请求的标头中有一个密钥,该密钥与注册的各个设备相关联。与此同时,它还包含由设备ID和其他详细信息组成的发布数据。
一旦我使用request.META获得该标头,如何将其保存在用户模型中(每次用户登录时都会更新),因此以后可以用作获取所有详细信息(如用户和关联设备)的外键。
class CustomLoginView(LoginView):
def get_response_serializer(self):
if getattr(settings, 'REST_USE_JWT', False):
response_serializer = JWTSerializer
else:
# print(self.request.data)
response_serializer = serializers.TokenSerializer
# response_serializer = {'data':response_serializer}
return response_serializer
def get_response(self):
# raise APIException("There was a problem!")
serializer_class = self.get_response_serializer()
# print(serializer_class.data)
try:
if getattr(settings, 'REST_USE_JWT', False):
data = {
'user': self.user,
'token': self.token
}
serializer = serializer_class(instance=data,
context={'request': self.request})
else:
print("hello")
serializer = serializer_class(instance=self.token,
context={'request': self.request})
print("BYE")
print(serializer.data)
# print(self.request.data)
try:
# print(serializer.data)
if 'email' not in self.request.POST:
return Response({'data':'message'})
return Response({'data':serializer.data,'status':1,'message':'Success'}, status=status.HTTP_200_OK)
except ValidationError as exc:
raise ValidationError({
'field_val1': exc.detail,
})
except:
print("in except")
raise APIException("There was a problem!")
def post(self, request, *args, **kwargs):
self.request = request
self.serializer = self.get_serializer(data=self.request.data,
context={'request': request})
print(self.request.data)
if self.serializer.is_valid():
print(request.META)
self.login()
return self.get_response()
else:
return Response({"data":[],"message":"Credentials are wrong",'status':0})
class User(AbstractUser):
"""User model."""
username = None
email = models.EmailField(_('email address'), unique=True)
mobile_token = models.CharField(max_length=20,blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
UserManager(BaseUserManager)类: “”“为没有用户名字段的用户模型定义模型管理器。”“”
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
"""Create and save a User with the given email and password."""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
"""Create and save a regular User with the given email and password."""
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
"""Create and save a SuperUser with the given email and password."""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
答案 0 :(得分:1)
定义一个instance method
,并在您的CustomLoginView
中将其用作
from rest_framework.exceptions import ValidationError
class CustomLoginView(LoginView):
def save_header(self):
headr = self.request.META.get('HTTP_MYHEADER', None)
if headr is None:
raise ValidationError('"MYHEADER" is missing in headers"')
current_user = self.user
current_user.mobile_token = headr
current_user.save()
# your code
更新
如下更改视图
from rest_auth.views import LoginView
from rest_framework.exceptions import ValidationError
class CustomLoginView(LoginView):
def save_header(self):
headr = self.request.META.get('HTTP_MYHEADER', None)
if headr is None:
raise ValidationError('"MYHEADER" is missing in headers"')
current_user = self.user
current_user.mobile_token = headr
current_user.save()
def post(self, request, *args, **kwargs):
response = super().post(request, *args, **kwargs)
if response.status_code == 200:
self.save_header()
return response
,您的有效载荷应为
{
"email":"myemail@email.com",
"password":"mypassword"
}