标签:
Django使用自定义认证方式 介绍了 “Django使用自定义认证方式”,这一篇说说怎样在前一篇的基础上提供rest api。
#coding:utf-8
from django.contrib.auth.models import User
from rest_framework import serializers
class LoginSerializer(serializers.ModelSerializer):
username = serializers.CharField(required=False, max_length=1024)
password = serializers.CharField(required=False, max_length=1024)
class Meta:
model = User
fields = (‘id‘, ‘username‘, ‘password‘)
#coding:utf-8
from rest_framework import generics, viewsets, mixins, status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import *
class LoginViewSet(APIView):
queryset = User.objects.all()
serializer_class = LoginSerializer
def post(self, request):
try:
username = request.data.get(‘username‘)
password = request.data.get(‘password‘)
user = User.objects.get(username__iexact=username)
if user.check_password(password):
print user
serializer = LoginSerializer({‘id‘: user.id, ‘username‘: user.username})
return Response(serializer.data)
return Response(status=status.HTTP_401_UNAUTHORIZED)
except User.DoesNotExist:
return Response(status=status.HTTP_401_UNAUTHORIZED)
from django.conf.urls import url, include
from rest_framework import routers
from .views import *
urlpatterns = [
url(r‘^api/login$‘, LoginViewSet.as_view()),
]
urlpatterns = [
...
url(r‘^login/‘, include(‘login.urls‘)),
url(r‘^api-auth/‘, include(‘rest_framework.urls‘, namespace=‘rest_framework‘)),
...
]
运行工程,然后访问 http://localhost:8000/login/api/login
转载请以链接形式标明本文地址
本文地址:http://blog.csdn.net/kongxx/article/details/50538938
Django rest framework 使用自定义认证方式
标签:
原文地址:http://blog.csdn.net/kongxx/article/details/50538938