获取TypeError:预期的str,字节或os.PathLike对象,而不是InMemoryUploadedFile

时间:2018-07-12 07:25:56

标签: python django

def post(self, request):
    form = CsvUploadForm(request.POST, request.FILES)

    if form.is_valid():
        with open(request.FILES['csv']) as csv_source:
            has_header = csv.Sniffer().has_header(csv_source.read(1024))
            csv_source.seek(0)
            reader = csv.DictReader(csv_source)
            ....
            ....

    return HttpResponse("file Uploaded")

使用上面的代码,我试图上传一个csv文件并阅读它。但我收到以下错误。

  

以open(request.FILES ['csv'])作为文件:   TypeError:预期的str,字节或os.PathLike对象,而不是InMemoryUploadedFile

我在这里想念什么?

Django 2.0.7 python 3.5

2 个答案:

答案 0 :(得分:2)

正如@ Daniel Roseman所说,您可以直接将文件流用作,

def post(self, request):
    form = CsvUploadForm(request.POST, request.FILES)

    if form.is_valid():
        reader = csv.DictReader(request.FILES['csv'])
        ....
        ....

    return HttpResponse("file Uploaded")

答案 1 :(得分:0)

尝试将请求读入BytesIO流中,然后对该对象执行操作。

def post(self, request):
    form = CsvUploadForm(request.POST, request.FILES)

    if form.is_valid():
        csv_source = BytesIO(request.FILES['csv'].read())
        has_header = csv.Sniffer().has_header(csv_source.read(1024))
        csv_source.seek(0)
        reader = csv.DictReader(csv_source)
        ....
        ....

    return HttpResponse("file Uploaded")