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:
import win32com.client
import threading
_thread_local = threading.local()
def get_com_object():
if not hasattr(_thread_local, "Word.Application"):
if hasattr(win32com.client, "pythoncom"):
win32com.client.pythoncom.CoInitialize()
else:
win32com.client.CoInitialize()
_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)
if hasattr(_thread_local, "Word.Application"):
del _thread_local.com_object
win32com.client.CoUninitialize()
return response
And here is the
views.py file code:
def my_view(request):
com_object = get_com_object()
result = com_object.visible()
return HttpResponse(result)