ensnare
ensnare

Reputation: 42093

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

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?

Upvotes: 17

Views: 5935

Answers (4)

Brandon
Brandon

Reputation: 175

I used this and it works perfectly:

if request.method == 'POST' and request.headers.get('X-Requested-With') == 'XMLHttpRequest':
    current_app.logger.info('Recognized an AJAX request!')
    # rest of code to handle initial page request

Upvotes: 0

ClassY
ClassY

Reputation: 655

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.

Upvotes: 4

AlexLordThorsen
AlexLordThorsen

Reputation: 8498

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.

Upvotes: 25

Kresten
Kresten

Reputation: 100

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

Upvotes: 1

Related Questions