Django翻译上传文档,输出下载的翻译文档时报错com_error at /translator/translator_upload/

我是 Web 开发新手,正在尝试在 Django 中创建一个语言翻译应用程序来翻译上传的文档。它依赖于pdf和docx之间的一系列相互转换。当我的代码输出下载的翻译文档时,有时得到这个错误com_error at /translator/translator_upload/ (-2147221008, 'CoInitialize has not been called.', None, None),我只是有时得到这个错误,而不是在重试之后(所以不是连续两次)。这是完整的错误消息:

Exception Location: C:\Users\John\tutorial-env\Lib\site-packages\win32com\client\dynamic.py, line 86, in _GetGoodDispatch
Raised during:  translator_upload.views.translateFile
Python Executable:  C:\Users\John\tutorial-env\Scripts\python.exe
Python Version: 3.11.4
Python Path:    
['C:\\djangoProjects\\mysite',
 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\python311.zip',
 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\DLLs',
 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311\\Lib',
 'C:\\Users\\John\\AppData\\Local\\Programs\\Python\\Python311',
 'C:\\Users\\John\\tutorial-env',
 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages',
 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\win32',
 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\win32\\lib',
 'C:\\Users\\John\\tutorial-env\\Lib\\site-packages\\Pythonwin']

下面是我的代码:

from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_protect
from .models import TranslatedDocument
from .forms import UploadFileForm
from django.core.files.storage import FileSystemStorage
import docx
from pdf2docx import parse
from docx2pdf import convert
import time #remove




# Create your views here.

@csrf_protect
def translateFile(request) :
    file = ''
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            uploaded_file = request.FILES['file']
            fs = FileSystemStorage()
            filename = fs.save(uploaded_file.name, uploaded_file)
            uploaded_file_path = fs.path(filename)
            
            file = (converter(uploaded_file_path))
        response = HttpResponse(file, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="' + filename + '"'
        return response
    
    else:
        form = UploadFileForm()
    return render(request, 'translator_upload/upload.html', {'form': form})    


def reConverter(inputDocxPath):
    return convert(inputDocxPath)

def translateDocx(aDocx, stringOfDocPath):
    docx_file = stringOfDocPath
    myDoc = docx.Document(docx_file)

    #translation logic



    myDoc.save(stringOfDocPath)
    return reConverter(stringOfDocPath)


    
#stringOfDocPath is used as convert() requires file path, not file object(myDoc)

def converter(inputPdfPath):
    # convert pdf to docx
    
    pdf_file = inputPdfPath
    docx_file = inputPdfPath + '.docx'


    parse(pdf_file, docx_file) #,  start=0, end=3)
    myDoc = docx.Document(docx_file)
    return translateDocx(myDoc, docx_file)

我试过加上这个但没用:

pythoncom.CoInitialize()
# Use the COM object here
pythoncom.CoUninitialize()

【以下回答由 GPT 生成】

问题的原因是在Django应用程序的translateFile函数中,由于缺少适当的初始化调用,导致CoInitialize has not been called错误。为了解决这个问题,你可以在translateFile函数中添加适当的初始化调用。

以下是一个可能的解决方案:

import pythoncom    # 导入pythoncom模块

# 翻译上传的文件
@csrf_exempt
def translateFile(request):
    # 添加CoInitialize调用
    pythoncom.CoInitialize()

    try:
        # 你的翻译逻辑
        # ...

        # 返回翻译后的文档
        # ...

    except Exception as e:
        # 错误处理逻辑
        # ...

    finally:
        # 添加CoUninitialize调用,确保已释放资源
        pythoncom.CoUninitialize()

通过在函数开头调用pythoncom.CoInitialize()来初始化,然后在函数末尾调用pythoncom.CoUninitialize()来释放资源,可以解决CoInitialize has not been called错误。

请注意,CoInitializeCoUninitialize是在使用win32com模块之前和之后的必要调用。确保在使用这个模块之前调用CoInitialize并在使用完之后调用CoUninitialize以确保正确性。

希望这个解决方案能够在你的应用程序中解决问题。如果问题仍然存在,请进一步检查你的代码或提供更多细节,以便我们能够提供更准确的解决方案。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^