小编Vil*_*uck的帖子

如何在Flask中还返回json和render_template?

我已经用Flask在Python中实现了一项服务,以创建服务器。我的服务(MyService)从用户处查询并返回响应,例如聊天机器人。因此,我想同时返回修改HTML模板的文本响应和包含将服务用作命令行的响应的json。目前我的服务仅返回渲染模板,我该怎么办?

我的应用程式:

app = Flask(__name__)

@app.route("/")
def main():
    return render_template('index.html')

@app.route("/result", methods=['POST', 'GET'])
def result():
   if request.method == 'POST':
       query = request.form['query']
       response = MyService.retrieve_response(query)
       return render_template("index.html", value=response)

if __name__ == "__main__":
    app.run()
Run Code Online (Sandbox Code Playgroud)

和我简单的index.html:

<!DOCTYPE html>
<html lang="en">

<body>

<h2>Wellcome!</h2>

<form action="http://localhost:5000/result" method="POST">
  Make a question:<br>
  <br>
  <input type="text" name="query" id="query">
  <br><br>
  <input type="submit" value="submit"/>
</form>


<br>
<h3>Response is: </h3>
<br>
{{value}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

html python templates json flask

2
推荐指数
2
解决办法
3679
查看次数

标签 统计

flask ×1

html ×1

json ×1

python ×1

templates ×1