Asynchronously update page with data that are stored by middleware - python

I have middleware, that stores all http requests into DB.
Also I have view, that fetches data from DB and put this data into the context.
views.py
def requests(request):
http_requests = WebRequest.objects.all()
context = {
"http_requests": http_requests
}
return render(request, "requests.html", context)
How can I asynchronously update data on this page as new requests come in (so, new requests should appear on this page asynchronously)? Can I use only Django features to achieve such behavior or I need to use some javascript libraries?

It depends on how much time you want to spend on the project. As Lorenzo stated, it might make sense to create an API and have javascript-frameworks (e.g. emberjs or angularjs) handle the asynchronity. I dont think you can handle this with pure django...
If you don't have time and are in for some 'hack' you could just replace the content of your page by polling the url and replacing the whole document with the response:
$.ajax({
type: "GET",
url: "<url_to_your_requests_view>",
success: function(response){
$('body').html(response);
}
});
This is NOT clean, but should work as a quick an dirty trick...
EDIT: If you only want to exchange certain parts of your site, you can break it down to just add elements to the page:
$.ajax({
type: "GET",
url: "<url_to_your_requests_view>",
success: function(response){
var newlyAddedRows = // find your newly added rows through some jquery
newlyAddedRows.forEach(function(row){
$('#request-holder').append(row);
});
}
});
OR WITH JSON
$.ajax({
type: "GET",
url: "<url_to_your_requests_api_endpoint>",
success: function(response){
var requestRows = response.requestItems
var $requestsHolder = $('#request-holder');
$requestHolder.empty();
requestRows.forEach(function(row){
requestsHolder.append('<div class="request-row">' + <visualize your data somehow> + '</div>'); //e.g. row.timestamp if you have that in your json
});
}
});

Related

Fetching data after a certain time interval(10 sec) from a continuously increasing database like mysql using flask

I want to create an api using python and flask that fetches data in regular time interval(10 sec) from a continuously increasing database where data is continuously coming and stored.I don't want to fetch the old data which were already fetched.
Say you currently have an API endpoint that returns all the database stored data:
#app.route('/data', methods=['post'])
def data():
all_the_data = Data.query.order_by(Data.created.desc()).all()
return jsonify(results=all_the_data)
So your ajax call currently doing something like:
$.ajax({
type: "POST",
url: "/data",
dataType: "json",
success: function(data) {
console.log(data);
update_graph(data);
}
});
You just need a way for the system to filter what's going out, back to the client-- so we instead of querying all the data, we can filter based on a reference:
#app.route('/data', methods=['post'])
def data():
client_data = request.json
reference = client_data.get('reference')
if reference:
# we have a reference, so lets filter the query:
query_data = Data.query.filter(Data.id>reference).order_by(Data.created.desc()).all()
else:
# no reference, so send the lot!
query_data = Data.query.order_by(Data.created.desc()).all()
return jsonify(results=query_data)
Then your ajax request needs to get the last reference from the last query it did-- and supply that to the API endpoint:
$.ajax({
type: "POST",
url: "/data",
data: JSON.stringify({ reference: 999 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
console.log(data)
update_graph(data["results"]);
}
});
So you just need to work out how to get that reference value from the last set of values you recieved (the API could send that back as another key, or you could poll your current set within javascript, etc).

URL sent to Django using AJAX is different when printed from Django

I have a JQuery event that, when a link is clicked, an AJAX POST request is sent to a Django function. There I print the recieved url and do other stuff with it. However, when it is printed (by Django) some characters in the url are changed.
The specific url this happened with was :
https://www.catholicleague.org/05press_releases/quarter%204/051110_put_on_notice.htm
Which was printed as :
https://www.catholicleague.org/05press_releases/quarter+4/051110_put_on_notice.htm
Where %20 was changed to +
Here is the AJAX and Django code:
$("a").on("click", function(e){
e.preventDefault();
if(e.target.href){
let clicked_source = e.target.href;
let csrf_tok = parent.document.getElementById("csrf_tok").value;
$.ajax({
url: "/change_origin/",
data: JSON.stringify({"clicked_source":clicked_source}),
type: "POST",
beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrf_tok );},
success: function(response) {
console.log(response.msg)
},
error:function(error) { console.log(error); }
});
}
});
def change_origin(request):
if request.method == 'POST':
received = ast.literal_eval(request.body.decode())
print(received)
clicked_source_url = received['clicked_source']
return JsonResponse({'msg': "ok"})
Where decode is used as the JSON object is received in Python as a byte-like object. And ast is used to turn the string representation of the object to an actual object (or dict) for access.
I need either:
1) A way to just send a string from Ajax to Django
2) A better way to deal with the received object as I believe using .decode() might be the one causing this issue.
EDIT: The link is the second link in the "origin" part of this article
https://www.snopes.com/fact-check/an-unmerried-woman/

