Getting incorrect 'api_key' or 'access token' error since last 2 days

madhavgoswami93
I have been using below code to generate an kite object. Code used to work 3 days back, but has started giving error . have checked kite.trade, API keys are set to expire on 12 June. Could not figure out reason. Can somebody help @sujith

time generated : 2022-06-03 10:14:53
Traceback (most recent call last):
File "/Users/madhavg/Documents/python_fun/blackpearl/Kite_Connect.py", line 164, in
quote = kite.quote("NSE:INFY")
File "/Users/madhavg/opt/anaconda3/envs/kite/lib/python3.8/site-packages/kiteconnect/connect.py", line 577, in quote
data = self._get("market.quote", params={"i": ins})
File "/Users/madhavg/opt/anaconda3/envs/kite/lib/python3.8/site-packages/kiteconnect/connect.py", line 842, in _get
return self._request(route, "GET", url_args=url_args, params=params, is_json=is_json)
File "/Users/madhavg/opt/anaconda3/envs/kite/lib/python3.8/site-packages/kiteconnect/connect.py", line 918, in _request
raise exp(data["message"], code=r.status_code)
kiteconnect.exceptions.TokenException: Incorrect `api_key` or `access_token`.



-- Python code

from kiteconnect import KiteConnect
import logger
import os
from dotenv import load_dotenv
from selenium import webdriver
import time
import os
from selenium import webdriver
import datetime as dt
from urllib import parse
from furl import furl



mylogger = logger.get_logger("Kite_Connect")


class Kite_Connect:
def __init__(self):

if self.should_generate_fresh_token():
mylogger.debug("generating access token and request token")
self.autologin()
self.kite = self.get_access()

def __repr__(self):
return "Kite Connect"

def should_generate_fresh_token(self):
if "time_generated" in os.environ:
time_generated = dt.datetime.strptime(
os.environ.get("time_generated"), "%Y-%m-%d %H:%M:%S"
)
print ("time generated : ", time_generated)
else:
time_generated = dt.datetime(1970, 1, 1, 0, 0, 0, 0)
today = dt.datetime.now()
refresh_threshold = dt.datetime(today.year, today.month, today.day, 4,0,0)
if (
(time_generated < refresh_threshold)
or (os.environ.get("access_token") is None)
or (os.environ.get("request_token") is None)
):
return True
else:
return False

def autologin(self):

dotenv_path = os.path.join(os.path.join(os.getcwd(), "sensitive"), ".env")
load_dotenv(dotenv_path)
dotenv_path2 = os.path.join(
os.path.join(os.getcwd(), "sensitive"), ".access_token"
)
load_dotenv(dotenv_path2)

kite = KiteConnect(api_key=os.environ.get("api_key"))
# service = webdriver.chrome.service.Service(r"/usr/local/bin/chromedriver")
service = webdriver.chrome.service.Service(r"/Users/madhavg/Downloads/chromedriver")
service.start()
options = webdriver.ChromeOptions()
options.add_argument("--headless")
options = options.to_capabilities()
# driver = webdriver.Remote(service.service_url, options)
chrome_path = r"/usr/local/bin/chromedriver"
driver = webdriver.Chrome(executable_path=chrome_path)
# driver = webdriver.Chrome(ChromeDriverManager().install())

print(kite.login_url())

driver.get(kite.login_url())
driver.implicitly_wait(10)
username = driver.find_element_by_xpath(
"/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[1]/input"
)
password = driver.find_element_by_xpath(
"/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[2]/input"
)
username.send_keys(os.environ.get("user_name"))
password.send_keys(os.environ.get("password"))
driver.find_element_by_xpath(
"/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[4]/button"
).click()
pin = driver.find_element_by_xpath(
"/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[2]/div/input"
)
pin.send_keys(os.environ.get("pin"))
driver.find_element_by_xpath(
"/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[3]/button"
).click()
time.sleep(10)

print(driver.current_url)
# print("request_token : ", driver.current_url.split("=")[4])
# os.environ["request_token"] = parse.parse_qs(parse.urlparse(driver.current_url).query)['request_token'][0]
os.environ["request_token"]=furl(driver.current_url).args['request_token'].strip()

# print(os.environ["request_token"])
print ('1')
access_token = ''
driver.quit()
try :
print (os.environ["request_token"])
print (os.environ["api_secret"])
data = kite.generate_session(
os.environ["request_token"], api_secret=os.environ.get("api_secret")
)
# print(data)
access_token = data["access_token"]
kite.set_access_token(data["access_token"])
request_token = os.environ["request_token"]
except Exception as err:
mylogger.error(
" %s"
% ( err)
)
if err == """kiteconnect.exceptions.TokenException: Incorrect `api_key` or `access_token`.""" or err == """Token is invalid or has expired.""":
print (os.environ['request_token'])
print(os.environ['access_token'])
# Kite_Connect = KC.Kite_Connect()
# kite = Kite_Connect.kite
# self.kite = kite

if access_token!= '':
access_token= os.environ['access_token']

with open(
os.path.join(os.path.join(os.getcwd(), "sensitive"), ".access_token"), "w"
) as file:
file.write('access_token="{}"'.format(os.environ['access_token']))
file.write("\n")
file.write('request_token="{}"'.format(os.environ['request_token'] ))
file.write("\n")
file.write(
'time_generated="{}"'.format(
dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
)
)

# os.environ["access_token"] = access_token

def get_access(self):

kite = KiteConnect(api_key=os.environ.get("api_key"))

kite.set_access_token(os.environ.get("access_token"))
return kite


if __name__ == "__main__":

dotenv_path = os.path.join(os.path.join(os.getcwd(), "sensitive"), ".env")
load_dotenv(dotenv_path)
dotenv_path2 = os.path.join(os.path.join(os.getcwd(), "sensitive"), ".access_token")
load_dotenv(dotenv_path2)
print(os.environ.get("api_key"))
print(os.environ.get("api_secret"))
Kite_Connect = Kite_Connect()

# kite = Kite_Connect.get_access()
kite = Kite_Connect.kite

# Fetch quote details
quote = kite.quote("NSE:INFY")
print(quote)

# Fetch last trading price of an instrument
ltp = kite.ltp("NSE:INFY")
print(ltp)

# Fetch order details
orders = kite.orders()
print(orders)
# Fetch position details
positions = kite.positions()
print(positions)

# Fetch holding details
holdings = kite.holdings()
print(holdings)

data = kite.historical_data(
738561, dt.date.today() - dt.timedelta(30), dt.date.today(), "day"
)
# print(data)

Tagged:
  • SRIJAN
    SRIJAN edited June 2022
    Your are using incorrect access token as the error message says. Use the correct access token and it will work.
Sign In or Register to comment.