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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With