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

时间:2017-01-28 21:19:46

标签: python flask flask-restful

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

我的代码非常相似:

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')

当它设置为这样时,我会从所有内容中获取HTML(在浏览器中甚至是curl中)。如果我反过来,我到处都会得到JSON。我有办法同时获得两者吗? (浏览器中的HTML,否则为JSON)

1 个答案:

答案 0 :(得分:3)

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

修改

归功于 Piotr Dawidiuk

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

  

Accept request-header字段可用于指定某些媒体   响应可接受的类型。接受标题即可   用于表示请求仅限于小型   所需类型的集合,如在内联请求的情况下   图像。