Getting a view does not return a valid response error message on my flask chatbot

久未见 提交于 2020-03-25 17:43:08

问题


Trying to create a whatsapp bot on Twilio that limits the number of requests a user can make within a 24 hour period.

However, when I send through a request I get this error message on ngrok

  File "C:\Users\User\Documents\GitHub\gradientboostwhatsapp\venv\lib\site-packages\flask\app.py", line 2097, in make_response
    "The view function did not return a valid response. The"
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

This is what I see on my twilio console:

MESSAGE
Internal Server Error

and on my terminal:

File "C:\Users\User\Documents\GitHub\gradientboostwhatsapp\venv\lib\site-packages\flask\app.py", line 2097, in make_response
    "The view function did not return a valid response. The"

Here is the code I wrote

from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse
import random
from pathlib import Path
from twilio.rest import Client
from datetime import datetime
import pytz
import re

app = Flask(__name__)
#this will store information about user session such as the time of user's first request and request counter
sessionStorage = {}
#addng user to session storage with current time and setting request counter to 0
time = datetime.now(pytz.timezone('Africa/Harare'))
counter = 0
def add_user(user):
    sessionStorage[user] = {}
    #time when first session starts
    sessionStorage[user][time] = datetime.now(pytz.timezone('Africa/Harare'))
    sessionStorage[user][counter] = 0
#checking if user can perform a request and updating time if required
def request_check(user):
    difference = sessionStorage[user][time] - datetime.now(pytz.timezone('Africa/Harare'))
    #check if it has been 24 hours after first request, if so then reset request counter and set last request time to current time
    sessionStorage[user][counter] = 0
    sessionStorage[user][time] = datetime.now(pytz.timezone('Africa/Harare'))
    #if user requests exceed 5 then do not allow any more requests
    if sessionStorage[user][counter] > 5:
        return False
    #in other cases allow user to continue requesting
    return True
#function to increment request counter for current user
def increment_request_counter(user):
    sessionStorage[user][counter] +=1

@app.route('/bot', methods=['POST'])
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    #extract phone number from ngrok
    number = request.values.get('From', '')
    #remove non numerical values
    cleaned_number = re.sub('[^0-9]', '', number)
    msg = resp.message()
    #create new user
    add_user(user=cleaned_number)
    responded = False
    if request_check(user=cleaned_number):
        if incoming_msg == 'help':
            output = 'Introduction text.'
            msg.body(output)
        responded = True
        if 'testing' in incoming_msg:
            msg.body(cleaned_number)
            responded = True
        if 'a' in incoming_msg:
            pre = 'More text
            msg.body(pre)
            responded = True
        if 'b' in incoming_msg:
            pre = 'Test text'
            msg.body(pre)
            responded = True
        if 'c' in incoming_msg:
            pre = 'I do not currently have any stats challanges, but will be adding a few soon.'
            msg.body(pre)
            responded = True
        if not responded:
            msg.body('Test message.')
            return str(resp)
        increment_request_counter(user=cleaned_number)

if __name__ == '__main__':
    app.run(debug=True)

The problem started when I tried to add the logic to limit the number of requests a user can make within a 24 hour period


回答1:


The problem is that you are not returning a response which flask thinks as a valid response. You can read more about responses in flask here.

So in your case add a return after all of your ifs under if request_check(user=cleaned_number): in bot() method. Also you should not return None. I think you are looking to return a json (just an advice).

For example:

@app.route('/bot', methods=['POST'])
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    #extract phone number from ngrok
    number = request.values.get('From', '')
    #remove non numerical values
    cleaned_number = re.sub('[^0-9]', '', number)
    msg = resp.message()
    #create new user
    add_user(user=cleaned_number)
    responded = False
    if request_check(user=cleaned_number):
        if incoming_msg == 'help':
            output = 'Introduction text.'
            msg.body(output)
            responded = True
            return "My Message"



来源:https://stackoverflow.com/questions/60822008/getting-a-view-does-not-return-a-valid-response-error-message-on-my-flask-chatbo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!