So, I ended up solving this not using pyodbc but using pymssql instead. I'm not sure if that help OP though. Just figured I'd share.
import dotenv, os, pymssql, win32security, win32con
from modules.utility import write_to_json
dotenv.load_dotenv()
def impersonate_user(username, password, domain):
"""Impersonate the security context of another user."""
handler = win32security.LogonUser(
username, domain, password,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT)
win32security.ImpersonateLoggedOnUser(handler)
write_to_json(get_records_from_database(), 'JSON_FILE_NAME')
handler.Close()
def terminate_impersonation():
"""Terminate the impersonation of another user."""
win32security.RevertToSelf()
def connect_pymssql():
con = pymssql.connect(
server=os.getenv('DB_SERVER'),
database=os.getenv('DB_NAME'),
port=os.getenv('DB_PORT')
)
cur = con.cursor()
return con, cur
def get_records_from_database():
con, cur = connect_pymssql()
cur.execute(f"select * from [TABLE];")
result = cur.fetchall()
con.close()
return [list(x) for x in result] if result else None