简体   繁体   English

如何从 django.http.response.StreamingHttpResponse 生成 csv 文件

[英]How to make the csv file from django.http.response.StreamingHttpResponse

I have StreamingHttpResponse and it downloads the csv file in brower.我有StreamingHttpResponse ,它会在浏览器中下载 csv 文件。

Now I want to use this in testcase现在我想在测试用例中使用它

response = self.client.get('/lusers/?&export=csv')

response is StreamingHttpResponse responseStreamingHttpResponse

How can I make the csv file from this (not via browser)如何从中制作csv文件(不是通过浏览器)

and check the contents??并检查内容??

self.assertContains(response, "dataincsv")

You can make text string from StreamingHttpResponse like this:您可以像这样从StreamingHttpResponse制作文本字符串:

str_response = '\n'.join(s.decode('U8') for s in response)

or或者

str_response = '\n'.join(map(lambda s: s.decode('U8'), iter(response)))

and check content with:并检查内容:

self.assertContains(str_response, "dataincsv")

StreamingHttpResponse is iterable object, and you can iteratate through this object any way you need. StreamingHttpResponse是可迭代的 object,您可以按需要以任何方式迭代此 object。

For example if you want to write to file you could do something like:例如,如果你想写入文件,你可以这样做:

# ...
for line in response:
    some_file.write(line)
# ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM