【django基礎】django接口 異步ajax請求 導出數據庫成excel表(包裹前端後端)

py文件:

from django.utils.http import urlquote
from rest_framework.views import APIView
from django.shortcuts import render, redirect, HttpResponse
from dal import models
from django.http import JsonResponse, FileResponse, StreamingHttpResponse
import os

import xlwt

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # C:\Users\user\Desktop\DownTest



class fileShow(APIView):

    def get(self, request):

        message = {}
        userinfo = models.UserInfo.objects.all()

        workbook = xlwt.Workbook(encoding='utf-8')  # 新建工作簿\

        sheet1 = workbook.add_sheet("用戶表")  # 新建sheet
        sheet1.write(0, 0, "ID")  # 第1行第1列數據
        sheet1.write(0, 1, "用戶名")  # 第1行第1列數據
        sheet1.write(0, 2, "密碼")  # 第1行第1列數據
        sheet1.write(0, 3, "創建時間")  # 第1行第1列數據

        path = BASE_DIR + "\\utils\\username.xlsx" # 儲存路徑

        excel_row = 1
        for obj in userinfo:
            data_id = obj.id
            data_username = obj.username
            data_password = obj.password
            data_time = obj.create_time

            sheet1.write(excel_row, 0, data_id)
            sheet1.write(excel_row, 1, data_username)
            sheet1.write(excel_row, 2, data_password)
            sheet1.write(excel_row, 3, str(data_time))
            excel_row += 1

            workbook.save(path)

        file = open(path,'rb')   # 字符串替換成文件
        print("file",file.name)
        # file_names = file.name.split('/')[-1]
        # print("file_names",file_names)

        response = FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'

        response['Content-Disposition'] = "attachment;filename={}".format(urlquote(path)) # 字符串替換成下載文件
        print(response)
        return response

html的ajax請求:

<button id="up">下載文件</button>  一個按鈕


請求:

// 下載文件
    $("#up").on("click", function () {
        $.ajax({
            url: "down/",
            type: "get",
            data: {},
            success: function (data) {
                var $a = $('<a></a>');
                $a.attr("href", "//127.0.0.1:8000/down/");  # 紅色的是你下載路徑
                $("body").append($a);
                $a[0].click();
                $a.remove();
            }

        })