Django.fun

com_error when trying to get COM object with win32com.client from Django view

I am trying to connect a SAP GUI session to my Django project so I can interact with it, by using win32com.client to work with COM objects. When working from the shell I have no problem at all to get this working by running the following code:

sap_gui = win32com.client.GetObject("SAPGUI")
application = sap_gui.GetScriptingEngine
connection = application.Children(0)
session = connection.Children(0)

If I start the server with this code in the views.py Django module this also works, and I can get the session info displayed in my Django view. However, I want to be able to connect and disconnect such session by hand, since different users will need to connect to different sessions, and by running the code at start I can only stick to the first session.

I have been trying to get this working by defining the following view in views.py:

def dashboard(request):
  if request.method == 'POST' and 'SAP_button' in request.POST:
    # Get the COM object (SAP session in this case)
    sap_gui = win32com.client.GetObject("SAPGUI") # ERROR HERE
    application = sap_gui.GetScriptingEngine
    connection = application.Children(0)
    session = connection.Children(0)
    # This is just a test to see if I get the desired output from the COM object
    test = session.info.User
  return render(request, 'Users/dashboard.html', {'test': test})

The corresponding html code for the form ('Users/dashboard.html') is the following:

<form action="", method="POST">{% csrf_token %}
    <button type="submit", name="SAP_button">Connect SAP</button>
</form>

When clicking the button the request works as expected but I get the following com_error: (-2147221020, 'Invalid syntax', None, None). This error comes from the very first line when trying to get the SAP COM object: sap_gui = win32com.client.GetObject("SAPGUI").

It looks like the code that is run from a view can't access the COM object but I am pretty new to Django and even researching for such error I have not been able to understand why this is happening or a possible solution/workaround. Any help is appreciated.

Answers: 1

Answered by xgsktx, Sept. 14, 2021, 2:04 p.m.

After some more research I ended up finding out the code after a POST request from a Django view is run in a different thread, and therefore COM libraries need to be initialized for such thread. I solved this issue by adding the following line of code before getting the COMobject:

import pythoncom
...
pythoncom.CoInitialize()
sap_gui = win32com.client.GetObject("SAPGUI") # ERROR SOLVED
...