簡體   English   中英

我可以使用Flask和flask-restul將JSON返回API調用,但將HTML返回瀏覽器嗎?

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

我正在為個人項目構建一個webapp,並且希望能夠將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)

我想說在您的后端,請檢查請求標頭中的'User-Agent'參數。 如果是瀏覽器,則返回html模板。 如果是API,則返回json。

編輯

歸功於Piotr Dawidiuk

上面的解決方案不是最優雅的方法。 accept屬性更適合確定json或html。

接受請求標頭字段可用於指定響應可接受的某些媒體類型。 接受標頭可用於指示該請求特別限於一小部分所需類型,例如在請求嵌入式圖像的情況下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM