如何阅读CSV Django HTTP响应 [英] How to read a csv django http response

查看:73
本文介绍了如何阅读CSV Django HTTP响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个视图中,我使用一个简单的csv编写器创建了一个完全由csv组成的Django HttpResponse对象:

In a view, I create a Django HttpResponse object composed entirely of a csv using a simply csv writer:

response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="foobar.csv"'

writer = csv.writer(response)

    table_headers = ['Foo', 'Bar']
    writer.writerow(table_headers)

    bunch_of_rows = [['foo', 'bar'], ['foo2', 'bar2']]
    for row in bunch_of_rows:
        writer.writerow(row)

return response

在单元测试中,我想测试此csv的某些方面,因此需要阅读.我正在尝试这样做:

In a unit test, I want to test some aspects of this csv, so I need to read it. I'm trying to do so like so:

response = views.myview(args)

reader = csv.reader(response.content)

headers = next(reader)
row_count = 1 + sum(1 for row in reader)

self.assertEqual(row_count, 3) # header + 1 row for each attempt
self.assertIn('Foo', headers)

但是测试失败,并在headers = next(reader)行上显示以下内容:

But the test fails with the following on the headers = next(reader) line:

nose.proxy.Error: iterator should return strings, not int (did you open the file in text mode?)

我在HttpResponse源中看到response.content正在将字符串作为字节字符串回散,但是我不确定如何正确处理该文件,以使csv.reader正确读取文件.我以为我可以用response替换response.content(因为您写入对象本身,而不是它的内容),但这只会导致错误稍有变化:

I see in the HttpResponse source that response.content is spitting the string back out as a byte-string, but I'm not sure the correct way to deal with that to let csv.reader read the file correctly. I thought I would be able to just replace response.content with response (since you write to the object itself, not it's content), but that just resulted in a slight variation in the error:

_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

哪个看起来更近,但显然仍然是错误的.阅读csv文档,我认为我无法正确打开文件.如何打开"这个类似文件的对象,以便csv.reader可以解析它?

Which seems closer but obviously still wrong. Reading the csv docs, I assume I am failing to open the file correctly. How do I "open" this file-like object so that csv.reader can parse it?

推荐答案

response.content提供字节.您需要将其解码为字符串:

response.content provides bytes. You need to decode this to a string:

foo = response.content.decode('utf-8')

然后使用io.StringIO将此字符串传递给csv阅读器:

Then pass this string to the csv reader using io.StringIO:

import io
reader = csv.reader(io.StringIO(foo))

这篇关于如何阅读CSV Django HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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