如何使用Django提供Result文件?

时间:2017-07-30 13:00:02

标签: python django-models django-forms django-templates django-views

我开发了一个App,它从上传方法获取输入文件,而不使用模型并在服务器后面运行一些代码

像这样:

/MyDjango_project_directory/media/input.csv

并在这样的位置生成一些结果文件。

/Virtualenv_directory/MyDjango_project_directory/OutPut_files_directory/result.csv
/Virtualenv_directory/MyDjango_project_directory/OutPut_files_directory/result.png

目前我只是将输出文件移动到" media"文件夹通过" sys"命令" views.py"在渲染结果页面之前,通过下载链接,可以成功下载文件。这是一个临时解决方案,对我有用,但不是我正在寻找的最佳解决方案。是否有任何身体有一些击球手的想法,以便我可以添加我的" output_directory"致力于下载目的。

已更新

我的观点:

from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
from django.shortcuts import render, redirect
from django.conf import settings
from django.core.files.storage import FileSystemStorage
import os
import glob
from django.core.files.storage import FileSystemStorage

def Home_page(request):

    return render(request, 'protocol/home.html', {})


#def Main_protocol(request):
   # return render(request, 'protocol/main_protocol.html', {}

def simple_upload(request):
    result_files_list = []
    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)

        os.system("python /home/user/Desktop/pep_learn_project/new_pep_src/protocol/PEP_learn_1.0_selected/Sample_protocol.py > pro.log")
        os.system("rm /home/user/Desktop/pep_learn_project/new_pep_src/media/*.csv")


        base_link = "/home/user/Desktop/pep_learn_project/new_pep_src/"
        names = []
        files_to_download = glob.glob("/path_to_files/*.*")

        for i, f in enumerate(files_to_download):
            if f.split(".")[1] in ["csv", "jpg"]:
                names.append(files_to_download[i].split("/")[6])

        return render(request, 'protocol/successful.html', {
            'names': names, 'base_link':base_link
        })

    return render(request, 'protocol/main_protocol.html')

网址:

from django.conf.urls import url
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^$', views.Home_page, name='Home_page'),
    url(r'^protocol/$', views.simple_upload, name='simple_upload'),
]

模板:

{% block content %}

<style type="text/css">



    table {

     margin-bottom: 20px;

     border-collapse: collapse;
     border-spacing: 0;
     width: 30%;
     border: 1px solid #ddd;
     bgcolor: #00FF00;
}

th, td {
    border: none;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even){background-color: #f2f2f2}

</style>



<div style="overflow-x:auto;">
  <table align="center">
    <tr>
      <th align="center">Result files</th>
    </tr>
    {% for a in names %}
    <tr>
     {% if a %}
      <td><a href="/media/{{a}}"> {{a}} </a> <br></td>
     {% endif %}
    </tr>
    {% endfor %}
  </table>
</div>


{% endblock %}

1 个答案:

答案 0 :(得分:1)

经过艰苦的努力,我终于写下了我需要的东西:

观点将是:

def Download_files(request, file_name):

        file_path = os.path.join('/out_put_files', file_name)
        file_wrapper = FileWrapper(file(file_path,'rb'))
        file_mimetype = mimetypes.guess_type(file_path)
        response = HttpResponse(file_wrapper, content_type=file_mimetype )
        response['X-Sendfile'] = file_path
        response['Content-Length'] = os.stat(file_path).st_size
        response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) 

        return response

和网址:

 url(r'^protocol/(?P<file_name>.+)$', views.Download_files, name='Download_files'),

我正在回答我自己的问题,这意味着我刚刚学会了这一点,并在此发布,以便如果有人可以从中受益。如果有任何专家看到这个答案,请仔细检查一下,它是一个丑陋的解决方案还是一个合适的解决方案,它在部署期间是否也能正常工作?谢谢。

这个问题帮助我理解和实施了这个概念:Downloading the files(which are uploaded) from media folder in django 1.4.3