django 生成并下载文件
总体流程:
生成文件--放到指定目录--给页面返回文件路由地址,页面通过window.open下载
涉及到几个主要设置:
1. setting.py 设置好文件存放的路径
-
CASE_FILE_ROOT = 'E:/测试/interface_web/upload/'
2. url.py 包含两个路由,一个是生成文件的,一个是提供文件下载服务的
-
url(r'^download_case/$', test_views.download_case, name='download_case'),
-
url(r'^case_file/(?P.*)$', serve, {'document_root': settings.CASE_FILE_ROOT, 'show_indexes': True}),
3. 页面的按钮 和 js + ajax
-
<button class="btn btn-info" id="download">导出excel</button>
-
<script type="text/javascript">
-
// 生成并下载excel
-
$(document).ready(function(){
-
$("#download").click(function(){
-
// 获取想要生成的文件名称
-
var case_name = $("#case_mid_title").text();
-
$.ajax({
-
type: "POST",
-
url: '/download_case/',
-
data: { case_name: case_name },
-
success: function (response){
-
var filepath_name = response;
-
window.open(filepath_name)
-
}
-
});
-
});
-
});
-
</script>
4. view.py
-
@csrf_exempt
-
def download_case(request):
-
if request.method == "POST":
-
# 当前的 case_name
-
now_case_name = request.POST.get("case_name")
-
cursor = connection.cursor()
-
# 获取case_list
-
try:
-
cursor.execute(
-
f"select case_id,case_type,case_description,interface_address,request_type,"
-
f"which_is_parameter,send_msg,exp_result,check_type,ignore_key,upload_files "
-
f"from interface_test_cases where case_name='{now_case_name}'")
-
case_rows = cursor.fetchall()
-
new_workbook = xlwt.Workbook()
-
work_sheet = new_workbook.add_sheet(now_case_name)
-
work_sheet.write(0, 0, '要写的内容')
-
-
filepath_name = f'E:/test/{now_case_name}.xls'
-
new_workbook.save(filepath_name)
-
# 这里要和url.py里的路由对应上,这里返回文件的地址
-
return HttpResponse(f'/case_file/{now_case_name}.xls')
-
except Exception as e:
-
log.info("生成Excel文件失败:")
-
log.info(str(e))
-
-
return redirect("/index/")
阅读(960) | 评论(0) | 转发(0) |