2013-08-05 68 views
1

我想輸入一個twilio號碼併爲用戶啓動一系列問題。如果這是他們第一次發短信,應該創建一個新的「呼叫者」。如果他們以前玩過,我想查看「last_question」,我們問他們並問他們適當的問題。我的下面的代碼不會產生SMS響應和Twilio錯誤「HTTP檢索失敗」。Twilio/Django沒有收到回覆短信

在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

從瀏覽器上方看到時是否看到任何錯誤?你得到了什麼迴應? –

+0

當我使用瀏覽器時,我得到「空值在列」身體「違反非空約束」這是有道理的,因爲我不發送任何東西,但我發送文本我本身必須有一個「身體」被髮送。 – theptrk

+0

是的,你可以單獨測試這2行:'resp = twilio.twiml.Reponse()'和'resp.sms('some message')'?我沒有閱讀文檔,但他們做了什麼? –

回答

1

Twilio員工在這裏 - 這個問題可能是因爲你沒有提供解決此視圖csrf_exempt裝飾。 Django會因爲收到來自twilio.com的HTTP POST請求而觸發安全錯誤。 Django不會接受任何HTTP POST沒有csrf標記的請求,除非您將其豁免。

你有沒有想過使用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開始。