后端:URL:
# 第一个导出全部,第二个导出筛选部分的,不加限制正则是为了接收参数
path('export_securitylog', security_log.ExportLog.as_view(),name='export_securitylog'), path('export_form_securitylog', security_log.ExportFormLog.as_view(), name='export_form_securitylog'),
后端 接口函数 修改:
def escape_uri_path(path):
"""
Escape the unsafe characters from the path portion of a Uniform Resource
Identifier (URI).
"""
# These are the "reserved" and "unreserved" characters specified in
# sections 2.2 and 2.3 of RFC 2396:
# reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
# unreserved = alphanum | mark
# mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
# The list of safe characters here is constructed subtracting ";", "=",
# and "?" according to section 3.3 of RFC 2396.
# The reason for not subtracting and escaping "/" is that we are escaping
# the entire path, not a path segment.
return quote(path, safe="/:@&+$,-_.!~*'()")
def write_to_excel(filename, head_data, records, download_url=None): """ 写入excel文件函数 :param filename: 文件名 :param head_data: 内容头部 :param records: 内容 :param download_url: 存储路径 :return: download_url,存储路径 """ # 获取时间戳 timestr = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # 工作表 wbk = xlwt.Workbook(encoding="utf-8") sheet1 = wbk.add_sheet(f'{filename}') # , cell_overwrite_ok=True) # 写入表头 for filed in range(0, len(head_data)): sheet1.write(0, filed, head_data[filed]) # , excel_head_style()) # 写入数据记录 red_style = excel_record_style(font_color_index=2) green_style = excel_record_style() # print("=======>: ", records) for row in range(1, len(records) + 1): for col in range(0, len(head_data)): # print("records[row - 1][col] =====>: ", records[row - 1][col]) sheet1.write(row, col, records[row - 1][col]) # if col == 8 and records[row - 1][col] and records[row - 1][col]>='37': # sheet1.write(row, col, records[row - 1][col], red_style) # # elif col == 9 and records[row - 1][col] and records[row - 1][col]>='37': # # sheet1.write(row, col, records[row - 1][col], red_style) # # elif col == 10 and records[row - 1][col] and records[row - 1][col]>='37': # # sheet1.write(row, col, records[row - 1][col], red_style) # elif col == 6 and records[row - 1][col]=='是': # sheet1.write(row, col, records[row - 1][col], red_style) # elif col == 7 and records[row - 1][col]=='是': # sheet1.write(row, col, records[row - 1][col], red_style) # else: # sheet1.write(row, col, records[row - 1][col], green_style) # # 设置默认单元格宽度 sheet1.col(col).width = 256 * 15 new_filename = filename + '-' + timestr + '.xls' if not download_url: download_url = get_download_url() save_path = os.path.join(download_url, new_filename) wbk.save(save_path) # print("保存的路径=====>", save_path) # return save_path.replace(download_url, "") # return save_path return new_filename def get_download_url(): if sys.platform == 'win32': return os.environ['temp'] return '/tmp' def export_back(queryset): """ 导出文件类型格式 queryset是查询的后的orm对象 """ # 用于第一行标题 title = ['ID', "安全级别", "日志类型", "攻击类型", "源区域", "目的安全区域", "源IPv4地址", "目的IPv4地址", "源端口", "目的端口", "源MAC", "封锁时间", "URL/目录", "策略名", "防护规则ID", "日志描述信息", "动作", "时间", ] records = [] for obj in queryset: # 遍历选择的对象列表 data_list = [] # 数据列表 每一行数据 data_list.append(obj.pk) data_list.append(sev_level_map(obj.sev_level)) data_list.append(log_type_map(obj.log_type)) data_list.append(attack_type_map(obj.attack_type)) data_list.append(obj.src_zone) data_list.append(obj.dst_zone) data_list.append(inet_ntoa(obj.src_ipv4)) data_list.append(inet_ntoa(obj.dst_ipv4)) # data_list.append(obj.src_ipv6) # data_list.append(obj.dst_ipv6) data_list.append(obj.src_port) data_list.append(obj.dst_port) data_list.append(obj.src_mac) data_list.append(str(obj.blk_duration) + "秒") data_list.append(obj.url_or_dir) data_list.append(obj.policy_name) data_list.append(obj.protect_rule_id) data_list.append(obj.description) data_list.append(action_map(obj.action)) data_list.append(change_time(obj.timestamp)[0]) records.append(data_list) # 以下是修改部分 filename = write_to_excel('filename', title, records) file_path = os.path.join(get_download_url(), filename) fd = open(file_path, 'rb') resp = FileResponse(fd) resp['Content-Type'] = 'application/octet-stream' resp['Content-Disposition'] = 'attachment;filename="{0}"'.format(escape_uri_path(filename)) return resp
# 使用导出函数
# 导出全部
class ExportLog(APIView):
def get(self, request):
queryset = models.SecurityLogModelHour.objects.all()
response = export_back(queryset)
return response
前端修改部分:
# 路由部分 exportLog: '/v1/log/export_securitylog', exportformLog: '/v1/log/export_form_securitylog?ip_address=', # 封装请求部分
// 安全日志全部导出 export const exporSecuritytLog = data => { return request({ url: paths.securityLog.exportLog, // get无参数 method: 'get', // params, responseType: 'blob' }) } // 安全日志输入框查询导出 export const exporFormSecuritytLog = params => { return request({ url: paths.securityLog.exportformLog + params, # get携带参数 method: 'get', // params, responseType: 'blob' }) } # vue部分 exporSecuritytLog().then(resp => { if (!resp) { this.$message.warning('数据为空') return } const blob = new Blob([resp], { 'Content-Type': 'application/vnd.ms-excel' }) if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, '安全日志.xls') } else { const href = URL.createObjectURL(blob) const a = document.createElement('a') a.style.display = 'none' a.href = href a.download = `安全日志_${(new Date()).getTime()}.xls` a.click() URL.revokeObjectURL(a.href) document.removeChild(a) } }) } var data = this.ipAddress // 携带的参数 exporFormSecuritytLog(data).then(resp => { if (!resp) { this.$message.warning('数据为空') return } const blob = new Blob([resp], { 'Content-Type': 'application/vnd.ms-excel' }) if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, '安全日志.xls') } else { const href = URL.createObjectURL(blob) const a = document.createElement('a') a.style.display = 'none' a.href = href a.download = `安全日志_${(new Date()).getTime()}.xls` a.click() URL.revokeObjectURL(a.href) document.removeChild(a) } })