在Flask中设计简单的问卷REST API

时间:2019-06-21 06:07:41

标签: python reactjs api flask

我正在用Flask开发一个简单的问卷调查REST API。该应用程序由前端和后端两部分组成。

前端功能:

  1. 显示调查表列表(用户可以选择他/她将通过的调查表)

  2. 进行问答(向用户显示问题和可能的答案)

后端功能:

  1. 从JSON文件加载问卷结构

  2. 用于用户应用程序的REST API(调查问卷列表)

  3. 当对话结束(回答了最后一个问题)时,后端应将对话历史记录到控制台中。日志应包含第一个问题和所有后续用户答案。示例:Are you hungry?: Yes -> Pizza -> Yes

限制

  1. 服务器不应通过一个响应返回整个对话框树。系统应该是交互式的(应仅加载下一个问题和答案变体)

  2. 与一个问题相关的答案数量限制为5

我是设计REST API的新手,我的问题是如何有效地设计API以完成给定的任务。这就是我后端代码的样子,我无法弄清楚如何使其能够满足挑战的要求。

'''
Dialog example:

Are you hungry? (Yes/No)
   Yes:
       What would you like to eat? (Hamburger/Pizza/Pop Corn/Chicken)
           Hamburger:
               Nice, I will order a hamburger for you!
           Pizza:
               Would you like pizza with mushrooms? (Yes/No)
                   Yes:
                       Ok, I will order the best pizza in town for you
                   No:
                       No? Well... stay hungry then
   No:
       Ok. Call me when you're hungry.
'''

from flask import Flask, jsonify


question_list = {
                    "Start": 
                        {
                            "question": "Are you Hungry?",
                            "options": ["Yes", "No"]
                        },
                    "Yes": 
                        {
                            "question": "What would you like to eat?",
                            "options": ["Hamburger", "Pizza", "Pop Corn", "Chicken"]
                        },
                    "No": 
                        {
                            "question": "Ok, call me when you are hungry.",
                            "options": [] # empty array means end of questions
                        },
                    "Pizza":
                        {
                            "Start":
                            {
                                "question": "Would you like pizza with mushroom?",
                                "options": ["Yes", "No"]
                            },
                            "Yes":
                            {
                                "question": "OK, I will order the best pizza in town for you.",
                                "options": [] # empty array means end of questions
                            },
                            "No":
                            {
                                "question": "No? Well... stay hungry then.",
                                "options": [] # empty array means end of questions
                            }
                        }                    
                }

app = Flask(__name__)

@app.route('/')
def StartQuestionnaire():
        return jsonify(question_list["Start"])

# last selected option will be passed as keyword argument
@app.route('/<string:option>')
def GetQuestion(option):
    return jsonify(question_list[option])

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

1 个答案:

答案 0 :(得分:0)

好的,所以我自己弄清楚了。并与希望解决此问题的任何人分享答案。 我现在正在从json文件中读取问卷调查数据。我现在有两条路线

  1. 获得第一个问题。
  2. 根据先前的选择获得下一个问题。

data.json

{
    "questionnaire_0" :
    [
        {
            "question": "Are you Hungry?",
            "options": ["Yes", "No"]
        },
        {
            "Yes": {
                "question": "What would you like to eat?",
                "options": ["Hamburger", "Pizza", "Pop Corn", "Chicken"]
            },
            "No": {
                "message": "OK, call me when you are hungry."
            }
        },
        {
            "Hamburger": {
                "message": "Nice, I will order a hamburger for you."
            },
            "Pizza": {
                "question": "Would you like pizza with mushroom?",
                "options": ["Yes", "No"]
            },
            "Pop Corn": {
                "question": "Would you like pop corn with cheese?",
                "options": ["Yes", "No"]
            },
            "Chicken": {
                "question": "Would you like chicken with cheese?",
                "options": ["Yes", "No"]
            }
        },
        {
            "Pizza": {
                "Yes": {
                    "message": "Ok, i will order the best pizza in town for you."
                },
                "No": {
                    "message": "No? Well... stay hungry then."
                }
            },
            "Pop Corn": {
                "Yes": {
                    "message": "Ok, i will order the best pop corn in town for you."
                },
                "No": {
                    "message": "No? Well... stay hungry then."
                }
            },
            "Chicken": {
                "Yes": {
                    "message": "Ok, i will order the best chicken in town for you."
                },
                "No": {
                    "message": "No? Well... stay hungry then."
                }
            }
        }
    ],
    "questionnaire_1":
    [
        {
            "question": "Are you bored?",
            "options": ["Yes", "No"]
        },
        {
            "Yes": {
            "question": "What would you like me to play?",
            "options": ["Song", "Movie", "Music", "Ted Talk"]
            },
            "No": {
                "message": "OK, call me when you are bored."
            }
        },
        {
            "Song": {
                "message": "Nice, I will play your favorite song."
            },
            "Movie": {
                "question": "Would you like to watch action movie?",
                "options": ["Yes", "No"]
            },
            "Music": {
                "question": "Would you like relaxing music?",
                "options": ["Yes", "No"]
            },
            "Ted Talk": {
                "question": "Would you like me to play simon sinek talk?",
                "options": ["Yes", "No"]
            }
        },
        {
            "Movie": {
                "Yes": {
                    "message": "Ok, i am playing Avengers."
                },
                "No": {
                    "message": "No? Well... stay bored then."
                }
            },
            "Music": {
                "Yes": {
                    "message": "Ok, i will play the most relaxing music."
                },
                "No": {
                    "message": "No? Well... stay bored then."
                }
            },
            "Ted Talk": {
                "Yes": {
                    "message": "Ok, get ready to feel inspired."
                },
                "No": {
                    "message": "No? Well... stay bored then."
                }
            }
        }
    ]
}

app.py

from flask import Flask, jsonify
import json
import sys


# global variables
num = 0
last_choice = 'empty'
questionnaire_key = ''
user_choice = []
data = {}

app = Flask(__name__)

with open('static/data.json') as f:
    data = json.load(f)

print(data, file=sys.stdout)

@app.route('/<int:index>/Start')
def StartQuestionnaire(index):
    global num, last_choice, questionnaire_key, user_choice
    num = 0
    last_choice = 'empty'
    user_choice.clear()
    questionnaire_key = 'questionnaire_' + str(index)


    user_choice.append(data[questionnaire_key][0]['question'])
    print(user_choice, file=sys.stdout)
    return jsonify(data[questionnaire_key][0])

# last selected option will be passed as keyword argument
@app.route('/<int:index>/<string:option>')
def GetQuestion(index, option):
    global num, last_choice, questionnaire_key
    num = num + 1
    response = {}

    user_choice.append(option)

    if last_choice != 'empty':
        response = data[questionnaire_key][num][last_choice][option]
    else:
        if option != 'Yes' and option != 'No':
            last_choice = option

        response = data[questionnaire_key][num][option]

    if option == 'No' or num == len(data[questionnaire_key]) - 1:
        for elem in user_choice:
            print(elem, file=sys.stdout)

    return jsonify(response)

if __name__ == '__main__':
    app.run(debug=False, use_reloader=False)