【问题标题】:How to return also json and render_template in Flask?如何在 Flask 中也返回 json 和 render_template?
【发布时间】:2018-09-12 20:07:55
【问题描述】:

我已经使用 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()

还有我的简单 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>

【问题讨论】:

  • 嗯,这看起来应该对我有用,你能尝试重新解释什么不起作用吗?
  • 现在我的应用只返回一个render_template,我想返回一个json和一个render_template。

标签: python html json templates flask


【解决方案1】:

您可以根据请求类型对退货进行分支。如果请求是 html 文本,则返回 render_template。如果请求是json,则返回json。例如:

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

【讨论】:

    【解决方案2】:

    @dvnguyen 的回答很好,但您可以考虑为 html 和 json 创建不同的路由。例如:

    @app.route("/web/result")
    def result_html():
       response = MyService.retrieve_response()
       return render_template("index.html", value=response)
    
    @app.route("/api/result")
    def result_json():
       response = MyService.retrieve_response()
       return jsonify(response)
    

    /api 或 /web 前缀使意图清晰,也简化了单元测试。

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 2020-04-16
      • 1970-01-01
      • 2022-08-19
      相关资源
      最近更新 更多