我可以使用 Flask 和 flask-resul 来 return JSON 到 API 调用但 HTML 到浏览器吗?

Can I use Flask and flask-restul to return JSON to API calls but HTML to browsers?

我正在为个人项目构建一个网络应用程序,我希望能够为 JSON 到 api 调用和 HTML 网站提供服务。

我的代码与此非常相似:

class TestAPI(Resource):
    def get(self):
        return {'hello': 'world'}
    def post(self):
        data = request.form["data"]            
        result = do_something(data)
        return {'result': result}

@mod.route("/")
def test():
    return render_template("test.html")

@mod.route("/do_something", methods=['GET','POST'])
def analyzer():
    form = TestForm()
    if request.method == 'POST':
        data = request.form.get("data")
        result = do_something(data)
        return render_template("result.html", result=result)
    return render_template("do_something.html", form=form)

我希望这能让用户导航到该页面并以表单形式提交数据、处理数据并在另一个 html 页面(使用 jinja 模板)中返回。我希望它也能让用户卷曲端点来做同样的事情,除了只是取回 JSON 值。

似乎发生的事情取决于我定义事物的顺序:

from app.views.test import test

api.add_resource(TestAPI, '/do_something')

当它像这样设置时,我从所有东西(在浏览器中,甚至从 curl 中)得到 HTML。如果我反转它,我到处都会得到 JSON 。有没有办法让我同时获得两者? (HTML 在浏览器中,JSON 否则)

我会说在你的后端,检查请求的 header 中的 'User-Agent' 参数。如果是浏览器,return html 模板。如果是 API, return json.

编辑

感谢 Piotr Dawidiuk

以上解决方案并不是最优雅的方法。 accept 属性更适合确定 json 或 html.

The Accept request-header field can be used to specify certain media types which are acceptable for the response. Accept headers can be used to indicate that the request is specifically limited to a small set of desired types, as in the case of a request for an in-line image.