Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 655
ensnare Avatar asked Jul 10 '14 23:07

ensnare


People also ask

How do I access requests in Flask?

To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.

Can AJAX use Python Flask?

We can also use Ajax to handle the user input rather than rendering a template. After carrying out the calculation client-side we will then pass the user input and results to the server to store in a database.

How do you handle requests in Flask?

When the Flask application handles a request, it creates a Request object based on the environment it received from the WSGI server. Because a worker (thread, process, or coroutine depending on the server) handles only one request at a time, the request data can be considered global to that worker during that request.


2 Answers

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.

like image 50
AlexLordThorsen Avatar answered Oct 26 '22 14:10

AlexLordThorsen


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.

like image 28
ClassY Avatar answered Oct 26 '22 15:10

ClassY