Javascript long polling a json file - angularjs/jquery - python

Wishing you a Happy New year.!
I am having trouble when i am trying to load a json file from my web server. Actually i do not know java script. I just need this code to work. I am developing a website using Django. One of the django views, serves the client side java script and at the back end on a separate thread, it process some modules and generates a json output.
Now i am accessing this json using the below code.
<script type="text/javascript">
function addmsg(msg) {
document.getElementById("messages").innerHTML = msg;
}
function waitForMsg() {
$.ajax({
type: "GET",
url: "{% static ""%}tmp/{{url_hash}}/{{url_json}}",
cache: false,
timeout: 50000,
success: function (data) {
addmsg(data);
if (!data) {
setTimeout(
waitForMsg,
1500
);
};
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
addmsg("error");
setTimeout(waitForMsg, 15000);
}
});
};
$(document).ready(function () {
waitForMsg();
addmsg("loading");
});
</script>
When i run this, javascript gets served and then it queries for the json file every 1.5 sec.
What happens is, once the file is available on the server, this script loads the file and redirects the page to something like this ,
localhost:8000/+e+/
I dono from where this is getting redirected. I am not redirecting on any views or urls.py is clean.
Please help me with a code which will load this json from webserver when its available and then print the contents.
Thanks
===========update------------------
can anyone please suggest me angular js script for achieving the same ? thanks
==================== Update =====================================
Found the error, Actually the json dict has javascript, which has } { and quotes. Which breaks it.

I suggest looking beyond a lack of knowledge about JavaScript and stepping through all the parts of your problem. For example, use chrome and open the developer tools tab. Reload the page. Look at the url the JavaScript is testing to open. I suspect it is not the url you intend.
This code looks odd:
{% static ""%
Why is there the quote in the middle of the django directive? This isn't a JavaScript issue, just a quoting issue. It's also a warning sign because your JavaScript is using template directives - not an impossible or illegal thing, but a concern that some teams wouldn't allow.
In any case, track down the url that is actually bring invoked, see if it is the one you intend, and check the quoting issue in the httpcall.

Related

How can I upload a file with JSON data to django rest api?

I am using angular as the front-end scope and Django Rest as the back-end. Now I am facing a situation where I want to create a Model. The structure of a model is really complex in nature, I could use some other simple way outs but using JSON and passing the files with that can really simplify the logic and also make process really efficient.
I am have been trying a lot but none of the ways seem to work.
Can some someone help me with a standard way or tell me even it is possible or not.
This the structure of my Typescript which I want to upload.
import { v4 as uuid4 } from 'uuid';
export interface CompleteReport{
title: string;
description: string;
author: string;
article_upload_images: Array<uuid4>,
presentation_upload_images: Array<uuid4>,
report_article: ReportArticle,
report_image: ReportImage,
report_podcast: ReportPodcast,
report_presentation: ReportPresentation,
report_video: ReportVideo,
}
export interface ReportArticle{
file: File;
body: string;
}
export interface ReportPodcast{
file: any;
}
export interface ReportVideo{
file: Array<File>;
}
export interface ReportImage{
file: File;
body: string;
}
export interface ReportPresentation{
body: string;
}
export interface UploadImage{
file: File;
}
I don't see how you wanna send data, but if you wanna send data with multipart/data-form, I think you should make small changes to your report structure.
JSON doesn't supports binary. So, you can't put files on it. You need to split file and report JSON.
(async () => {
let formData = new FormData();
// here's how to send file on multipart/data-form via fetch
let reportFile = document.querySelector('#file');
formData.append("file", imagefile.files[0]);
// here's your report json
let report = {
...
};
formData.append("report", JSON.stringify(report));
// send request and upload
let response = await fetch(url, {
method: 'POST',
body: formData
});
// do something with response
let responseText = await response.text();
console.log(responseText)
})();
And I see UUID on your frontend code, I think it's better to put that kinda stuff on backend to prevent manipulated request. I think it's better to put complicated stuff, and any server data related on your backend. Just my opinion.

Ajax POST doesn't work with Flask / IIS7.5

Because I start to go crazy I really need your help xD
I'm tying to make a simple Ajax POST, and with it I want to send JSON data to python script to save it later on server.
I'm using python 3.6.4 (anaconda3 with wfastcgi.py) for backend and Javascript (jQuery) and Flask for frontend.
Here's what I got from Chrome Dev Tools -> Network:
POST 1 is from local python server Werkzeug, POST 2 is from IIS 7.5.
I'm showing both in hope that it will help locate the problem. I only need a way to fix IIS.
I already tried :
<customHeaders> with Access-Control-Allow-Origin etc
<requestFiltering> with <add verb="POST" allowed="true" />, or <verbs allowUnlisted="true">
changing OPTIONSVerbHandler verb from OPTIONS to POST (don't ask me, found it here)
But it didn't help.
With Failed Request Tracing Rules module I was able to find this:
But I don't know what where in IIS I can change anything with FastCgi to make it work with POST.
My Ajax POST:
$.ajax({
url: "/static/scripts/saveData.py",
type: "post",
data: JSON.stringify(tableObject),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(error){
console.log(error)
}
});
ps. Link to file works because when I change POST to GET I get code from saveData.py in console.log(response).
I think that you forgot to register this method in flask routs:
#app.route('/login', methods=['POST', 'GET'])
Soooo, after close to 2 days of looking in net, tying different ways to make it work, i finally found a way to send a Ajax POST.
Basically I had to change target url "/static/scripts/saveData.py" from local address to Flask url "/annotate" and this enable me to send data with POST and letter process it in views.py (my main flask view file).
$.ajax({
url: "/annotate",
type: "post",
data: JSON.stringify(tableObject),
//data: tableObject,
contentType: "application/json"
});
Now, why this work, and POST to normal .py script doesn't, I don't know.
But at least now I can work with that data.

Django testing ajax endpoint in view

I'm using django-ajax in a django application, and want to do more thorough unit testing of the view that uses it.
My template for a particular view contains the following:
{% block head_js %}
<script type="text/javascript">
$(function() {
$('#progressbar').progressbar({
value: false
});
var checkStatus = function() {
$.ajax({
type: "POST",
url: '/ajax/MyApp/check_provisioning.json',
dataType: 'json',
success: function(data) {
if (data.data.complete != true) {
setTimeout(checkStatus, 3000);
} else {
// We've finished provisioning, time to move along.
window.location.replace('/MyApp/next');
}
}
});
};
checkStatus();
});
</script>
{% endblock %}
In MyApp/endpoints.py I have the function (simplified):
def check_provisioning(request):
# Do some stuff
return {'complete': some_boolean}
Now... As far as I can tell, the view functions just fine, in actual usage.
But when making unit tests, django's test client retrieves the rendered response, but doesn't run anything embedded therein.
Does anyone know a way I can unit test that the view and/or the endpoint function are actually doing what they're supposed to? I would rather not fall back on using the django test framework to set up for a selenium test for the one view in the whole project that uses django-ajax this way.
You could use something like django-casper:
https://github.com/dobarkod/django-casper
I haven't used it, but it appears to be a django-specific python library which interfaces with CasperJS and PhantomJS.
PhantomJS is a web-kit based headless browser that gives a more light-weight alternative to browser automation with selenium.

how to make django server and angular client side projects different with CSRF protection

I have read different blogs about django and angular, but all of them have client side (HTML+CSS+JS) codes inside django project.
All I want to do is create two projects: One with all client side stack ( HTML+JS+CSS) and another with Django and Django-rest-framework only. This means that I could write all my presentation code in different project and server code in different project but link them together using REST api.
But there comes a threat which I should always consider CSRF against which Django's CSRF Middleware provide nice security.
So, is it possible to put my client codes outside the Django project directory but still get protected against CSRF?
Read the documentation, everything is explained well. The cleanest way to do this is when you will submit your data using Ajax, you have to add a custom header X-CSRFToken. The token can be parsed from the cookies, which should be enabled by the way. Here is a link to the documentation.
The documentation is always the best place to find your questions, you just have to read mate. But anyway, here is an example:
// Using the jquery cookie plugin, you can get the csrf token like this
var csrftoken = $.cookie('csrftoken');
Then in your javascript/Anuglar code, to post or make ajax request, you have to add the X-CSRFToken header before making the POST/PUT request:
// This HTTP method doesn't need protection since you will be reading and not pushing data
// into the server
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// This is for setting up the upcoming ajax request, here you add the header with the
// csrftoken you got it from the cookies
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
NB: This is using jQuery, you can still do the same thing using Angular.
After this you can make your Ajax call and Django will happily accept your request, again RTD please, everything is well explained, you have all of this code examples included.

How to make asynchronous HTTP POST requests

I have this program which runs in a loop with pythoncom.PumpMessages().
While this program runs, it takes input and stores it iternally.
When the input reaches a certain lenght, I'd like to send a HTTP POST request asynchronously to a database I have in the cloud so the program doesn't stop taking input while the request is sent. I do not need the request from the server, although it would be nice.
Is this possible? I'm having a hard time figuring this out. Right now it does it synchronously.
Thanks!
This can be done if you use python requests library to send post requests.
It has been answered here.
Asynchronous Requests with Python requests
The example is for "GET" request but you can easily do post request as well.
JavaScript works on any browser without added libraries.
This is great for loading parts of a page without stalling the UI, but use another method (e.g. server or NodeJS) if sending many requests (e.g. >100).
<p id="demo">Customer info will be listed here...</p>
<script>
function showCustomer(str) {
var xmlhttp;
if (str == "") {
document.getElementById("demo").innerHTML = "";
return;
}
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "yourFile.php?queryVariable="+str, true);
xmlhttp.send();
}
</script>
Source: http://www.w3schools.com/xml/tryit.asp?filename=try_dom_xmlhttprequest_database
GET: http://www.w3schools.com/xml/tryit.asp?filename=try_dom_xmlhttprequest_first
More here: http://www.w3schools.com/xml/dom_http.asp

Categories