gpt4 book ai didi

csv - 在 drf 中导入 csv 文件

转载 作者:行者123 更新时间:2023-12-04 08:42:26 25 4
gpt4 key购买 nike

我正在尝试创建一个 View 以使用 drf 和 django-import-export 导入 csv。
我的例子(我正在做婴儿步骤和调试来学习):

class ImportMyExampleView(APIView):
parser_classes = (FileUploadParser, )

def post(self, request, filename, format=None):
person_resource = PersonResource()
dataset = Dataset()
new_persons = request.data['file']
imported_data = dataset.load(new_persons.read())
return Response("Ok - Babysteps")
但我收到此错误(使用 postman ):
Tablib has no format 'None' or it is not registered.
更改为 imported_data = Dataset().load(new_persons.read().decode(), format='csv', headers=False)我收到这个新错误:
InvalidDimensions at /v1/myupload/test_import.csv
No exception message supplied
有没有人有任何提示或可以指出引用?我正在关注这个 site ,但我必须“翻译”为 drf。

最佳答案

从婴儿步开始是一个好主意。我建议先让一个独立的脚本工作,以便您可以检查文件是否可以读取和导入。
如果您可以设置断点并进入 django-import-export 源代码,这将为您节省大量时间来了解正在发生的事情。
示例测试函数(基于 example app ):

def test_import():
with open('./books-sample.csv', 'r') as fh:
dataset = Dataset().load(fh)
book_resource = BookResource()
result = book_resource.import_data(dataset, raise_errors=True)
print(result.totals)
您可以对此进行调整,以便导入您自己的数据。一旦一切正常,您就可以将它与您的 post() 集成。功能。
我建议让示例应用程序运行,因为它将演示导入是如何工作的。 InvalidDimensions意味着您尝试加载的数据集与 Dataset 预期的格式不匹配.尝试删除 headers=False arg 或显式声明标题( headers=['h1', 'h2', 'h3'] - 交换标题的正确名称)。

关于csv - 在 drf 中导入 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64490444/

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