django生成并下载文件

960阅读 0评论2022-12-19 大镇
分类:Python/Ruby

django 生成并下载文件

总体流程:
生成文件--放到指定目录--给页面返回文件路由地址,页面通过window.open下载

涉及到几个主要设置:
1. setting.py  设置好文件存放的路径

  1. CASE_FILE_ROOT = 'E:/测试/interface_web/upload/'
2. url.py 包含两个路由,一个是生成文件的,一个是提供文件下载服务的

点击(此处)折叠或打开

  1. url(r'^download_case/$', test_views.download_case, name='download_case'),
  2. url(r'^case_file/(?P.*)$', serve, {'document_root': settings.CASE_FILE_ROOT, 'show_indexes': True}),
3. 页面的按钮 和 js + ajax

  1. <button class="btn btn-info" id="download">导出excel</button>

  1. <script type="text/javascript">
  2. // 生成并下载excel
  3. $(document).ready(function(){
  4.   $("#download").click(function(){
  5.    // 获取想要生成的文件名称
  6.     var case_name = $("#case_mid_title").text();
  7.     $.ajax({
  8.        type: "POST",
  9.        url: '/download_case/',
  10.        data: { case_name: case_name },
  11.        success: function (response){
  12.                    var filepath_name = response;
  13.                    window.open(filepath_name)
  14.                 }
  15.         });
  16.   });
  17.   });
  18. </script>

4. view.py

  1. @csrf_exempt
  2. def download_case(request):
  3.     if request.method == "POST":
  4.         # 当前的 case_name
  5.         now_case_name = request.POST.get("case_name")
  6.         cursor = connection.cursor()
  7.         # 获取case_list
  8.         try:
  9.             cursor.execute(
  10.                 f"select case_id,case_type,case_description,interface_address,request_type,"
  11.                 f"which_is_parameter,send_msg,exp_result,check_type,ignore_key,upload_files "
  12.                 f"from interface_test_cases where case_name='{now_case_name}'")
  13.             case_rows = cursor.fetchall()
  14.             new_workbook = xlwt.Workbook()
  15.             work_sheet = new_workbook.add_sheet(now_case_name)
  16.             work_sheet.write(0, 0, '要写的内容')
  17.           
  18.             filepath_name = f'E:/test/{now_case_name}.xls'
  19.             new_workbook.save(filepath_name)
  20.             # 这里要和url.py里的路由对应上,这里返回文件的地址
  21.             return HttpResponse(f'/case_file/{now_case_name}.xls')
  22.         except Exception as e:
  23.             log.info("生成Excel文件失败:")
  24.             log.info(str(e))

  25.     return redirect("/index/")


上一篇:linux安装mysql 5.7
下一篇:django下载大文件--文件分割