pyad doesn't like querying outside of MainThread
LivInTheLookingGlass opened this issue · 2 comments
LivInTheLookingGlass commented
This bug has been seen by a bunch of people online, although it looks like they never got down to the root cause.
- https://stackoverflow.com/questions/44109346/pywintypes-com-error-when-running-pyad-adgroup-on-flask
- https://stackoverflow.com/questions/47735809/running-pyad-in-flask
- https://www.reddit.com/r/flask/comments/7ix26p/af_using_pyad_to_query_ad_and_create_a_security/
I think I have boiled it down to the simplest reliable cause.
from pyad import pyad
from threading import Thread
query = "CN=blah,OU=blah,DC=example,DC=corp,DC=domain,DC=com"
def test():
print(pyad.from_dn(query))
t = Thread(target=test)
t.start()
Expected result:
It should print something like <ADGroup 'CN=blah,OU=blah,DC=example,DC=corp,DC=domain,DC=com'>
Actual result:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "<stdin>", line 2, in test
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyad\pyad.py", line 18, in from_dn
q = ADObject.from_dn(distinguished_name,options)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyad\adobject.py", line 131, in from_dn
return cls(distinguished_name, None, options)
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyad\adobject.py", line 88, in __init__
self.__set_adsi_obj()
File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pyad\adobject.py", line 76, in __set_adsi_obj
self._ldap_adsi_obj = self.adsi_provider.getObject('', self.__ads_path)
File "<COMObject ADsNameSpaces>", line 2, in getObject
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221020), None)
LivInTheLookingGlass commented
Now, I'm entirely unsure what the problem is here, but it clearly doesn't like being run outside of MainThread
papylhomme commented
For future references, forcing the initialization of pythoncom from the thread did the trick for me (from the answer to https://stackoverflow.com/questions/47735809/running-pyad-in-flask)
import pythoncom
# From thread
pythoncom.CoInitialize()