繁体   English   中英

twilio:从 None 提高 KeyError(key)

[英]twilio: raise KeyError(key) from None

我正在尝试使用 twilio 发送消息,但出现以下错误。 如何解决此错误?

import os
from twilio.rest import Client

account_sid = os.environ['testtest']
auth_token = os.environ['testtesttest']
client = Client(account_sid, auth_token)

message = client.messages \
                .create(
                     body="Join Earth's mightiest heroes. Like Kevin Bacon.",
                     from_='+16813203595',
                     to='+12345678'
                 )

print(message.sid)
    raise KeyError(key) from None
KeyError: 'testtest'

为了轻松测试您的代码:一个简单的解决方法是暂时不使用环境变量,将您的代码重构为:

from twilio.rest import Client

account_sid = 'testtest'
auth_token = 'testtesttest'
client = Client(account_sid, auth_token)

message = client.messages \
                .create(
                     body="Join Earth's mightiest heroes. Like Kevin Bacon.",
                     from_='+16813203595',
                     to='+12345678'
                 )

print(message.sid)

一旦满意,然后考虑并从 twilio 得到响应,您可以切换到 env 变量

设置环境变量取决于操作系统。

以下是链接列表,具体取决于您使用的机器

  1. Windows 10 https://superuser.com/questions/949560/how-do-i-set-system-environment-variables-in-windows-10
  2. Linux https://linuxize.com/post/how-to-set-and-list-environment-variables-in-linux/
  3. Mac https://apple.stackexchange.com/questions/106778/how-do-i-set-environment-variables-on-os-x

您还需要设置您的 twilio 帐户并从他们auth_token获得您的account_sidauth_token

对于未来的任何人,如果您想要这个问题的简单答案。

在 Twilio 的示例代码中,它有这两行

account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']

您实际上并未在这些行中放置您的 Twilio 帐户 sid 和令牌。 保持原样。 不要更改这些行。 不要添加您的帐户 sid 和您的令牌。 而是在命令提示符下键入:

export TWILIO_ACCOUNT_SID=your_SID_account
export TWILIO_AUTH_TOKEN=your_auth_token

现在运行脚本,脚本将提取您的环境密钥。 以这种方式确保您的信息安全:)

嘿伙计们,这很简单,就像您对任何其他字典一样赋值!

account_sid=os.environ['TWILIO_ACCOUNT_SID']='value of sid'
auth_token=os.environ['TWILIO_AUTH_TOKEN']='value of auth token'

暂无
暂无

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

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