python - 我可以使用 Flask 和 Flask-restul 将 JSON 返回给 API 调用,但将 HTML 返回给浏览器吗?

标签 python flask flask-restful

我正在为个人项目构建一个 Web 应用程序,我希望能够为 API 调用提供 JSON 服务,为网站提供 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 模板)。我希望它也能让用户 curl 端点做同样的事情,除了返回 JSON 值。

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

from app.views.test import test

api.add_resource(TestAPI, '/do_something')

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

最佳答案

我会说在您的后端中,检查请求 header 中的'User-Agent'参数。如果是浏览器,则返回 html 模板。如果是API则返回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.

关于python - 我可以使用 Flask 和 Flask-restul 将 JSON 返回给 API 调用,但将 HTML 返回给浏览器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41914940/

相关文章:

python - Flask api 表示影响所有 View

python - 在网站中抓取动态内容

python - Pandas 从 Multiindex 获取行名称(样本名称)

linux - 使用 Linux 系统凭据登录 Flask

python-3.x - 通过 Ajax 将数据发布到 Flask 时出现 500 内部服务器错误

python-3.x - 属性错误 : 'dict' object has no attribute '_sa_instance_state'

python - Flask-restful API 授权。在装饰器中访问 c​​urrent_identity

Python ImageIO Gif 设置帧间延迟

python - Pygtk 图形上下文和分配颜色

python - Flask:使用重新加载器重新启动找不到文件