Проблема с кодировкой, когда я использую NamedTemporaryFile

Я хочу создать временный файл и отправить его клиенту. Файл, который я отправляю, имеет проблему с кодировкой. Я создаю временный файл с помощью функции NamedTemporaryFile().
Когда я ставлю кодировку="utf-8" в NamedTemporaryFile, я получаю следующую ошибку:

** PermissionError: [WinError 32] The process cannot access the file because this file is in use by another process: 'C:\\..\\AppData\\Local\\Temp\\tmpglkdf_2o'  

(Когда я не пишу encoding="utf-8", все идет хорошо, я могу скачать файл, но с проблемой кодировки)

views.py

from django.http.response import HttpResponse
from django.http import StreamingHttpResponse
from wsgiref.util import FileWrapper
import mimetypes
import pandas as pd
import pdb;

def page(request):
    object = pd.DataFrame(data={"ColumnWithé": ["éà"]})
    fileErr(request, object=object)

def fileErr(request, object=None):
    # Create a temp file
    if(isinstance(object, pd.DataFrame)):
        print("========== IF ==========")
        #pdb.set_trace()
        f = NamedTemporaryFile(delete=False, encoding="utf-8")
        object.to_csv(f, sep=',')
        request.session["errpath"] = f.name.replace("\\","/")
    # Send the temp file when the user click on button
    else:
        print("========== ELSE ==========")
        #pdb.set_trace()
        filename="err.csv"
        file_path = request.session.get("errpath") 
        response = StreamingHttpResponse(FileWrapper(open(file_path, 'rb')),
                                        content_type=mimetypes.guess_type(file_path)[0])
        response['Content-Length'] = os.path.getsize(file_path)
        response['Content-Disposition'] = "Attachment;filename=%s" % filename
        return response

.html

<a href="{% url 'downloadfile' %}"> 

urls.py

urlpatterns = [path("download-file", views.fileErr, name="downloadfile"),]

Результат, когда я не пишу encoding="utf-8"
enter image description here

Вернуться на верх