Run OLEDB query to OSI PI archive from plotly callback.
The OLEDB query normally runs as:
"
conn = Dispatch('ADODB.Connection')
conn.Open('Provider=PISDK; Data Source=your_server;')
...
conn.Close()
"
This works fine from an individual python script, however if running from plotly callback, it could have the "CoInitialize has not been called" error.
That is because Dash callbacks often run in separate threads or processes that do not automatically initialize the COM library, which is required by ADODB.Connection.
A standalone script works because Python's main thread typically handles COM initialization implicitly.
TO make it work in a callback function, use the pythoncom library to manage the COM threading model within your Dash callbacks.
1. Import pythoncom
2. Call pythoncom.CoInitialize()
3. Call pythoncom.CoUninitialize() when finished
import pythoncom
from win32com.client import Dispatch
from dash import dcc, html, Input, Output, Dash
@app.callback(...)
def update_data_from_pi(n):
# Initialize COM library for this thread
pythoncom.CoInitialize()
try:
conn = Dispatch('ADODB.Connection')
conn.Open('Provider=PISDK; Data Source=your_server;')
...
conn.Close()
except Exception as e:
print(e)
finally:
# Uninitialize COM library
pythoncom.CoUninitialize()