本文主要介绍django中token的生成与使用。
版本:前端
python 3.5.2python
Django 2.0.3django
djangorestframework 3.7.7spa
建立Django项目rest
1.安装django。https://docs.djangoproject.com/en/2.0/intro/tutorial01/code
2.安装djangorestframework pip install djangorestframework
blog
配置认证模式token
在settings中添加以下配置 接口
INSTALLED_APPS = [ ...... ...... 'rest_framework.authtoken' ...... ]
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ) }
生成并使用Tokenip
Note:注意使用python manage.py migrate 生成对应的表
在须要使用的地发引入
from rest_framework.authtoken.models import Token from django.contrib.auth.models import User from rest_framework import permissions
1.在代码中建立Toke
token = Token.objects.create(user=...) print token.key
2.在接口中认证用户
例如:
class DoingView(views.APIView): permission_classes = (permissions.IsAuthenticated,) def get(self,request): doning....
Note:使用 request.user 来得到请求的用户是谁。
3.前端请求参数
前端请求时须要在headers中带上以下参数,例如
“Authorization”:“Token c4742d9de47d2cfec1dbe5819883ce6a3e4d99b”