【发布时间】:2019-05-01 07:09:19
【问题描述】:
我是 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.py
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
【问题讨论】:
-
不确定,但也许您想测试带或不带参数的 GET。
-
使用 GET 进行测试是什么意思?当我使用这个时:“if request.method == "GET":" - 它允许我使用 URL 从争论中获取结果 - 如果我没有输入任何参数,它不会将我重定向到form.html
-
我的意思是
http://138.10.2.1:8000/sample?psi=1&lavr=1&dsc=...是带参数的GET,http://138.10.2.1:8000/sample是不带参数的。对于这两种情况,您需要不同的输出。 -
哦..我明白了..所以如果我不输入任何参数,我如何才能显示 .html?这将允许我在 html 表单中附加一个文件并创建到 POST 并获得相同的 json 结果
标签: python python-3.x post flask get