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
JavaScript
x
4
1
TWILIO_ACCOUNT_SID= 'xxxxxxxxxxxxxxxxxxxxxx'
2
TWILIO_AUTH_TOKEN= 'xxxxxxxxxxxxxxxxxxxxxxx'
3
TWILIO_NUMBER= 'xxxxxxxxxxxxxxxxxx'
4
settings.py
JavaScript
1
9
1
import os
2
3
TWILIO_ACCOUNT_SID = os.getenv('TWILIO_ACCOUNT_SID')
4
TWILIO_AUTH_TOKEN = os.getenv('TWILIO_AUTH_TOKEN')
5
TWILIO_NUMBER = os.getenv('TWILIO_NUMBER')
6
SMS_BROADCAST_TO_NUMBERS = [
7
'+111111111',
8
]
9
views
JavaScript
1
16
16
1
from django.conf import settings
2
from django.http import HttpResponse
3
from twilio.rest import Client
4
5
6
def broadcast_sms(request):
7
message_to_broadcast = ("Have you played the incredible TwilioQuest "
8
"yet? Grab it here: https://www.twilio.com/quest")
9
client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
10
for recipient in settings.SMS_BROADCAST_TO_NUMBERS:
11
if recipient:
12
client.messages.create(to=recipient,
13
from_=settings.TWILIO_NUMBER,
14
body=message_to_broadcast)
15
return HttpResponse("messages sent!", 200)
16
and here is when code work, but i want to import this from settings..
JavaScript
1
15
15
1
# def sms(request):
2
# TWILIO_ACCOUNT_SID = "xxxxxxxxxxxxxxxxxxxxxxx"
3
# TWILIO_AUTH_TOKEN = "xxxxxxxxxxxxxxxxx"
4
# TWILIO_NUMBER = "xxxxxxxxxxxxx"
5
# message_to_broadcast = ("Have you played the incredible TwilioQuest "
6
# "yet? Grab it here: https://www.twilio.com/quest")
7
#
8
# client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
9
# for recipient in settings.SMS_BROADCAST_TO_NUMBERS:
10
# if recipient:
11
# client.messages.create(to=+xxxxxxxxx,
12
# from_=+xxxxxxxxxx,
13
# body=message_to_broadcast)
14
# return HttpResponse("messages sent!", 200)
15
Any idea how to solve this?
Advertisement
Answer
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.