• [Django] Auth django app with rest api


    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.

  • 相关阅读:
    mysql启动报错:Failed to start LSB: start and stop MySQL
    springboot学习源码
    A query was run and no Result Maps were found for the Mapped Statement
    mybaties报错:There is no getter for property named 'table' in 'class java.lang.String'
    redis.clients.jedis.exceptions.JedisDataException: ERR Client sent AUTH, but no password is set
    Missing artifact com.lowagie:itextasian:jar:2.1.7
    Vue.js安装及环境搭建
    高并发与多线程
    NoNodeAvailableException[None of the configured nodes are available:[.127.0.0.1}{127.0.0.1:9300]
    oracle中sys用户下all_tables表个字段说明
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6730828.html
Copyright © 2020-2023  润新知