Django get request via ajax making two requests

I am working on passing data from ajax to a Django view. However, ajax somehow is making 2 GET requests: one with the query string and the other without it. In the view when I try to get the query string its empty.
Ajax code:
<script>
$( document ).ready(function() {
var query = "{{ item.ipv4_address }}";
$("#clickid").click(function() {
$.ajax({
url: "/reserve/run/?ip=",
type: "GET",
data: {ip:query},
success:function(data){
console.log(data);
}
});
});
});
</script>
Django view:
def run_script(request):
if request.GET:
ip = request.GET['ip']
print ip
return render_to_response('test.html',{'item':ip})
Two urls:
[16/Dec/2017 07:43:56] "GET /reserve/run/?ip=198.18.101.123 HTTP/1.1" 200 570
[16/Dec/2017 07:03:58] "GET /reserve/run/ HTTP/1.1" 200 1
urls.py file
url(r'^run/$',views.run_script,name='run_script'),
Please let me know where I am going wrong. Also, let me know if you need any more info. Any pointers is appreciated.
If you are passing query parameter in your data attribute you need not to send it in url parameter.Update your url parameter as:
$.ajax({
url: "/reserve/run/",
type: "GET",
data: {ip:query},
success:function(data){
console.log(data);
}
});
I found the error. In my tag, I had mentioned the URL too. {% url 'run_script' %}. This was sending that extra GET request. Once I removed it, the issue resolved.

How to receive dictionary in post data python

I'm trying to send array as a parameter to the api which is using python and django framework.
Here's my client side code that is being used to access the api:
$.ajax(
type: 'POST',
url: 'http://example.com/api/users',
data: {user:{name:'Rohit Khatri', age:20, father_name:'S.K'},type:'info'},
complete: function(response) {
console.log(response);
}
);
Here's the view where I'm trying to access the request parameters
def get_users(request):
print(request.POST.get('ids'))
and when I try to access ids parameter, It gives None.
If anyone has faced the same problem, please help me.
You can try getting the list as follows:
request.POST.getlist('ids[]')
Note: You will be better off if you send/receive your data as JSON. You first need to set the Accept and Content-Type headers to application/json while sending the request and then convert the json to python object using json.loads. Example as follows:
Javascript/AJAX
$.ajax(
type: 'POST',
url: 'http://example.com/api/users',
contentType: 'application/json'
data: {ids:[1,2,3,4,5],type:'info'},
complete: function(response) {
console.log(response);
}
);
Django
import json
def get_users(request):
ids = request.POST.get('ids')
if ids:
ids = json.loads(ids)
Update:
In case you need to use more complicated data such as an object (dictionary) using json will be your best bet and it will work pretty similar to the above example.
Javascript/AJAX
$.ajax(
type: 'POST',
url: 'http://example.com/api/users',
contentType: 'application/json'
data: {ids:{"x":"a", "y":"b", "z":"c"}, type:'info'},
complete: function(response) {
console.log(response);
}
);
Django
import json
def get_users(request):
ids = request.POST.get('ids')
if ids:
ids = json.loads(ids)

how to read a file using ajax and django?

My Ajax code:
var upfile = $("#file-id").val().split(/[\/\\]/).pop();
$.ajax({
type: 'POST',
url: '/upload/',
data:{"upfile":upfile},
success: function(data) {
if (data['success'] === "true") {
}
},
dataType: 'json'
});
return false;
Django code:
In simple form submit action request.FILES.get('upfile') works. I can read the content of file using read() But in ajax, it is not working. even request.POST.get('upfile') gives me the filename string.
How to solve this issue?
It's normal, by default a form submitted with Ajax will not upload files. You need o have a look to some file upload jquery plugins (there's a few of them, I can not suggest one as I did not try any of these yet)

Categories

Resources