码迷,mamicode.com
首页 > 其他好文 > 详细

django def Token验证

时间:2019-04-05 14:00:24      阅读:325      评论:0      收藏:0      [点我收藏+]

标签:size   .com   session   obj   model   org   guid   basic   pass   

https://www.django-rest-framework.org/api-guide/authentication/#basicauthentication

1.INSTALLED_APPS

INSTALLED_APPS = (
    ...
    ‘rest_framework.authtoken‘
)

2.REST_FRAMEWORK配置

REST_FRAMEWORK = {
    # ‘DEFAULT_PAGINATION_CLASS‘:‘rest_framework.pagination.PageNumberPagination‘,
    # ‘PAGE_SIZE‘:2,
    ‘DEFAULT_FILTER_BACKENDS‘: (‘django_filters.rest_framework.DjangoFilterBackend‘,),
    ‘DEFAULT_AUTHENTICATION_CLASSES‘: (
        ‘rest_framework.authentication.BasicAuthentication‘,
        ‘rest_framework.authentication.SessionAuthentication‘,
        ‘rest_framework.authentication.TokenAuthentication‘
    )
}

3.migrate生成表

4.创建一个token

import sys
import os

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd)
os.environ.setdefault(‘DJANGO_SETTINGS_MODULE‘, ‘MxShop.settings‘)

import django
django.setup()

from rest_framework.authtoken.models import Token

from django.contrib.auth import authenticate
user = authenticate(username=‘admin‘,password=‘admin‘)
token = Token.objects.create(user=user)
print(token.key)

5.生成oken

技术图片

6.验证token

技术图片

可通过request.user查看

django def Token验证

标签:size   .com   session   obj   model   org   guid   basic   pass   

原文地址:https://www.cnblogs.com/chenyishi/p/10658468.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!