如何使用flask将JSON数据显示到前端接口?

时间:2019-09-17 00:38:13

标签: python json python-3.x flask flask-restful

我有一个flask restful api,可从JSON文件中获取问题和可能的答案,并在浏览器中按原样显示。从JSON文件中选择下一个问题取决于上一个问题的所选选项。 我的应用程序运行正常,但是现在我要使用URL进行输入,我希望前端页面使用单选按钮显示问题及其所有选项,并且输入必须通过选择单选按钮,然后按一个按钮(提交/下一个等等)。

这是我的烧瓶代码:

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=True, use_reloader=False)

这是我的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."
            }
        }
    }
]

}

如何连接前端,以便用户可以使用美观的视图回答问题,而无需更改URL。


PS:正如我提到的,除了第一级问题外,任何其他问题都取决于先前的答案,因此一次应该看到一个问题。 第一页应显示单选按钮列表以选择问卷。

2 个答案:

答案 0 :(得分:1)

这是一个非常广泛的问题-您实际上是在问我如何使网站的字体结尾。

有很多选择。您可以使用React之类的框架构建客户端应用程序,该框架将使用javascript调用您的API,然后向用户显示信息。

或者,您可以在服务器上呈现页面并将其返回给用户,而不是原始json。在您的情况下,请使用Flask templates。上一个链接包含flask的创建者编写的“ Flask Mega教程”。关于在一个SO答案中构建网站前端的讨论实在太多了,该教程将为您提供一个使用python构建网站的绝佳起点。

答案 1 :(得分:0)

看到它是一个宁静的api,有两种方法可以解决这个问题,

  1. 您可以使用Flask模板显示网站的主要布局,然后使用一些JavaScript来使用AJAX在网站上进行更新。

  2. 您可以全力以赴,学习诸如React,Vue或Angular之类的前端javascript框架。如果您希望建立意识形态瓶,您将很乐意做出反应!

如有其他疑问,请评论!