16

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?

ensnare
  • 40,069
  • 64
  • 158
  • 224

3 Answers3

25

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.

hamidfzm
  • 4,595
  • 8
  • 48
  • 80
AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103
  • 2
    Notice that (from Flask official documentation): "This only works with libraries that support the X-Requested-With header and set it to “XMLHttpRequest”." – slashCoder Jan 15 '19 at 14:52
  • 5
    "'Request.is_xhr' is deprected as of flask version 0.13", the above answer is not viable anymore – Kresten May 29 '19 at 15:05
  • @kres0345 Would you like to answer the current valid method and I'll upvote your answer? – AlexLordThorsen May 29 '19 at 17:36
  • @AlexLordThorsen I couldn't find a "proper" method for checking whether a request is of ajax origin, but I posted a workaround that worked for my purpose – Kresten May 29 '19 at 19:13
4

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.

ClassY
  • 744
  • 5
  • 20
1

There isn't any way to be certain whether a request is made by ajax.

What I found that worked for me, was to simply include a get parameter for xhr requests and simply omit the parameter on non-xhr requests.

For example:

  • XHR Request: example.com/search?q=Boots&api=1
  • Other Requests: example.com/search?q=Boots
Kresten
  • 100
  • 2
  • 9