[英]Twilio/Django not receiving response SMS
我想輸入一個twilio號碼,並向用戶提出一系列問題。 如果這是他們第一次發短信,則應創建一個新的“呼叫者”。 如果他們以前玩過,我想查詢“ last_question”,我們問他們並問他們適當的問題。 我的下面代碼沒有產生SMS響應,並且沒有Twilio錯誤“ HTTP檢索失敗”。
在models.py我有
class Caller(models.Model):
body = models.CharField(max_length=200)
from_number = models.CharField(max_length=20)
last_question = models.CharField(max_length=2, default="0")
def __unicode__(self):
return self.body
在views.py中
def hello_there(request):
body = request.REQUEST.get('Body', None)
from_number = request.REQUEST.get('From', None)
try:
caller = Caller.objects.get(from_number = from_number)
except Caller.DoesNotExist:
caller = None
if caller:
if caller.last_question == "0":
if body == "Password":
message = "Welcome to the game. What is 3 + 4?"
caller.last_question = "1"
else:
message = "What is the password?"
else:
message = "you broke me"
else:
new_caller = Caller(body=body, from_number=from_number, last_question="0")
new_caller.save()
message = "New user created"
resp = twilio.twiml.Reponse()
resp.sms(message)
return HttpResponse(str(resp))
Twilio員工在這里-問題可能是因為您沒有在此視圖周圍提供csrf_exempt
裝飾器。 Django將收到來自twilio.com的HTTP POST
請求,從而觸發安全錯誤。 除非您將其免除,否則Django將不接受沒有csrf令牌的任何HTTP POST
請求。
您是否考慮過將django-twilio軟件包用於Django? 使用twilio進行開發時,它將使您的生活更加輕松。 這就是django-twilio的視圖:
from django_twilio.decorators import twilio_view
@twilio_view
def hello_there(request):
body = request.REQUEST.get('Body', None)
from_number = request.REQUEST.get('From', None)
try:
caller = Caller.objects.get(from_number=from_number)
except Caller.DoesNotExist:
caller = None
if caller:
if caller.last_question == "0":
if body == "Password":
message = "Welcome to the game. What is 3 + 4?"
caller.last_question = "1"
else:
message = "What is the password?"
else:
message = "you broke me"
else:
new_caller = Caller(body=body, from_number=from_number, last_question="0")
new_caller.save()
message = "New user created"
resp = twilio.twiml.Reponse()
resp.sms(message)
return resp
twilio_view
裝飾器將提供csrf豁免,並確保所有請求都是真實的並且來自twilio.com。
請查看安裝說明以開始使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.