博客五部曲之三 - 博客RESTful


1593 浏览 5 years, 9 months

28 Base APIView for User Login

版权声明: 转载请注明出处 http://www.codingsoho.com/

Base APIView for User Login

接下来实现用户登陆。在用户登陆中,我们打算引入token来验证登陆。

src/accounts/api/serializers.py

from rest_framework.serializers import (
     CharField,

class UserLoginSerializer(ModelSerializer):
     token = CharField(allow_blank=True, read_only=True)
     username = CharField()
     email = EmailField(label='Email Address')
     class Meta:
         model = User
         fields = [
             'username',
             'email',
             'password',
             'token',
         ]
         extra_kwargs = {"password":
                             {"write_only": True}
                             }
     def validate(self, data):
         # email = data['email']
         # user_qs = User.objects.filter(email=email)
         # if user_qs.exists():
         #     raise ValidationError("This user has already registered.")
         return data

视图里post验证的过程跟form验证有的类似,首先通过Serializer获取数据,并且做验证is_valid,如果验证失败,那么Response错误(TTP_400_BAD_REQUEST),注意这儿的Response是RESTful的响应,不是HttpResponse。如果验证成功,那么正常处理,返回TTP_200_OK.

src/accounts/api/views.py

from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from rest_framework.views import APIView

from .serializers import (
     UserLoginSerializer, 

class UserLoginAPIView(APIView):
     permission_classes = [AllowAny]
     serializer_class = UserLoginSerializer     
     def post(self, request, *args, **kwargs):
         data = request.data
         serializer = UserLoginSerializer(data=data)
         if serializer.is_valid(raise_exception=True):
             new_data = serializer.data
             return Response(new_data, status=HTTP_200_OK)
         return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

最后,添加到URL

src/accounts/api/urls.py

from .views import (
     UserLoginAPIView        

urlpatterns = [
     url(r'^login/$', UserLoginAPIView.as_view(), name='login'),

访问http://127.0.0.1:8000/api/users/login/,当前还只是做了数据的格式验证,下一节会对数据有效性进行验证。