django 用户登录token认证

  • Post author:
  • Post category:其他


创建项目

指定app名
在这里插入图片描述

**



配置settings

**

写入rest_fromworK和rest_fromwork.authtoken

在这里插入图片描述

配置数据库

在这里插入图片描述

修改时区和语言等

LANGUAGE_CODE = ‘zh-Hans’

TIME_ZONE = ‘Asia/Shanghai’

USE_I18N = True

USE_L10N = True

USE_TZ = False




配置model

在这里插入图片描述

**



生成迁移

python

manage.py

makemigrations

#注意要自己建数据库

**



执行迁移

python

manage.py

migrate

**




View视图

from django.shortcuts import render

from rest_framework.viewsets import ModelViewSet

from .models import *

from rest_framework.authentication import BasicAuthentication,TokenAuthentication,SessionAuthentication

from .serizer import *

from rest_framework.permissions import IsAuthenticated,IsAdminUser

class GoodViewset(ModelViewSet):

#继承视图,里面写好了创建修改等

queryset = Goods.objects.all()

#获取商品表的对象

serializer_class =Goodser

#序列化类在另一个视图里

authentication_classes = [BasicAuthentication,TokenAuthentication,SessionAuthentication]

#BasicAuthentication 基本身份验证要求提供用户名和密码。

#TokenAuthentication token认证

#SessionAuthentication 基于session的用户认证

permission_classes = (IsAuthenticated,)

#验证普通用户,IsAdminUser 管理员用户

**



serialzers序列化

from rest_framework.serializers import ModelSerializer

from .models import *

class Goodser(ModelSerializer):

class Meta:

model=Goods

#拿到商品表,前面变量不可更改

fields = ‘

all



#获取全部,前面变量不可更改

**

**



配置路由

from django.contrib import admin

from django.urls import path,include

from rs.views import *

from rest_framework.authtoken.views import obtain_auth_token

from rest_framework.routers import DefaultRouter

router = DefaultRouter()

router.register(‘goods’,GoodViewset,)

#页面名称,视图

urlpatterns = [

path(‘admin/’, admin.site.urls),

path(’’,include(router.urls)),

path(‘token’,obtain_auth_token),

#token 页面,输入账号密码获取token

]

**



版权声明:本文为cesor原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。