gpt4 book ai didi

python - 如何在 Django 中测试文件响应?

转载 作者:太空狗 更新时间:2023-10-29 22:25:09 25 4
gpt4 key购买 nike

我有一个生成并返回 CSV 文件的 API:

def getCSV():
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=export.csv'
writer = csv.writer(response, csv.excel)

# ... Write some CSV content ...

return response

当我从浏览器调用它时,它工作正常,但我不知道如何编写调用 API 的测试并检查 CSV 内容是否正确。

如果我:

c = Client()
r = c.get('/my/export/api')
print(r.content)

这只打印了三个字节,很可能在概念上是完全错误的。

如何在我的测试中获取 CSV 文件响应的内容?

最佳答案

How to read a csv django http response

import csv
import io

def test_csv_export(self):

response = self.client.get('/my/export/api')
self.assertEqual(response.status_code, 200)

content = response.content.decode('utf-8')
cvs_reader = csv.reader(io.StringIO(content))
body = list(cvs_reader)
headers = body.pop(0)

print(body)
print(headers)

关于python - 如何在 Django 中测试文件响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41121785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com