如何使用Django提供结果文件? [英] how to serve Result file using Django?

查看:93
本文介绍了如何使用Django提供结果文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个应用程序,该应用程序无需使用模型就可以从上传方法中获取输入文件,并在服务器后面运行一些代码

I have developed an App that takes input file from the upload method without using model and run some code behind the server

像这样:

/MyDjango_project_directory/media/input.csv

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

And generates some result files in a location like this.

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

目前,我只是通过 views.py中的 sys命令将输出文件移到 media文件夹中只需在呈现结果页面之前并通过下载链接就可以成功下载文件。这是对我有用的临时解决方案,但不是我正在寻找的最佳解决方案。是否有人有一些连击想法,以便我可以添加 output_directory专用于下载目的。

Presently I am just moving the output files into "media" folder through "sys" command in "views.py" just before rendering the result page and through download link one can download the files successfully. This is a temporary solution which is working for me but not the best solution for which I am looking for. Does any body have some batter idea so that I can add my "output_directory" dedicate for the download purposes.

已更新

我的观点:

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 %}


推荐答案

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

After struggling a lot finally I have write down what I needed:

视图将是:

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'),

我正在回答自己的问题,这意味着我刚学到了这一段时间之前,并张贴在这里,以便可以从中受益。如果有专家回答此问题,请对其进行丑陋的解决方案或适当的解决方案,并在部署期间也能使用?谢谢。

I am answering my own question this means I just learned this little while ago, and posted here so that if some one can be benefited from this. If any expert came across to this answer kindly review it, wither its a ugly solution or an appropriate solution and will it work during deployment also ?. thanks.

此问题为我提供了很多理解和实施的概念:从django 1.4.3的media文件夹中下载文件(上传的文件)

This Question has helped me a lot to understand and implement the concept: Downloading the files(which are uploaded) from media folder in django 1.4.3

这篇关于如何使用Django提供结果文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