導出excel,並將數據返回給前端(包含權限判斷)

一.先寫導出按鈕接口

  1.此接口對用戶權限進行判斷前端

  2.此接口將前端的參數組合拼湊到下一個接口的url中去,用於條件篩選redis

  3.用戶有權限的狀況下將用戶的權限信息保存到redis中去,並將token寫到url的參數中,以便對用戶下載時權限的驗證django

class ExportInfoButtonView(APIView):
    permission_classes = [SupserPermisson,]

    def get(self, request,pk):
        res = {'error':'','success':''}

        cinema_obj = Cinema.objects.filter(cinema_code=pk)
        if not cinema_obj:
            res['error'] = '信息不存在'
            return JsonResponse(data=res, code=400, desc="success", status=status.HTTP_400_BAD_REQUEST)
        params_dic=dict(request.query_params)
        del_keys=[]
        for i in params_dic:
            if params_dic[i][0] == '':
                del_keys.append(i)
            else:
                params_dic[i] = params_dic[i][0]
        if del_keys:
            for key in del_keys:
                params_dic.pop(key)
        params_dic['token'] = make_token(request.user.username)
        params = urlencode(params_dic,encoding='utf8')
        data = {}
        data['url'] = '127.0.0.1:8000/test/export_info_excel/{0}?{1}'.format(pk,params)
        res['success'] = data
        return JsonResponse(data=res, code=200, desc="success", status=status.HTTP_200_OK)

 1.1 說明:建立token 和驗證token的函數數組

import time
import hashlib
import redis
from ticket_audit import settings_sample
redis_obj = redis.Redis(host=settings_sample.REDIS_HOST, port=settings_sample.REDIS_PORT)


def make_token(user):  #建立token的函數  返回一個有過時時間的token
    ti=str(time.time())
    md5_obj = hashlib.md5(ti.encode('utf8'))
    md5_obj.update(user.encode('utf8'))
    token=md5_obj.hexdigest()
    print(token)
    redis_obj.set(token,'1',ex=20)
    return token


def check_token(token):   #token 驗證函數,驗證帶過來的token是否在redis中存在
    print(redis_obj.get(token),'這是題啃=======')
    if redis_obj.get(token):
        return True
    return False

二.下載接口

class ExportCinemaMovieExcelView(GenericAPIView):
    serializer_class = InfoSerializers
    queryset = Info.objects.all()
    filter_backends = (DjangoFilterBackend,)
    filter_class = InofFilter

    def get(self, request, pk):
        res = {'error': '', 'success': {}}
        token = request.query_params.get('token', None)
     #驗證用戶token
if not token or not check_token(token): res['error'] = '用戶沒有權限' return JsonResponse(data=res, code=401, desc="success", status=status.HTTP_401_UNAUTHORIZED) info_obj = Info.objects.filter(code=pk) if not cinfo_obj: res['error'] = '不存在' return JsonResponse(data=res, code=400, desc="success", status=status.HTTP_400_BAD_REQUEST) dic,_ = info_data_to_dict(pk, report_data, data1, data2)      #獲取到數據以後 將數據寫入到excel中去 name,file_name = export_cinema_movie_excel(dic)
    #讀取剛剛寫好的excel文件 並將文件返回給前端 with open(name,
'rb') as model_excel: result = model_excel.read() response = HttpResponse(result) response['Content-Disposition'] = 'attachment; filename=%s'%file_name os.remove(name) return response

2.1函數export_cinema_movie_excelapp

from io import BytesIO,StringIO

import datetime

# 定義時間標誌變量
import xlwt as xlwt
from django.http import HttpResponse


def expor_info_excel(result):
    sheet_time = datetime.datetime.now()
    sheet_mark = sheet_time.strftime('%Y-%m-%d')
    book_mark = sheet_time.strftime('%Y%m%d')

    # 查詢數據結果和字段名字 賦值給兩個變量
    result = result  #查詢的數據信息

    fields = ['a','b','c','d','e','f','試試人數','生物誤差','城市誤差'] # 查詢到的標題描述信息

    response = HttpResponse(content_type='application/vnd.ms-excel')  # 指定返回爲excel文件
    response['Content-Disposition'] = 'attachment;filename=cinema_movie_%s.xls' %book_mark # 指定返回文件名
    wb = xlwt.Workbook(encoding='utf-8')  # 設定編碼類型爲utf8
    sheet = wb.add_sheet(sheet_mark)  # excel裏添加類別

    for field in range(0,len(fields)):
        sheet.write(0,field,fields[field])
    #數據座標0,0 ~ row,col   row取決於:result的行數;col取決於fields的總數
    # for row in range(1,len(result)+1):
    row = 1
    j = 1
    while row <= len(result):
        for i in result:
            sheet.write(row, 0, j)
            sheet.write(row, 1, i)
            sheet.write(row, 2, result[i].get('num_a',None))
            sheet.write(row, 3, result[i].get('num_b',None))
            sheet.write(row, 4, result[i].get('report_c',None))
            sheet.write(row, 5, result[i].get('num_d',None))
            sheet.write(row, 6, result[i].get('num_r',None))
            sheet.write(row, 7, result[i].get('report_f',None))
            sheet.write(row, 8, result[i].get('report_g',None))
            row += 1
            j += 1

    import os
    name=os.getcwd()+'/temp/cinema_movie_%s.xls'%book_mark 
    fields_name = 'cinema_movie_%s.xls'%book_mark
 wb.save(name)#將數據寫入到這個地址的這個xls文件中 return name, fields_name
相關文章
相關標籤/搜索