[英]how to send JSON to HTML file using flask?
I'm at a beginner at coding and i'm stuck at the final closing :|我是编码的初学者,我被困在最后的闭幕式上:| i'm using python 2.7 this is my serever.py我正在使用 python 2.7 这是我的serever.py
from flask import Flask, render_template,request,jsonify
import requests
import json
import new
app = Flask(__name__)
#serve homepage
@app.route('/', methods=["GET","POST"])
def homepage():
return render_template('page2.html')
@app.route('/page3.html', methods=["POST"])
def result_matchup():
h= request.form['h']
a= request.form['a']
l= request.form['l']
p= request.form['p']
result = json.dumps(new.calc(h,a,l,p))
return render_template('page3.html',result=result)
if __name__ == "__main__":
app.run(debug=True)
when i ask for return result
for checking myself, this is the output:当我要求return result
以检查自己时,这是输出:
{"f": 197.1, "k": 196}
this is my page3.html:这是我的 page3.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center><h1>Final = {{f}}</h1></center>
</body>
</html>
the output for all this is "Final = " ,while I expect for Final = 197.1.所有这些的输出是"Final = " ,而我期望Final = 197.1。
what am I doing wrong?我究竟做错了什么? any help?有什么帮助吗?
thanks!谢谢!
I assume new.calc
returns a dictionary.我假设new.calc
返回一个字典。 No need to use json.dumps
to stringify that before passing to your template.在传递给您的模板之前,无需使用json.dumps
进行字符串化。 So instead try:因此,请尝试:
result = new.calc(h,a,l,p)
result
should now be a dictionary, with the keys 'f'
and 'k'
result
现在应该是一个字典,键为'f'
和'k'
Therefor in the template you should access this dictionary, as you would in python:因此,在模板中你应该访问这个字典,就像你在 python 中一样:
<center><h1>Final = {{result['f']}}</h1></center>
I would also advise using a later version of python since 2.7
is unsupported now, and making this change early will prevent you having to make already written code, 3.x
compatible later.我还建议使用更高版本的 python,因为现在不支持2.7
,并且尽早进行此更改将防止您必须使已经编写的代码与3.x
兼容。
Two suggestions:两个建议:
You serialize your result as JSON writing result = json.dumps(new.calc(h,a,l,p))
.您将结果序列化为 JSON 写入result = json.dumps(new.calc(h,a,l,p))
。 However, you should directly pass a Python object to render_template
.但是,您应该直接将 Python 对象传递给render_template
。 In fact, that's one of the strengths of Jinja templating: You do not need to pass JSON, but you can handle Python objects directly.事实上,这是 Jinja 模板的优势之一:您不需要传递 JSON,但您可以直接处理 Python 对象。 So just write result = new.calc(h,a,l,p)
.所以只需写result = new.calc(h,a,l,p)
。
Second, within the Jinja template, you have to access the objects as you passed them through your render_template
function.其次,在 Jinja 模板中,您必须在通过render_template
函数传递对象时访问它们。 In your case, <center><h1>Final = {{result['f]}}</h1></center>
should do the job.在您的情况下, <center><h1>Final = {{result['f]}}</h1></center>
应该可以完成这项工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.