Django上传和处理文件,不保留数据

时间:2022-09-15 21:44:31

Python: 2.7.11

Python:2.7.11

Django: 1.9

Django:1.9

I want to upload a csv file to Django and analyze it with a Python class. No saving is allowed and the file is only needed to reach the class to be analyzed. I'm using Dropzone.js for the form but I don't understand how I should configure/program the views to achieve this.

我想上传一个csv文件到Django,并使用Python类对其进行分析。不允许保存,文件只需要到达要分析的类。我用Dropzone。用于表单的js,但我不明白如何配置/编程视图来实现这一点。

<form action="/upload/" method="post" enctype="multipart/form-data" class="dropzone" id="dropzone">
    {% csrf_token %}
    <div class="fallback">
        <input name="file" type="file" multiple />
    </div>
</form>

I have found an article about this but it describes saving and is based on Django 1.5.

我找到了一篇关于这方面的文章,但是它描述了保存,并且基于Django 1.5。

view.py

view.py

def upload(request):
    if request.method == 'POST':
        file = FileUploadForm(request.POST)
        if file.is_valid():
            return HttpResponseRedirect('/upload/')
    else:
        file = FileUploadForm()

    return render(request, 'app/upload.html', {'file': file})

forms.py

forms.py

from django import forms
class FileUploadForm(forms.Form):
    file = forms.FileField()

Closing Update: The most important difference between the helping answer and my situation is that I had to decode my input. See the following line as mine csv_file in handle_csv_data:

结尾更新:帮助答案和我的情况之间最重要的区别是我必须解码我的输入。在handle_csv_data中,如下一行作为我的csv_file:

StringIO(content.read().decode('utf-8-sig'))

1 个解决方案

#1


1  

Access the csv file in the view function. If you are using python 3, you must wrap the InMemoryUploadedFile in a TextIOWrapper to parse it with the csv module.

在视图函数中访问csv文件。如果您使用的是python3,那么您必须将InMemoryUploadedFile包装在TextIOWrapper中,以使用csv模块解析它。

In this example the csv is parsed and passed back as a list named 'content' that will be displayed as a table.

在这个示例中,csv被解析并作为一个名为“content”的列表返回,该列表将显示为一个表。

views.py

views.py

import csv
import io  # python 3 only

def handle_csv_data(csv_file):
    csv_file = io.TextIOWrapper(csv_file)  # python 3 only
    dialect = csv.Sniffer().sniff(csv_file.read(1024), delimiters=";,")
    csv_file.seek(0)
    reader = csv.reader(csv_file, dialect)
    return list(reader)


def upload_csv(request):
    csv_content=[]
    if request.method == 'POST':
        csv_file = request.FILES['file'].file
        csv_content = handle_csv_data(csv_file)  
    return render(request, 'upload.html', {'content':content})

Your original code did not use django's form framework correctly, so I just dropped that from this example. So you should implement error handling when the uploaded file is invalid or missing.

您的原始代码没有正确地使用django的表单框架,所以我从这个示例中删除了它。因此,当上传的文件无效或丢失时,应该执行错误处理。

upload.html

upload.html

  <form action="/upload/" 
        method="post" 
        enctype="multipart/form-data" 
        class="dropzone" 
        id="dropzone">
    {% csrf_token %}
    <div class="fallback">
      <input name="file" type="file"/>
      <input type="submit"/>
    </div>
  </form>
  {% if content %}
  <table>
  {% for row in content %}
    <tr>
    {% for col in row %}
      <td>{{ col }}</td>
    {% endfor %}
    </tr>
  {% endfor %}
  </table>
  {% endif %}

I've added a 'submit' button so this works without the dropzone thing. I also removed 'multiple' from the file input, to keep the example simple. Finally there's a table if the template receives content from a parsed csv. But when using dropzone.js, you have to use a javascript callback function to display the table.

我添加了一个“提交”按钮,这样就可以在没有dropzone的情况下运行。我还从文件输入中删除了“多个”,以保持示例的简单性。最后,如果模板从parsed csv中接收内容,则会有一个表。但是,当使用dropzone。js,必须使用javascript回调函数来显示表。

#1


1  

Access the csv file in the view function. If you are using python 3, you must wrap the InMemoryUploadedFile in a TextIOWrapper to parse it with the csv module.

在视图函数中访问csv文件。如果您使用的是python3,那么您必须将InMemoryUploadedFile包装在TextIOWrapper中,以使用csv模块解析它。

In this example the csv is parsed and passed back as a list named 'content' that will be displayed as a table.

在这个示例中,csv被解析并作为一个名为“content”的列表返回,该列表将显示为一个表。

views.py

views.py

import csv
import io  # python 3 only

def handle_csv_data(csv_file):
    csv_file = io.TextIOWrapper(csv_file)  # python 3 only
    dialect = csv.Sniffer().sniff(csv_file.read(1024), delimiters=";,")
    csv_file.seek(0)
    reader = csv.reader(csv_file, dialect)
    return list(reader)


def upload_csv(request):
    csv_content=[]
    if request.method == 'POST':
        csv_file = request.FILES['file'].file
        csv_content = handle_csv_data(csv_file)  
    return render(request, 'upload.html', {'content':content})

Your original code did not use django's form framework correctly, so I just dropped that from this example. So you should implement error handling when the uploaded file is invalid or missing.

您的原始代码没有正确地使用django的表单框架,所以我从这个示例中删除了它。因此,当上传的文件无效或丢失时,应该执行错误处理。

upload.html

upload.html

  <form action="/upload/" 
        method="post" 
        enctype="multipart/form-data" 
        class="dropzone" 
        id="dropzone">
    {% csrf_token %}
    <div class="fallback">
      <input name="file" type="file"/>
      <input type="submit"/>
    </div>
  </form>
  {% if content %}
  <table>
  {% for row in content %}
    <tr>
    {% for col in row %}
      <td>{{ col }}</td>
    {% endfor %}
    </tr>
  {% endfor %}
  </table>
  {% endif %}

I've added a 'submit' button so this works without the dropzone thing. I also removed 'multiple' from the file input, to keep the example simple. Finally there's a table if the template receives content from a parsed csv. But when using dropzone.js, you have to use a javascript callback function to display the table.

我添加了一个“提交”按钮,这样就可以在没有dropzone的情况下运行。我还从文件输入中删除了“多个”,以保持示例的简单性。最后,如果模板从parsed csv中接收内容,则会有一个表。但是,当使用dropzone。js,必须使用javascript回调函数来显示表。