How can I identify requests made via AJAX in Python's Flask?

后端 未结 3 2255
無奈伤痛
無奈伤痛 2021-02-19 04:59

I\'d like to detect if the browser made a request via AJAX (AngularJS) so that I can return a JSON array, or if I have to render the template. How can I do this?

3条回答
  •  萌比男神i
    2021-02-19 05:10

    Flask comes with a is_xhr attribute in the request object.

    from flask import request
    @app.route('/', methods=['GET', 'POST'])
    def home_page():
        if request.is_xhr:
            context = controllers.get_default_context()
            return render_template('home.html', **context)
    

    Notice: This solution is deprecated and not viable anymore.

提交回复
热议问题