程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django + DRF JWT certification + vue3 using Axios

編輯:Python

Axios Installation and configuration

  • install
pnpm install axios
  • encapsulation axios: To configure baseUrl, Request to intercept , The response to intercept
// requests.ts In file 
// import { Message } from "element-ui";
/**** request.js ****/
// Import axios
import axios from "axios";
// Use element-ui Message Make a message reminder 
//1. Create a new axios example ,
const service = axios.create({

// Public interface -- Note here that we will talk about 
baseURL: "http://127.0.0.1:8000/api/v1",
// Timeout time The unit is ms, I've set it up here 3s Timeout for 
timeout: 3 * 1000,
});
// 2. Request interceptor 
service.interceptors.request.use(
(config) => {

// Some processing before sending a request , Data transformation , Configure the request header , Set up token, Set up loading etc. , Add... As needed 
// config.data = JSON.stringify(config.data); // Data transformation , You can also use qs transformation 
// config.headers = {

// "Content-Type": "application/x-www-form-urlencoded", // Configure the request header 
// };
// Pay attention to token We need to introduce cookie Method or use local localStorage Other methods , recommend js-cookie
const token = localStorage.getItem("token"); // Here take token Before , You definitely need to get token, Save it 
if (token) {

// config.params = { token: token }; // If required, carry it in the parameter 
config.headers = {


// Need basis DRF Provided JWT Certified to carry Token, The prefix can also be something else 

Authorization: "JWT " + token,
}; // If the request is carried in the request header 
}
console.log(" Check the request header ", config.headers);
return config;
},
(error) => {

return Promise.reject(error);
}
);
// 3. Response interceptors 
service.interceptors.response.use(
(response) => {

// Some common processing after receiving the response data and successfully , close loading etc. 
return response;
},
(error) => {

/***** The processing of abnormal response is started *****/
if (error && error.response) {

// 1. Common error handling 
// 2. Handle according to the response code 
switch (error.response.status) {

case 400:
error.message = " Wrong request ";
break;
case 401:
error.message = " unauthorized , Please login again ";
break;
case 403:
error.message = " Access denied ";
break;
case 404:
error.message = " Request error , The resource was not found ";
window.location.href = "/NotFound";
break;
case 405:
error.message = " The request method does not allow ";
break;
case 408:
error.message = " request timeout ";
break;
case 500:
error.message = " Server side error ";
break;
case 501:
error.message = " Network not implemented ";
break;
case 502:
error.message = " Network error ";
break;
case 503:
error.message = " Service not available ";
break;
case 504:
error.message = " Network timeout ";
break;
case 505:
error.message = "http The version does not support the request ";
break;
default:
error.message = ` Connection error ${
error.response.status}`;
}
} else {

// timeout handler 
if (JSON.stringify(error).includes("timeout")) {

console.log(" Server response timed out , Please refresh the current page ");
}
error.message = " Failed to connect to server !";
}
// Can cooperate with Element-plus To prompt relevant information 
// ELMessage.error(error.message);
/***** End of processing *****/
// If no error handling is required , The above processes can be omitted 
// return Promise.resolve(error.response);
console.log(error.message);
console.log(1213);
return Promise.reject(error);
}
);
//4. Import files 
export default service;
  • ts Simple use in ,get and post request
// api.ts
import service from "./requests";
// Export each... As needed API
// *************************** //
// Request home page data 
interface Iget {

[propName: string]: any;
}
export function GetHomeAPI<T>(data: Iget) {

return service.get<T>("/mdm/slideinfo/", {
 ...data });
}
interface ILogin {

username: string;
password: string;
}
export function PostLoginAPI(data: ILogin) {

return service({

method: "POST",
url: "/user/login/auth/",
data,
});
}

Vue Use in

<script setup lang="ts">
// Import API Interface data 
import {
 GetHomeAPI, PostLoginAPI } from './api/api'
