使用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) andtonumber 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:
If this prints your correct SID, you know the environment variable is working.print("Account SID:", os.environ.get('TWILIO_ACCOUNT_SID'))
内容的提问来源于stack exchange,提问作者Alex Kopels
相关产品推荐
相关产品推荐

