我想发一个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))
答案 0 :(得分:1)
Twilio员工在这里 - 问题可能是因为您没有在此视图周围提供csrf_exempt
装饰器。 Django将触发安全错误,因为它正在从twilio.com收到HTTP POST
请求。除非您免除csrf令牌,否则Django将不接受任何HTTP POST
请求。
您是否考虑过为Django使用django-twilio包?使用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。
查看installation instructions即可开始使用。