Basics of Django under scv file

Django integration of recent relevant information, the record speaks slowly in the future, today it csv related to write such.

Here we use development tools is pycharm, after the establishment of a app we do the following in the file views.py

from django.http import HttpResponse
import csv

def index(request):
    response = HttpResponse(content_type='text/csv') #告诉浏览器这是一个  csv 格式的文件 不是html 如果不指定 就是html 
    response['Content-Disposition']="attechment;filename='abc.csv'"# 在 response 添加一个 'Content-Disposition'头  这样的话 是为了告诉他 该怎么样处理这个csv文件 attechment 说明这是一个附件 这样浏览器就不会显示它 而是下载  filename='abc.csv' 是指定附件的名字  
    writer = csv.writer(response) #writer 将 内容写进respone
    writer.writerow(['username','age','height'])
    writer.writerow(['qulinx', '18', '181cm'])  #这两部是讲内容逐行写入
    return response

Thus, after the visit to address this, it will automatically download a file from the abc.csv

===============

Because the power csv file, we may now write the contents csv according to different styles, so each arrangement will be very complicated, so I gave Django provides a template function, to speak the written template styles ready, you can call when you want to use, to avoid the country and more useless operations.

1. The need to find the folder template was created under the template file template, assuming award named: python.txt (suffix does not require, Django can be identified)

Write the following:

{% for row in rows%}{{row.0}}{{row.1}}{{row.2}}{% endfor %}

About template statement will be updated in the future ~
# role is to tell the template text output one by one,
# noticed wrap, punctuation, and so will the results of an impact

2. view.py wrote:

import csv   #操作csv
from django.template import loader  #操作模板

def template_csv_view(request):
    response = HttpResponse(content_type='text/csv')  #创建一个HttpResponse对象
    response['Content-Disposition'] = "attechment;filename='linzhen.csv'"
    context = {
        'rows':[
            ['username','age','height'],
            ['康康',18,'181cm',]
        ]
    }  #context字典的key为rows,因为模板中遍历的对象也是rows,所以要一直

    template= loader.get_template('python1806.txt')  #导入模板
    csv_template = template.render(context)  #讲context根据模板渲染
    response.content = csv_template  #讲渲染结果赋给respones.content
    return response

This will get csv file based on the template of the written ~

===============

When confronted with large files, it is a test of our strength machine hardware, but like the apple that enterprises will be improved by optimization software

So when we have to deal with large csv file, ordinary methods may also be used, but this method may be because the file is too large to corresponding timeout.

def large_csv_view(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = "attechment;filename='linzhen.csv'"
    writer = csv.writer(response)
    for row in range(0,1000000):
        writer.writerow(['Row {}'.format(row),'{}'.format(row)])
    return response

    

So here we can use StreamingHttpResponse, this class does not inherit, HttpResponse similar to watching the live time while downloading, not Caton

from django.http import StreamingHttpResponse  #导入
def large_csv_view(request):  
    response = StreamingHttpResponse(content_type='text/csv')
    response['Content-Disposition'] = "attechment;filename='kangbazi.csv'"
    rows = ("第{},{}\n".format(row,row) for row in range(0,10000000))
    response.streaming_content=rows
    return response

 

Published 14 original articles · won praise 12 · views 10000 +

Guess you like

Origin blog.csdn.net/Watson_Ashin/article/details/82950867