You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Twilio官方示例代码发送SMS出现KeyError问题求助

Fixing the KeyError in Your Twilio SMS Code

Hey there, let's break down what's going wrong here and fix it step by step!

The Root Cause of the KeyError

That error is happening because you're using your full Twilio Account SID (ACa30b8fa59e7eba0e6dc5dbedaf5e8fcb) as the name of the environment variable you're trying to read with os.environ[]. But your system doesn't have an environment variable with that long SID as its name—so Python can't find it and throws a KeyError.

Step 1: Set Up Your Environment Variables Correctly

First, you need to create environment variables that store your Twilio credentials. Let's use clear, standard names for these:

  • For macOS/Linux (run these in your terminal before executing your script):
    export TWILIO_ACCOUNT_SID="ACa30b8fa59e7eba0e6dc5dbedaf5e8fcb"
    export TWILIO_AUTH_TOKEN="Your-Redacted-Auth-Token-Here"
    
  • For Windows Command Prompt:
    set TWILIO_ACCOUNT_SID=ACa30b8fa59e7eba0e6dc5dbedaf5e8fcb
    set TWILIO_AUTH_TOKEN=Your-Redacted-Auth-Token-Here
    
  • If you're using an IDE like PyCharm or VS Code, you can add these environment variables directly in your run configuration settings instead of using the terminal.

Step 2: Update Your Code to Use the Correct Variable Names

Now modify your script to read from the environment variables you just set up:

# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Your Account Sid and Auth Token stored as environment variables
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)

message = client.messages \
    .create(
         body="What is up Med",
         from_='+Your-Twilio-Phone-Number',
         to='+Your-Target-Phone-Number'
     )

print(message.sid)

Quick Extra Checks to Ensure Success

  • If you're using a Twilio trial account, make sure both your from_ number (the Twilio number) and to number are verified in your Twilio console.
  • Double-check that you copied your Auth Token correctly—no extra spaces or missing characters.
  • To confirm your environment variables are set properly, you can add a quick print statement before initializing the Client:
    print("Account SID:", os.environ.get('TWILIO_ACCOUNT_SID'))
    
    If this prints your correct SID, you know the environment variable is working.

内容的提问来源于stack exchange,提问作者Alex Kopels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 06:39:09