zl程序教程

您现在的位置是:首页 >  后端

当前栏目

[Django] Auth django app with rest api

djangoAppAPI with rest auth
2023-09-14 09:00:51 时间

First, start the env:

. bin/activate

 

Then cd to our module

cd djangular

 

Create a new app:

python manage.py startapp auth_api

 

Create a api.py inside auth_api folder:

from django.contrib.auth import authenticate, login, logout
from rest_framework import status, views
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator

from .serializers import UserSerializer

# views.APIView -- rest api call
class LoginView(views.APIView):

    @method_decorator(csrf_protect)
    def post(self, request):
        user = authenticate(
            username=request.data.get("username"),
            password=request.data.get("password")
        )

        if user is None or not user.is_active:
            return Response({
                    'status': 'Unauthorized',
                    'message': 'Username or password incorrect'
                }, status=status.HTTP_401_UNAUTHORIZED)

        login(request, user)
        return Response(UserSerializer(user).data) # convert python object to json using serializer and send back to client

class LogoutView(views.APIView):

    def get(self, request):
        logout(request)
        return Response({}, status=status.HTTP_204_NO_CONTENT)

 

auth_api/serialilzer.py

from django.contrib.auth.models import User

from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):


    class Meta:
        model = User
        fields = ('id', 'username')

 

auth_api/urls.py:

from django.conf.urls import url
from .api import LoginView, LogoutView

urlpatterns = [
    url(r'^login/$', LoginView.as_view()), # because LoginView is class not a method, we need to call as_view() method
    url(r'^logout/$', LogoutView.as_view()),
]

 

top leavel settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'scrurumboard',
    'tictactoe',
    'auth_api'  # add app here
]

 

top leavel urls.py:

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^scrumboard/', include('scrurumboard.urls')),
    url(r'^auth_api/', include('auth_api.urls')), # add url here
]

 

If visit the localhost:8000/auth_api/login, should see the interface.