You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask聊天机器人服务中同时返回JSON与render_template?

实现Flask服务同时返回HTML模板与JSON响应

没问题,我来帮你搞定这个需求。核心思路是根据请求的类型(或参数)来判断返回哪种格式的响应——浏览器请求就返回渲染后的HTML,命令行/API调用就返回JSON。下面是具体的实现方案:

1. 修改/result路由逻辑

首先,我们需要在/result路由里先处理用户的查询,生成机器人的响应内容,然后根据请求的特征(比如请求头的Accept字段,或者自定义的参数)来决定返回格式。

完整代码示例

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# 模拟你的聊天机器人响应生成函数
def get_bot_response(user_query):
    # 这里替换成你实际的机器人逻辑
    return f"收到你的查询:{user_query},这是机器人的回复~"

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

@app.route("/result", methods=['POST', 'GET'])
def result():
    # 获取用户查询:如果是POST取form数据,GET取query参数
    if request.method == 'POST':
        user_query = request.form.get('query')  # 假设前端表单的name是query
    else:
        user_query = request.args.get('query')
    
    # 生成机器人响应
    bot_response = get_bot_response(user_query)

    # 判断返回格式:两种方式选一种即可
    # 方式1:通过请求头的Accept字段判断(推荐,符合REST规范)
    if request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html:
        return jsonify({
            "user_query": user_query,
            "bot_response": bot_response
        })
    # 方式2:通过URL参数指定格式(比如/result?format=json)
    # if request.args.get('format') == 'json':
    #     return jsonify({
    #         "user_query": user_query,
    #         "bot_response": bot_response
    #     })
    else:
        # 返回渲染后的HTML模板,把bot_response传给模板
        return render_template('result.html', response=bot_response)

2. 关键部分解释

  • 获取用户查询:兼容POST(表单提交)和GET(URL参数)两种方式,你可以根据实际需求调整。
  • 判断返回格式:
    • 方式1利用HTTP请求头的Accept字段:当命令行用curl或Postman请求时,通常会发送Accept: application/json,这时就返回JSON;浏览器默认会发送Accept: text/html,就返回HTML。
    • 方式2用URL参数更直观,比如命令行调用curl "http://localhost:5000/result?query=你好&format=json"就能直接拿到JSON。
  • JSON返回:用Flask的jsonify函数,它会自动设置正确的Content-Type头为application/json。
  • HTML返回:把机器人响应传入模板,比如你的result.html里可以用{{ response }}来展示内容。

3. 测试方法

  • 浏览器测试:访问主页提交表单,会跳转到渲染后的结果页面。
  • 命令行测试:
    # POST请求
    curl -X POST -d "query=你好呀" http://localhost:5000/result -H "Accept: application/json"
    # 或者GET请求带format参数
    curl "http://localhost:5000/result?query=你好呀&format=json"
    
    这样就能拿到JSON格式的响应了。

内容的提问来源于stack exchange,提问作者Villuck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:15:24