{"id":75742,"date":"2020-01-20T11:56:41","date_gmt":"2020-01-20T06:26:41","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=75742"},"modified":"2024-04-12T14:17:16","modified_gmt":"2024-04-12T08:47:16","slug":"producing-csv","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/","title":{"rendered":"Producing CSV"},"content":{"rendered":"<p>Python comes with a CSV library, csv. The key to using it with Django is that the csv module\u2019s CSV-creation capability acts on file-like objects, and Django\u2019s HttpResponse objects are file-like objects. Here\u2019s an example:<\/p>\n<p>import csv<br>\nfrom django.http import HttpResponse<\/p>\n<p>def some_view(request):<br>\n# Create the HttpResponse object with the appropriate CSV header.<br>\nresponse = HttpResponse(content_type=&#8217;text\/csv&#8217;)<br>\nresponse[&#8216;Content-Disposition&#8217;] = &#8216;attachment;<br>\nfilename=&#8221;somefilename.csv&#8221;&#8216;<\/p>\n<p>writer = csv.writer(response)<br>\nwriter.writerow([&#8216;First row&#8217;, &#8216;Foo&#8217;, &#8216;Bar&#8217;, &#8216;Baz&#8217;])<br>\nwriter.writerow([&#8216;Second row&#8217;, &#8216;A&#8217;, &#8216;B&#8217;, &#8216;C&#8217;, &#8216;&#8221;Testing&#8221;&#8216;])<\/p>\n<p>return response<\/p>\n<p>The code and comments should be self-explanatory, but a few things deserve a mention:<\/p>\n<ul>\n<li>The response gets a special MIME type, text\/csv. This tells browsers that the document is a CSV file, rather than an HTML file. If you leave this off, browsers will probably interpret the output as HTML, which will result in ugly, scary gobbledygook in the browser window.<\/li>\n<li>The response gets an additional Content-Disposition header, which contains the name of the CSV file. This filename is arbitrary; call it whatever you want. It\u2019ll be used by browsers in the Save as\u00e2\u20ac\u00a6<\/li>\n<li>dialogue, etc.<\/li>\n<li>Hooking into the CSV-generation API is easy: Just pass response as the first argument to csv.writer. The csv.writer function expects a file-like object, and HttpResponse objects fit the bill.<\/li>\n<li>For each row in your CSV file, call writer.writerow, passing it an iterable object such as a list or tuple.<\/li>\n<li>The CSV module takes care of quoting for you, so you don\u2019t have to worry about escaping strings with quotes or commas in them. Just pass writerow() your raw strings, and it\u2019ll do the right thing.<\/li>\n<\/ul>\n<h3>Streaming large CSV files<\/h3>\n<p>When dealing with views that generate very large responses, you might want to consider using Django\u2019s StreamingHttpResponse instead. For example, by streaming a file that takes a long time to generate you can avoid a load balancer dropping a connection that might have otherwise timed out while the server was generating the response. In this example, we make full use of Python generators to efficiently handle the assembly and transmission of a large CSV file:<\/p>\n<h3>import csv<\/h3>\n<p>from django.utils.six.moves import range<br>\nfrom django.http import StreamingHttpResponse<\/p>\n<p>class Echo(object):<br>\n&#8220;&#8221;&#8221;An object that implements just the write method of the file-like<br>\ninterface.<br>\n&#8220;&#8221;&#8221;<br>\ndef write(self, value):<br>\n&#8220;&#8221;&#8221;Write the value by returning it, instead of storing in a buffer.&#8221;&#8221;&#8221;<br>\nreturn value<\/p>\n<p>def some_streaming_csv_view(request):<br>\n&#8220;&#8221;&#8221;A view that streams a large CSV file.&#8221;&#8221;&#8221;<br>\n# Generate a sequence of rows. The range is based on the maximum number of<br>\n# rows that can be handled by a single sheet in most spreadsheet<br>\n# applications.<br>\nrows = ([&#8220;Row {}&#8221;.format(idx), str(idx)] for idx in range(65536))<br>\npseudo_buffer = Echo()<br>\nwriter = csv.writer(pseudo_buffer)<br>\nresponse = StreamingHttpResponse((writer.writerow(row)<br>\nfor row in rows), content_type=&#8221;text\/csv&#8221;)<br>\nresponse[&#8216;Content-Disposition&#8217;] = &#8216;attachment;<br>\nfilename=&#8221;somefilename.csv&#8221;&#8216;<br>\nreturn response<\/p>\n<h3>Using The Template System<\/h3>\n<p>Alternatively, you can use the Django template system to generate CSV. This is lower-level than using the convenient Python csv module, but the solution is presented here for completeness. The idea here is to pass a list of items to your template, and have the template output the commas in a for loop. Here\u2019s an example, which generates the same CSV file as above:<\/p>\n<p>from django.http import HttpResponse<br>\nfrom django.template import loader, Context<\/p>\n<p>def some_view(request):<br>\n# Create the HttpResponse object with the appropriate CSV header.<br>\nresponse = HttpResponse(content_type=&#8217;text\/csv&#8217;)<br>\nresponse[&#8216;Content-Disposition&#8217;] = &#8216;attachment;<br>\nfilename=&#8221;somefilename.csv&#8221;&#8216;<\/p>\n<p># The data is hard-coded here, but you could load it<br>\n# from a database or some other source.<br>\ncsv_data = (<br>\n(&#8216;First row&#8217;, &#8216;Foo&#8217;, &#8216;Bar&#8217;, &#8216;Baz&#8217;),<br>\n(&#8216;Second row&#8217;, &#8216;A&#8217;, &#8216;B&#8217;, &#8216;C&#8217;, &#8216;&#8221;Testing&#8221;&#8216;, &#8220;Here&#8217;s a quote&#8221;),<br>\n)<\/p>\n<p>t = loader.get_template(&#8216;my_template_name.txt&#8217;)<br>\nc = Context({&#8216;data&#8217;: csv_data,})<br>\nresponse.write(t.render(c))<br>\nreturn response The only difference between this example and the previous example\\<br>\nis that this one uses template loading instead of the CSV module. The rest of the co\\<br>\nde &#8211; such as the `content_type=&#8217;text\/csv&#8217;` &#8211; is the same. Then, create the template `\\<br>\nmy_template_name.txt`, with this template code:<\/p>\n<p>{% for row in data %}<br>\n&#8220;{{ row.0|addslashes }}&#8221;,<br>\n&#8220;{{ row.1|addslashes }}&#8221;,<br>\n&#8220;{{ row.2|addslashes }}&#8221;,<br>\n&#8220;{{ row.3|addslashes }}&#8221;,<br>\n&#8220;{{ row.4|addslashes }}&#8221;<br>\n{% endfor %}<\/p>\n<p>This template is quite basic. It just iterates over the given data and displays a line of CSV for each row. It uses the addslashes template filter to ensure there aren\u2019t any problems with quotes.<\/p>\n<h3>Other Text-Based Formats<\/h3>\n<p>Notice that there isn\u2019t very much specific to CSV here \u2013 just the specific output format. You can use either of these techniques to output any text-based format you can dream of. You can also use a similar technique to generate arbitrary binary data; For example, generating PDFs.<\/p>\n\n\n<p><a href=\"https:\/\/www.vskills.in\/certification\/tutorial\/certified-django-developer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Back to Tutorial<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python comes with a CSV library, csv. The key to using it with Django is that the csv module\u2019s CSV-creation capability acts on file-like objects, and Django\u2019s HttpResponse objects are file-like objects. Here\u2019s an example: import csv from django.http import HttpResponse def some_view(request): # Create the HttpResponse object with the appropriate CSV header. response =&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[8655],"tags":[8793],"class_list":["post-75742","page","type-page","status-publish","hentry","category-django-web-development","tag-producing-csv"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Producing CSV - Tutorial<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Producing CSV - Tutorial\" \/>\n<meta property=\"og:description\" content=\"Python comes with a CSV library, csv. The key to using it with Django is that the csv module\u2019s CSV-creation capability acts on file-like objects, and Django\u2019s HttpResponse objects are file-like objects. Here\u2019s an example: import csv from django.http import HttpResponse def some_view(request): # Create the HttpResponse object with the appropriate CSV header. response =...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/\" \/>\n<meta property=\"og:site_name\" content=\"Tutorial\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vskills.in\/\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-12T08:47:16+00:00\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/\",\"name\":\"Producing CSV - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-20T06:26:41+00:00\",\"dateModified\":\"2024-04-12T08:47:16+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Producing CSV\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"name\":\"Tutorial\",\"description\":\"Vskills - A initiative in elearning and certification\",\"publisher\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\",\"name\":\"Vskills\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"width\":73,\"height\":55,\"caption\":\"Vskills\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/vskills.in\/\",\"https:\/\/x.com\/vskills_in\",\"https:\/\/www.linkedin.com\/company-beta\/1371554\/\",\"https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Producing CSV - Tutorial","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/","og_locale":"en_US","og_type":"article","og_title":"Producing CSV - Tutorial","og_description":"Python comes with a CSV library, csv. The key to using it with Django is that the csv module\u2019s CSV-creation capability acts on file-like objects, and Django\u2019s HttpResponse objects are file-like objects. Here\u2019s an example: import csv from django.http import HttpResponse def some_view(request): # Create the HttpResponse object with the appropriate CSV header. response =...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/","og_site_name":"Tutorial","article_publisher":"https:\/\/www.facebook.com\/vskills.in\/","article_modified_time":"2024-04-12T08:47:16+00:00","twitter_misc":{"Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/","name":"Producing CSV - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-20T06:26:41+00:00","dateModified":"2024-04-12T08:47:16+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/producing-csv\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"Producing CSV"}]},{"@type":"WebSite","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","name":"Tutorial","description":"Vskills - A initiative in elearning and certification","publisher":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization","name":"Vskills","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","width":73,"height":55,"caption":"Vskills"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/vskills.in\/","https:\/\/x.com\/vskills_in","https:\/\/www.linkedin.com\/company-beta\/1371554\/","https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw"]}]}},"_links":{"self":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75742","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/comments?post=75742"}],"version-history":[{"count":4,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75742\/revisions"}],"predecessor-version":[{"id":83371,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75742\/revisions\/83371"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=75742"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=75742"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=75742"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}