Flask:对单个URL使用[GET,POST]功能

问题描述 投票:1回答:3

我是Flask的新手,想知道是否可以使用相同的URL在html和查询中显示表单以显示某些内容

理想情况下,我希望发生以下结果。

如果我要通过这样做在138.10.2.1/sample中创建一个查询:

http://138.10.2.1:8000/sample?psi=1&lavr=1&dsc=1&ifsc=1&ics=1&eng=3&ol1=1&ol2=1&reso=1&educ=1&listen=1&time=1&probe=1&unders=1

它会显示:

*something in json format*

在网页上

否则,如果我直接谈到这个:

http://138.10.2.1:8000/sample

它将引导我到一个带有表单的.html页面,以填充或允许用户附加文件以供使用和上传以显示json格式的转换文件。

这是我的代码

sample.朋友

from flask import Flask, flash, request, redirect, url_for, make_response, send_from_directory, render_template
import convert as ps

app = Flask(__name__)

@app.route("/sample", methods=["GET", "POST"])
def query_strings():

    #This is not working: if request.method == "POST":

        args1 = request.args["psi"]
        args2 = request.args["lavr"]
        args3 = request.args["dsc"]
        args4 = request.args["ifsc"]
        args5 = request.args["ics"]
        args6 = request.args["eng"]
        args7 = request.args["ol1"]
        args8 = request.args["ol2"]
        args9 = request.args["reso"]
        args10 = request.args["educ"]
        args11 = request.args["listen"]
        args12 = request.args["time"]
        args13 = request.args["probe"]
        args14 = request.args["unders"]

        args_list = [args1, args2, args3, args4, args5, args6, args7, args8,args9, args10, args11, args12, args13, args14]


        result = ps.execute(args_list)
        response = app.response_class(
            response=result,
            status=200,
            mimetype='application/json'
        )
        return response
    #This is my html form: return render_template("form.html")
if __name__ == '__main__':
   app.run(debug = True)

现在,我可以拥有的是运行查询,但是如果我刚刚输入,我会被提示输入我声明的参数:

http://138.10.2.1:8000/sample
python python-3.x post flask get
3个回答
1
投票

如果长度为0,您可以检查参数的数量并返回HTML表单,如下所示:

    # if there are no arguments provided, show HTML form
    if len(request.args) == 0:
        return render_template("form.html")

此外,不需要将每个参数存储为单独的变量,然后将它们组合到一个列表中。 request.args已经是一个字典了,所以你可以简单地获得参数名称和值的列表:

list(request.args.keys()) # list of argument names eg. ['psi', 'lavr', 'dsc', 'ifsc'...]
list(request.args.values()) # list of argument values eg. [1, 1, 1, 1...]

您可以检查参数名称是否与所需的集匹配:

if set(argument_names) == {"psi","lavr","dsc","ifsc","ics","eng","ol1","ol2","reso","educ","listen","time","probe","unders"}:
        # return JSON

总的来说,您的代码看起来像这样:

from flask import Flask, request, render_template
import json

app = Flask(__name__)

@app.route("/sample", methods=["GET", "POST"])
def query_strings():
    # if there are no arguments provided, show HTML form
    if len(request.args) == 0:
        return render_template("form.html")

    argument_names = list(request.args.keys())

    # if the argument list is valid
    if set(argument_names) == {"psi","lavr","dsc","ifsc","ics","eng","ol1","ol2","reso","educ","listen","time","probe","unders"}:
        # return JSON
        response = app.response_class(
                response=json.dumps(request.args),
                status=200,
                mimetype='application/json'
        )
        return response

    return "Invalid arguments"

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

这将:

  • 如果加载没有参数的form.html,请显示/sample
  • 如果使用有效参数加载/sample,则将参数显示为JSON(例如./sample?psi=1&lavr=1&dsc=1&ifsc=1&ics=1&eng=3&ol1=1&ol2=1&reso=1&educ=1&listen=1&time=1&probe=1&unders=1
  • 在任何其他情况下显示“无效的参数”

1
投票

哦..我知道..如果我没有输入任何参数,怎么能显示.html?这将允许我在html表单中附加一个文件并创建POST并获得相同的json结果

根据您对问题的评论和您发布的示例代码,我假设您可能正在寻找类似这样的内容:

@app.route("/sample", methods=["GET", "POST"])
def query_strings():
    args1 = request.args.get("psi")
    args2 = request.args.get("lavr")
    args3 = request.args.get("dsc")
    args4 = request.args.get("ifsc")
    args5 = request.args.get("ics")
    args6 = request.args.get("eng")
    args7 = request.args.get("ol1")
    args8 = request.args.get("ol2")
    args9 = request.args.get("reso")
    args10 = request.args.get("educ")
    args11 = request.args.get("listen")
    args12 = request.args.get("time")
    args13 = request.args.get("probe")
    args14 = request.args.get("unders")

    args_list = [
        args1, args2, args3, args4, args5, args6, args7, args8,
        args9, args10, args11, args12, args13, args14
    ]

    if not all(args_list):
        return render_template('form.html')
    else:
        result = ps.execute(args_list)
        response = app.response_class(
            response=result,
            status=200,
            mimetype='application/json'
        )
        return response

在这种情况下,如果您在GET请求中不提供参数,它将呈现具有html格式的模板。

而且不是总是检查请求方法我建议你看看Flask的MethodView。使用它你可以很好地将逻辑拆分为请求与查询字符串中的参数和表单提交与json:http://flask.pocoo.org/docs/1.0/api/#flask.views.MethodView


0
投票

试试这段代码,我希望它会对你有所帮助。默认情况下,它使用GET方法,因此无法正常工作。当您单击提交按钮时,它会调用POST方法。

from flask import Flask, flash, request, redirect, url_for, make_response, send_from_directory, render_template
import convert as ps

app = Flask(__name__)

@app.route("/sample", methods=["GET", "POST"])
def query_strings():

    if request.method == "POST":

        args1 = request.args["psi"]
        args2 = request.args["lavr"]
        args3 = request.args["dsc"]
        args4 = request.args["ifsc"]
        args5 = request.args["ics"]
        args6 = request.args["eng"]
        args7 = request.args["ol1"]
        args8 = request.args["ol2"]
        args9 = request.args["reso"]
        args10 = request.args["educ"]
        args11 = request.args["listen"]
        args12 = request.args["time"]
        args13 = request.args["probe"]
        args14 = request.args["unders"]

        args_list = [args1, args2, args3, args4, args5, args6, args7, args8,args9, args10, args11, args12, args13, args14]


        result = ps.execute(args_list)
        response = app.response_class(
            response=result,
            status=200,
            mimetype='application/json'
        )
        # return response
        return render_template("form.html", response = response)
    return render_template("form.html")

    #This is my html form: return render_template("form.html")
if __name__ == '__main__':
   app.run(debug = True)
© www.soinside.com 2019 - 2024. All rights reserved.