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

Vil*_*uck 2 html python templates json flask

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

fea*_*ool 6

@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)
Run Code Online (Sandbox Code Playgroud)

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


dvn*_*yen 5

您可以根据请求类型分出退货。如果请求是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)
Run Code Online (Sandbox Code Playgroud)