Django项目中使用JWT的实现代码

yipeiwu_com6年前Python基础

1.requiremwnts:

  • Django版本:2.2
  • python版本:3.6
  • djangorestframework版本:3.1
  • djangorestframework-jwt版本:1.11
  • MySQL版本:5.7

注意:使用Django 2.1以上的版本,MySQL数据库必须在5.5以上的版本。

2.新建项目

1)使用pycharm新建一个Django项目,我的项目名称叫:django_jwt

2)使用语句 python manage.py startapp django_restframework_jwt新建一个名为django_restframework_jwt的app

3)在settings.py加入注册代码:

INSTALLED_APPS = [
  'django.contrib.admin',
  'django.contrib.auth',
  'django.contrib.contenttypes',
  'django.contrib.sessions',
  'django.contrib.messages',
  'django.contrib.staticfiles',

  # 新添加
  'django_restframework_jwt',
  'rest_framework',
]

4)在settings.py中追加配置相关文件:

REST_FRAMEWORK = {
  'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated', #必须有
  ),
  'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
  )
}
import datetime
JWT_AUTH = {
 # 指明token的有效期
 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
}

5)settings.py中修改数据库相关配置:

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql', # 数据库的类别
    'NAME': 'test', # 数据库的名字
    'HOST': '127.0.0.1', # 数据库的ip
    'USER': 'root', # 用户名
    'PASSWORD': '5201314', # 密码
    'PORT': '3307'
  }
}

6)在自己的本地数据库中新建一个叫test的数据库;

7)安装相关的依赖包:

pip install djangorestframework-jwt
pip install djangorestframework markdown Django-filter

8)在django_jwt/urls.py配置相关的路由:

from django.contrib import admin
from django.urls import path, include
from django_restframework_jwt.views import IndexView

urlpatterns = [
  path('admin/', admin.site.urls),
  path('jwt/', include('django_restframework_jwt.urls')),
  path('index/', IndexView.as_view(), name='index'),
]

9)在django_restframework_jwt/views.py写一个测试的视图:

from django.shortcuts import render, HttpResponse
from rest_framework.views import APIView


class IndexView(APIView):
  """
  首页
  """

  def get(self, request):
    return HttpResponse('首页')

10)新建django_restframework_jwt/urls.py文件,修改成下面的代码:

from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token

app_name = 'jwt'
urlpatterns = [
  path('jwt_token_auth/', obtain_jwt_token),

]

11)执行下面两句命令:

python manage.py makemigrations
python manage.py migrate

在数据库中创建相应的表。

12)创建一个超级用户,用来测试token

python manage.py createsuperuser

13)运行项目,打开Postman软件,测试项目:

第一步测试成功,能得到token

接着使用token

token值的前面记得要加入JWT,还要加上一个空格。

能正常进入首页,如果没有在headers加入token,是不能正常访问首页的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python字典中的键映射多个值的方法(列表或者集合)

一个字典就是一个键对应一个单值的映射。如果你想要一个键映射多个值,那么你就需要将这多个值放到另外的容器中, 比如列表或者集合里面。比如,你可以像下面这样构造这样的字典: d = {...

python dataframe 输出结果整行显示的方法

在使用dataframe时遇到datafram在列太多的情况下总是自动换行显示的情况,导致数据阅读困难,效果如下: # -*- coding: utf-8 -*- import nu...

举例讲解Python设计模式编程中的访问者与观察者模式

访问者模式 我觉得Visitor模式是在补修改已有程序结构前提下,通过添加额外的访问者完成对代码功能的拓展 为什么这样用?当你的类层次较多,在某层结构中增加新的方法,要是在基类上面添加或...

python多线程http压力测试脚本

本文实例为大家分享了python多线程http压力测试的具体代码,供大家参考,具体内容如下 #coding=utf-8 import sys import time import...

Python matplotlib绘制饼状图功能示例

Python matplotlib绘制饼状图功能示例

本文实例讲述了Python matplotlib绘制饼状图功能。分享给大家供大家参考,具体如下: 一 代码 import numpy as np import matplotlib....