status
Published
date
Dec 22, 2021
slug
summary
category
技术分享
tags
Python
Django
Vue

0.开发环境

后端:
  1. Python
  1. Django
  1. Django RestFramework
  1. Djangorestframework-simplejwt
前端:
  • vue
  • vue-admin-template
相关参考

1.后端开发

初始化一个Django项目
django-admin startproject simple
cd simple
python manage.py startapp users
目录结构如下:
+--- db.sqlite3
+--- manage.py
+--- simple
|   +--- asgi.py
|   +--- settings.py
|   +--- urls.py
|   +--- wsgi.py
|   +--- __init__.py
+--- users
|   +--- admin.py
|   +--- apps.py
|   +--- migrations
|   |   +--- __init__.py
|   +--- models.py
|   +--- tests.py
|   +--- urls.py
|   +--- views.py
|   +--- __init__.py
simple/settings.py 中进行配置:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users',  # add
    'rest_framework',  # add
    'rest_framework_simplejwt',  # add
    'corsheaders',  # add
]
同步数据库并创建超级用户:
# 同步数据库
python manage.py makemigrations
python manage.py migrate

# 创建超级用户 admin/123456
python manage.py createsuperuser
simple/urls.py 中编写路由:
from django.contrib import admin
from django.urls import path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView

from users import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('verify/', TokenVerifyView.as_view(), name='token_verify'),
]
对接口进行测试
POST http://127.0.0.1:8000/login/ username=admin password=123456
编写测试的接口:
from django.contrib.auth.models import User
from django.http import JsonResponse
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.views import APIView


class MyView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, *args, **kwargs):
        res = {
            "code": 20000,
            "msg": "获取用户信息成功",
            "data": ["Get information successfully!"]
        }
        return Response(res)

class UserInfo(APIView):
    def get(self, request, *args, **kwargs):
        res = {
            "code": 20000,
            "msg": "获取用户信息成功",
            "data": []
        }
        try:
            userInfo = list(User.objects.filter(username=request.user.username).values())
            if len(userInfo) > 0:
                userInfo = userInfo[0]
            else:
                userInfo = {}
            res["data"] = userInfo
        except Exception as e:
            res["code"] = -1
            res["msg"] = f"获取用户信息失败, {e}"

        return JsonResponse(res)
url配置增加两条:
path('info/', views.MyView.as_view()),
path('user/info/', views.UserInfo.as_view()),

2.前端开发

git clone https://github.com/PanJiaChen/vue-admin-template.git #clone 项目
cd vue-admin-template
npm install #安装依赖
npm run dev #启动项目

2.1移除mock服务

修改 vue.config.js ,参考:和服务端进行交互
// 原
before: require('./mock/mock-server.js')

// 改为
proxy:{
    [process.env.VUE_APP_BASE_API]:{
        target: 'http:127.0.0.1:8000',
        changeOrigin :true,
        pathRewrite: {
            ['^' + process.env.VUE_APP_BASE_API]: ''
        }
    }
},
after: require('./mock/mock-server.js')

2.2修改认证方式

修改 src/utils/request.js,将请求响应的判断加上 token 判断
baseURL: 'http://localhost:8000',  // add

config.headers['X-Token'] = getToken() //原
config.headers['Authorization'] = 'Bearer '+getToken()  //修改后

if (res.code !== 20000) //原
if (res.code !== 20000 && res.access === undefined) //修改后
修改 src/utils/auth.js,将 TokenKey 修改为后端返回的 token 名称
const TokenKey = 'vue_admin_template_token' // 原
const TokenKey='access' //修改后
修改 src/module/user.js,修改为后端返回的token名
//原
const { data } = response
commit('SET_TOKEN', data.token)
setToken(data.token)
//修改后
commit('SET_TOKEN', response.access)
setToken(response.access)

2.3修改登陆相关请求的url

修改 src/api/user.js,修改请求的 url
url: '/vue-admin-template/user/login', //原
url: '/login/',  //修改后

2.4新逻辑开发

src/js下新建demo.js
import request from '@/utils/request'

export function getInfo(token) {
  return request({
    url: '/user/info',
    method: 'get',
    params: { token }
  })
}
src/vue下新建demo/index.vue
<!-- HTML -->
<template>
<div>
    <h1>Index</h1>
    <div a>{{info}}</div>
</div>
</template>

<!-- Vue -->

<script>
import {
    getInfo
} from '@/api/demo'
export default {
    data() {
        return {
            info: '',
        };
    },
    created() {
        this.getinfo()
    },
    methods: {
      getinfo() {
          getInfo().then(response => {
              console.log(response);
              this.info = response;
          }).catch(e => {
              console.log(e);
          });
       },
    },
};
</script>

<!-- CSS样式 -->

<style scoped>
</style>
修改 src/router/index.js,增加新的路由地址
{
    path: '/demo',
    component: Layout,
    children: [
      {
        path: 'demo',
        name: 'demo',
        component: () => import('@/views/demo/index'),
        meta: { title: 'Form', icon: 'form' }
      }
    ]
  },
 

  • Cusdis
  • GitTalk