Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am working on a project, which is in Python and Django. Whenever I try to select MS word file and upload it, the browser shows me this error.
com_error at /Review_page/
(-2147221008, 'CoInitialize has not been called.', None, None)

I have done all the things which were necessary like: created middleware files, applied middleware into the Django setting but don't know how to solve it. If anyone knows about it, any help will be appreciated.

What I have tried:

Here is the custom middleware.py file code which I have created:
Python
import win32com.client
import threading

# Create a thread-local storage for the COM object
_thread_local = threading.local()

def get_com_object():
    if not hasattr(_thread_local, "Word.Application"):
        
        # Initialize COM based on the version of pywin32 
        if hasattr(win32com.client, "pythoncom"):
            win32com.client.pythoncom.CoInitialize()
        else:
            win32com.client.CoInitialize()

        # Create the COM object
        _thread_local.com_object = win32com.client.Dispatch("Word.Application") 

    return _thread_local.com_object 

class COMMiddleware:
    def __init__(self, get_response):  
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request) 

        # Uninitialize COM after the response is sent
        if hasattr(_thread_local, "Word.Application"):
            del _thread_local.com_object
 
            # Uninitialize COM
            win32com.client.CoUninitialize()

        return response

And here is the views.py file code:
Python
def my_view(request):
    com_object = get_com_object()
    result = com_object.visible()

    return HttpResponse(result)
Posted
Updated 2-Oct-23 5:01am
v5
Comments
Richard MacCutchan 26-Sep-23 3:43am    
Some part of your code has not initialised the COM interface, so you need to find out where. But there is nothing anyone here can do without much more detailed information.
Richard MacCutchan 26-Sep-23 8:29am    
OK, you have shown the code, but where does the error occur?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900