简体   繁体   English

从 None 提高 KeyError(key)

[英]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..."这是我正在使用的代码,第 18 行是“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()

To summarize and add to the conversation.总结并添加到对话中。

As chickity already pointed out, you need to set your environment variables.正如chickity 已经指出的那样,您需要设置环境变量。 This can be down with Python or via CMD/terminal.这可以通过 Python 或通过 CMD/终端来解决。

# 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.但是,在脚本中执行此操作可能会导致将您的机密/密码添加到 git 的潜在致命错误。 Therefore, it is advised to do this via CMD.因此,建议通过 CMD 执行此操作。 To permanently add the environment variables use setx .要永久添加环境变量,请使用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:执行此操作后,您可以将第 18 行更改为:

# 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}"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM