'raise KeyError(key) from None

I am getting an error message and have no idea how to proceed, the error message is displayed below. I have downloaded all necessary tools for it to run however it seems to be having a problem with the keys. I have inputted them right however to keep my account private I have substituted the account username and password hidden. Thanks in advance

C:\Users\User\Downloads\real-time-intrinio-python-master\real-time-intrinio-python-master> python realtime.py AAPL 
Using Ticker: AAPL 
Traceback (most recent call last):
  File "realtime.py", line 18, in <module>
     r=requests.get(auth_url, headers={"Authorization": "Basic %s" % base64.b64encode(os.environ['myUsername'] + ":" + os.environ['myPassword'])}) 
  File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 669, in __getitem__
     raise KeyError(key) from None 
KeyError: 'myUsername'

This is the code I am using and line 18 is "r=requests.get(auth_url, headers..."

import websocket
import _thread
import time
import requests
import base64
import json
import sys
import os
from requests.auth import HTTPBasicAuth

try:
    print ("Using Ticker: " + str(sys.argv[1]))
except:
    print ("Please include ticker as first argument")
    sys.exit()

auth_url = "https://realtime.intrinio.com/auth";
r=requests.get(auth_url, headers={"Authorization": "Basic %s" % base64.b64encode(os.environ['7641353c8540cd7c795c96f097185c26'] + ":" + os.environ['c15d32295cf254ab57d5523c5bf95f80'])})

socket_target = "wss://realtime.intrinio.com/socket/websocket?token=%s" % (r.text)

def on_message(ws, message):
    try:
        result = json.loads(message)
        print (result["payload"])
    except:
        print (message)

def on_error(ws, error):
    print ("###ERROR### " + error)

def on_close(ws):
    print ("###CONNECTION CLOSED###")

def on_open(ws):
    def run(*args):
        security = "iex:securities:" + str(sys.argv[1]).upper()
        message = json.dumps({"topic": security,"event": "phx_join","payload": {},"ref": "1"})
        ws.send(message)
    thread.start_new_thread(run, ())


websocket.enableTrace(True)
ws = websocket.WebSocketApp(socket_target, on_message = on_message, on_error = on_error, on_close = on_close)
ws.on_open = on_open
ws.run_forever()


Solution 1:[1]

To summarize and add to the conversation.

As chickity already pointed out, you need to set your environment variables. This can be down with Python or via CMD/terminal.

# Set environment variables
os.environ['myUsername'] = 'username'
os.environ['myPassword'] = 'secret'

However, doing this in a script can lead to the potential fatal mistake that your secrets/passwords are added to git. Therefore, it is advised to do this via CMD. To permanently add the environment variables use setx. For some more details and caveats see this post.

setx myUsername username
setx myPassword secret

After doing this, you could change line 18 to:

# Get environment variables and create request
USER = os.getenv('myUsername')
PASSWORD = os.environ.get('myPassword')
token = base64.b64encode(f"{USER}:{PASSWORD}")
r=requests.get(auth_url, headers={"Authorization": f"Basic {token}"})

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Chiel