Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

Using COM Objects with CherryPy

If you use COM objects with CherryPy (2.1 or greater) you might be greeted with a traceback similar to one of these:

Traceback (most recent call last):
...
  File "server.py", line 84, in test
    ou = GetObject('LDAP://OU=YourContainer, DC=YourSite, DC=com')
  File "c:\python24\lib\site-packages\win32com\client\__init__.py", line 73, in GetObject
    return Moniker(Pathname, clsctx)
  File "c:\python24\lib\site-packages\win32com\client\__init__.py", line 88, in Moniker
    moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
com_error: (-2147221020, 'Invalid syntax', None, None)

or

Traceback (most recent call last):
...
  File "server.py", line 78, in test
    word = Dispatch('Word.Application')
  File "c:\python24\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 79, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
com_error: (-2147221008, 'CoInitialize has not been called.', None, None)

CherryPy 2.1 and up uses a threaded HTTP server by default. CherryPy 2.0 did not, and thus you had to do nothing special to use COM objects. To use COM in threads, you have to make a few simple changes. Try adding these lines to your server file:

from pythoncom import CoInitialize, CoUninitialize

"""
Define your site classes here...
"""

def InitializeCOM(threadIndex):
    CoInitialize()

def UninitializeCOM(threadIndex):
    CoUninitialize()

cherrypy.engine.on_start_thread_list = [InitializeCOM]
cherrypy.engine.on_stop_thread_list = [UninitializeCOM]

That will setup COM access for each of your threads. See ticket 194 for more details.

Older versions

replace this with this
2.2engine.on_start_thread_listserver.on_start_thread_list
engine.on_stop_thread_list server.on_stop_thread_list
2.1server.on_start_thread_listserver.onStartThreadList
server.on_stop_thread_list server.onStopThreadList

Hosted by WebFaction

Log in as guest/cpguest to create tickets