问题
I am trying to include TWILIO API to my project. It should send sms. I have finished tutorial, but then i get error Credentials are required to create a TwilioClient. I have credentials in .env file and then i try to import them to settings and then get this credentials from settings to views.
This is when i get error.
.env
TWILIO_ACCOUNT_SID= 'xxxxxxxxxxxxxxxxxxxxxx'
TWILIO_AUTH_TOKEN= 'xxxxxxxxxxxxxxxxxxxxxxx'
TWILIO_NUMBER= 'xxxxxxxxxxxxxxxxxx'
settings.py
import os
TWILIO_ACCOUNT_SID = os.getenv('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOKEN = os.getenv('TWILIO_AUTH_TOKEN')
TWILIO_NUMBER = os.getenv('TWILIO_NUMBER')
SMS_BROADCAST_TO_NUMBERS = [
'+111111111',
]
views
from django.conf import settings
from django.http import HttpResponse
from twilio.rest import Client
def broadcast_sms(request):
message_to_broadcast = ("Have you played the incredible TwilioQuest "
"yet? Grab it here: https://www.twilio.com/quest")
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
for recipient in settings.SMS_BROADCAST_TO_NUMBERS:
if recipient:
client.messages.create(to=recipient,
from_=settings.TWILIO_NUMBER,
body=message_to_broadcast)
return HttpResponse("messages sent!", 200)
and here is when code work, but i want to import this from settings..
# def sms(request):
# TWILIO_ACCOUNT_SID = "xxxxxxxxxxxxxxxxxxxxxxx"
# TWILIO_AUTH_TOKEN = "xxxxxxxxxxxxxxxxx"
# TWILIO_NUMBER = "xxxxxxxxxxxxx"
# message_to_broadcast = ("Have you played the incredible TwilioQuest "
# "yet? Grab it here: https://www.twilio.com/quest")
#
# client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
# for recipient in settings.SMS_BROADCAST_TO_NUMBERS:
# if recipient:
# client.messages.create(to=+xxxxxxxxx,
# from_=+xxxxxxxxxx,
# body=message_to_broadcast)
# return HttpResponse("messages sent!", 200)
Any idea how to solve this?
回答1:
So you are using a .env file rather than setting your OS's environmental variables? If so, there is and article below, pointing to https://github.com/theskumar/python-dotenv.
How To Set Environment Variables
回答2:
replace line
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
with
client = Client("y3234hgfds","etgwegpi34y35")
where y3234hgfds
is the TWILIO_ACCOUNT_SID
from your settings and etgwegpi34y35
is the TWILIO_AUTH_TOKEN
来源:https://stackoverflow.com/questions/61042648/twilio-api-error-credentials-are-required-to-create-a-twilioclient-django