'I have a trouble using win32com in DJango

I made a python module getting data and making DataFrame from another window Application by win32com.

running django server, this module works well at first call. but from the second call, this module can't work. it seems that before created win32com object interrupt new created win32com object.

views.py

from django .http import HttpResponse
from myModele import *
from django .views .decorators .csrf import csrf_exempt
import json
   
@csrf_exempt
def test (request ):
   df = getStock('param1', 'param2', 'param3' )
   return json.dumps(HttpResponse(result))

myModule.py

import json
import pandas as pd
import win32com.client
import pythoncom

def getStock(code, name, startDay):

    pythoncom.CoInitialize() # It seems to have been used incorrectly.

    cpOhlc = win32com.client.Dispatch('CpSysDib.StockChart') # on the second running module, error happen here
    
    today = datetime.today()
    _startDay = datetime.strptime(startDay, '%Y%m%d')
    dif = today - _startDay
    qcy = math.trunc(int(dif.days))

    cpOhlc.SetInputVAlue(0, code)
    cpOhlc.SetInputVAlue(1, ord('2'))
    cpOhlc.SetInputVAlue(4, qcy)
    cpOhlc.SetInputVAlue(5, [0,5])
    cpOhlc.SetInputVAlue(6, ord('D'))
    cpOhlc.SetInputVAlue(9, ord('1'))
    cpOhlc.BlockRequest()
    count = cpOhlc.GetHeaderValue(3)

    data = []
    date = []
    for i in reversed(range(count)):
        __date = str(cpOhlc.GetDataValue(0,i))
        _date = pd.Timestamp(
            year=int(__date[0:4]),
            month=int(__date[4:6]),
            day=int(__date[6:8])
        )
        date.append(_date)
            
        data.append([
            cpOhlc.GetDataValue(1,i)
        ])
    
    
    df = pd.DataFrame(data, columns=[name], index=date)
    
    pythoncom.CoUninitialize() # It seems to have been used incorrectly.

    return df


error code

  File "C:\Users\jo\AppData\Local\Programs\Python\Python39-32\lib\site-packages\pandas\core\indexing.py", line 931, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "C:\Users\jo\AppData\Local\Programs\Python\Python39-32\lib\site-packages\pandas\core\indexing.py", line 1566, in _getitem_axis
    self._validate_integer(key, axis)
  File "C:\Users\jo\AppData\Local\Programs\Python\Python39-32\lib\site-packages\pandas\core\indexing.py", line 1500, in _validate_integer
    raise IndexError("single positional indexer is out-of-bounds")
IndexError: single positional indexer is out-of-bounds


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source