I've created a Flask application which:
- Reads events from different event sources;
- Persists those events to database; and
- Allows users to search through those events using DataTables 1.10.20.
I'm trying to:
- Read the parameters that DataTables is passing to the Flask backend via an AJAX request whenever a user attempts to search through the table; and
- Translate those parameters into a dictionary so they can be used when performing server-side filtering.
Here is the code for the table I created in DataTables:
$(document).ready(function() {
events_table_template = {
"scrollX": true,
"pageLength": 10,
"processing": true,
"serverSide": true,
"ajax": {
"url": "/ajax/events",
"type": "POST",
"dataType": "json",
"dataSrc": "data",
"contentType": "application/json"
},
"columns": [
{"data": "event_id"},
{"data": "event_type"},
{"data": "event_timestamp"},
{"data": "event_name"},
]
};
var table = $('#events-table').DataTable(events_table_template);
});
I've tried explicitly returning JSON within the DataTables configuration:
$(document).ready(function() {
events_table_template = {
...
"ajax": {
...
"data": function(args){
return {"args": JSON.stringify(args)};
}
};
var table = $('#events-table').DataTable(events_table_template);
});
Here is the AJAX endpoint on the Flask server:
from mycode import EventService
from flask import Blueprint
import flask
blueprint = Blueprint('events-ajax', __name__, url_prefix='/ajax/')
@blueprint.route('/events/', methods=["POST"])
def get_events():
print("Request data", flask.request.data)
print("Request form", flask.request.form)
api = EventService()
events = api.get_events_via_database()
rows = []
for event in api.get_events_via_database():
rows.append({
'event_id': event.event_id,
'event_type': event.type,
'event_timestamp': event.timestamp,
'event_name': event.name,
})
response = {
'data': rows,
'recordsTotal': len(events),
'recordsFiltered': len(events),
'draw': 1,
}
return flask.jsonify(response)
I've noticed that:
flask.request.datareturns a bunch of URL encoded text:Request data b'draw=1&columns%5B0%5D%5Bdata%5D=event_id&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=host_id&columns%5B1%5D%5B...flask.request.formreturns anImmutableMultiDictobject:ImmutableMultiDict([])
I've tried to:
Read the content of the AJAX request using these functions:
flask.request.dataflask.request.formflask.request.jsonflask.request.get_json(force=True)
Change the
content-typefrom the DataTables side of things fromapplication/jsontoapplication/json; charset=utf-8
How do you read the AJAX request as JSON?