5

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()
Chiel
  • 1,865
  • 1
  • 11
  • 24
Lasheen Lartey
  • 497
  • 2
  • 5
  • 8
  • 3
    basically it's saying the environment variables in the OS assigned to `'myUsername'` or `'myPassword'` have not yet been set. On `cmd` terminal, try `echo %myUsername%` and `echo %myPassword%` – chickity china chinese chicken Aug 02 '17 at 23:20
  • To correct the error @downshift pointed out, at the `cmd` prompt you will need to `set myUsername=something` (and/or `set myPassword=somethingelse`) which will set them temporarily. To set them permanently on Windows, you can define the environment variable(s) and their values is the Settings | Control Panel | System | Advanced system settings, where there's an "Environment Variables..." button. – martineau Aug 03 '17 at 00:25
  • Thanks for the responses. Sorry, but I'm a complete beginner to python and setting environment variables. I would like to set this variable permanently, so do I need to set as a 'user variables for user' or 'system variables'. Also do I just simply add new and type myUsername as variable name and "32rqwefrwaf33f" as variable value. Or does a seperate document need to be made. – Lasheen Lartey Aug 03 '17 at 07:53
  • I've got it working no worries thanks – Lasheen Lartey Aug 03 '17 at 11:45

1 Answers1

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}"})
Chiel
  • 1,865
  • 1
  • 11
  • 24