interface IgetHome {

"id": number;
"province": string;
"county": string;
"slide_name": string;
"slide_head": string;
"slide_type": string;
"slide_status": number;
"created_time": string;
"is_active": boolean;
"user": number;
}
interface Ilogin {

"token": string
"id": number
"username": string
"role": boolean
}
function getHome() {

GetHomeAPI<IgetHome>({
}).then(
(res) => {

console.log(res)
}
).catch()
}
const getAs = async () => {

await GetHomeAPI({
 id: 1 }).then(
(res) => {

console.log(res.data)
}
).catch()
}
const login = () => {

PostLoginAPI({

username: "admin",
password: "521",
}).then(
(res) => {

console.log(res.data)
localStorage.setItem("token", res.data.token)
}
).catch()
}
</script>
<template>
<button @click="getHome">getHome</button>
<button @click="getAs">getAs</button>
<button @click="login">login</button>
</template>
<style>
</style>

Django The backend configuration

# settings.py
# in the light of drf Configuration information , Global configuration drf Authentication and permissions of the view 
REST_FRAMEWORK = {

# Specify view permissions 
'DEFAULT_PERMISSION_CLASSES': (
# 'rest_framework.permissions.AllowAny', # By default, each view , Allow any user to access 
# 'rest_framework.permissions.IsAuthenticatedOrReadOnly', # The authenticated user can operate , Otherwise, you can only access 
'rest_framework.permissions.IsAuthenticated', # The authenticated user can operate , Otherwise, you can only access 
), # You can also specify permission classes in each view 
# Appoint drf Authentication mechanism 
'DEFAULT_AUTHENTICATION_CLASSES': (
# rest_framework_jwt authentication , You can also specify the authentication class in each view 
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
# new edition drf schema_class The default is rest_framework.schemas.openapi.AutoSchema
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
# Global configuration drf Current limiting of the view Throttling
# REST_FRAMEWORK = {

# 'DEFAULT_THROTTLE_CLASSES': (
# # Restrict all anonymous unauthenticated users , Use IP Differentiate users 
# 'rest_framework.throttling.AnonRateThrottle',
# # Restrict authenticated users , Use User id To distinguish between 
# 'rest_framework.throttling.UserRateThrottle'
# ),
# 'DEFAULT_THROTTLE_RATES': {

# # have access to second, minute, hour or day To indicate the period 
# 'anon': '3/minute',
# 'user': '5/minute'
# }
# }
# in the light of rest_framework_jwt Configuration information 
JWT_AUTH = {

'JWT_AUTH_HEADER_PREFIX': 'JWT', # Set up Prefix in the request header 
'JWT_RESPONSE_PAYLOAD_HANDLER':
# 'rest_framework_jwt.utils.jwt_response_payload_handler', # Default jwt Authentication successful return data 
'user.utils.jwt_response_payload_handler', # Customize jwt Authentication successful return data 
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=60 * 60 * 3), # To specify token The validity of the , Default 5 branch 
'JWT_ALLOW_REFRESH': True, # Allow refresh 
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(
days=7
), # How often can the old be used token To refresh to get new token, The default is 7 God 
}

verification

  • Not logged in

  • Before login , No, token etc.

  • After logging in , Save the token

  • After logging in , Re request data

combination pinia To use

  • Change request interception
import {
 ElMessage } from 'element-plus';
// Import axios
import axios from 'axios';
import {
 IUser, KEY_USER_ID } from '@/store/modules/useUserStore';
// Use element-ui Message Make a message reminder 
//1. Create a new axios example ,
const service = axios.create({

// Public interface -- Note here that we will talk about 
baseURL: 'http://127.0.0.1:8000/api/v1',
// Timeout time The unit is ms, I've set it up here 5s Timeout for 
timeout: 5 * 1000,
});
// 2. Request interceptor 
service.interceptors.request.use(
(config) => {

// Some processing before sending a request , Data transformation , Configure the request header , Set up token, Set up loading etc. , Add... As needed 
// config.data = JSON.stringify(config.data); // Data transformation , You can also use qs transformation 
// config.headers = {

// "Content-Type": "application/x-www-form-urlencoded", // Configure the request header 
// };
// Pay attention to token We need to introduce cookie Method or use local localStorage Other methods , recommend js-cookie
// Here take token Before , You definitely need to get token, Save it 
try {

const user = JSON.parse(localStorage.getItem(KEY_USER_ID) || '') as IUser;
if (user.token) {

config.headers!['Authorization'] = `JWT ${
user.token}`;
}
} catch (e) {
}
// if (token) {

// // config.params = { token: token }; // If required, carry it in the parameter 
// config.headers = {

// // Need basis DRF Provided JWT Certified to carry Token, The prefix can also be something else 
// Authorization: 'JWT ' + token.token,
// }; // If the request is carried in the request header 
// }
// console.log(' Check the request header ', config.headers);
return config;
},
(error) => {

return Promise.reject(error);
}
);
// 3. Response interceptors 
service.interceptors.response.use(
(response) => {

// Some common processing after receiving the response data and successfully , close loading etc. 
return response;
},
(error) => {

/***** The processing of abnormal response is started *****/
if (error && error.response) {

// 1. Common error handling 
// 2. Handle according to the response code 
switch (error.response.status) {

case 400:
error.message = ' Wrong request !';
break;
case 401:
error.message = ' unauthorized , Please login again ';
break;
case 403:
error.message = ' Access denied ';
break;
case 404:
error.message = ' Request error , The resource was not found ';
window.location.href = '/NotFound';
break;
case 405:
error.message = ' The request method does not allow ';
break;
case 408:
error.message = ' request timeout ';
break;
case 500:
error.message = ' Server side error ';
break;
case 501:
error.message = ' Network not implemented ';
break;
case 502:
error.message = ' Network error ';
break;
case 503:
error.message = ' Service not available ';
break;
case 504:
error.message = ' Network timeout ';
break;
case 505:
error.message = 'http The version does not support the request ';
break;
default:
error.message = ` Connection error ${
error.response.status}`;
}
} else {

// timeout handler 
if (JSON.stringify(error).includes('timeout')) {

console.log(' Server response timed out , Please refresh the current page ');
}
error.message = ' Failed to connect to server !';
}
// Can cooperate with Element-plus To prompt relevant information 
ElMessage.error(error.message);
/***** End of processing *****/
// If no error handling is required , The above processes can be omitted 
// return Promise.resolve(error.response);
return Promise.reject(error);
}
);
//4. export file 
export default service;
  • pinia in
import {
 defineStore } from 'pinia';
// Define the interface according to the returned data 
export interface IUser {

id: number;
username: string;
token: string;
role: string;
email?: string;
}
export const KEY_USER_ID = 'user';
const useUserStore = defineStore({

id: KEY_USER_ID,
state: (): IUser => ({

id: -1,
username: '',
role: '',
email: '',
token: '',
}),
actions: {

setToken(token: string) {

this.$state.token = token;
},
setID(id: number) {

this.$state.id = id;
},
setRole(role: string) {

this.$state.role = role;
},
// Make all interface specifications optional 
login(user: Partial<IUser>) {

this.$state = {

...this.$state,
...user,
};
},
},
// Enable data cache to browser 
persist: {

enabled: true,
strategies: [
{

// Custom name 
key: KEY_USER_ID,
// Save the location , The default is saved in sessionStorage
storage: localStorage,
// Specify the data to persist 
// paths: ['age'],
},
],
},
});
export default useUserStore;
  • Login function
import useUserStore from '@/store/modules/useUserStore';
import {
 useRouter } from 'vue-router';
const router = useRouter()
const useUser = useUserStore()
const login = () => {

PostLoginAPI({

username: "admin",
password: "521",
}).then(
(res) => {

console.log(res.data)
// localStorage.setItem("token", res.data.token) Change it as follows 
useUser.login(res.data)
}
).catch()
}

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved