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

后端 未结 3 2250
無奈伤痛
無奈伤痛 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条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-19 05:09

    for future readers: what I do is something like below:

    request_xhr_key = request.headers.get('X-Requested-With')
    if request_xhr_key and request_xhr_key == 'XMLHttpRequest':
       #mystuff
    
       return result
    abort(404,description="only xhlhttprequest is allowed")
    

    this will give an 404 error if the request header doesn't contain 'XMLHttpRequest' value.

提交回复
热议问题