How to: django template pass array and use it in javascript? - python

Ok so here is a problem,
I have an html template which looks something like this:
<script>
$(function() {
var vCountries = {{ visitedCountriesList }};
});
</script>
<..>
{{ visitedCountriesList }}
from server I pass an list to this item, but after rendering it looks like this:
<script>
$(function() {
var vCountries = ;
});
</script>
<..>
[u'Afghanistan', u'Japan', u'United Arab Emirates']
so my question is - why ? and how I can pass it to javascript...?

The problem is the string representation of the array isn't valid JavaScript. The u' at the start is no good. This:
[u'Afghanistan', u'Japan', u'United Arab Emirates']
should be this:
['Afghanistan', 'Japan', 'United Arab Emirates']
You have two options. In the view function, encode it as JSON there there:
render_to_response('my_view.html', {
'visitedCountriesList' : json.dumps(visitedCountriesList)
})
or create a filter that you can use. See this one for an example. Then usage is just:
<script>
$(function() {
var vCountries = {{ visitedCountriesList|jsonify }};
});
</script>

you should have in your html an id with the variable rendered and look it there, lets do an example:
<...>
<loldiv id="myvar" data="{{info}}"/>
<...>
and in your javascript:
<script>
$(function() {
var vCountries = $("#myvar").attr("data");
});
</script>
That is assuming you are using jQuery.
I dont really know why that template assign the variable but you should not render any information on javascript code since there is a moment where you are going to take that js and put it on a compressed file, or move it, or reuse it and it will be really hard to do it if you rendered the variable values that way.
hope this helps!

Related

Pretty print sympy when not using iPython

I am using SymPy with PyScript so I cannot use init_printing() in my code as I am not running code cell by cell. How can I still use pprint to make my output look good in Web?
Output I am getting:
Output I am expecting:
I wrote a MathJax example that displays formulas correctly: link Right-click on the page to view the source code.
The key is that you must tell MathJax to typeset the answer. This requires dropping down to JavaScript for a simple two line call:
<script>
function draw(str) {
var math = MathJax.Hub.getAllJax("MathDiv")[0];
MathJax.Hub.Queue([ "Text", math, str ]);
}
</script>
Example code including initializing MathJax and setting up the display DIV:
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
processEscapes: true
}
});
</script>
<div id="MathDiv">\({}\)</div>
<py-script>
delta__y_l = symbols('Delta__y_l')
latexstr = latex(delta__y_l)
js.draw(latexstr)
</py-script>

Flask: Get modification date of uploaded file [duplicate]

Is there ever a way possible to get the actual creation / modification time of the file being uploaded, using JavaScript?
As for PHP, using filectime() and filemtime(), it only shows the date / time the file is uploaded, and not the time the file is actually created / modified on the source.
In short, what I want is to check the m-time of a file before/during/after upload (where-ever possible) and decide whether or not to store the file on the server, and report the same back to the client.
If you're talking about the file date/time on the user's machine, you can get that via the File API (support), which provides lastModified, which is the date/time as a number of milliseconds since The Epoch (if you want a Date, you can pass that into new Date). (There's also the deprecated lastModifiedDate, but that is deprecated and not supported on Safari [at least].) The File API is universally supported in modern browsers (the particular feature you'd be using is the File object). You'd get the value from the File object and include that information in a separate (for instance, hidden) field.
Here's a rough-but-complete example of reading the last modified date (live copy):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Modified</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function showFileModified() {
var input, file;
// Testing for 'function' is more specific and correct, but doesn't work with Safari 6.x
if (typeof window.FileReader !== 'function' &&
typeof window.FileReader !== 'object') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('filename');
if (!input) {
write("Um, couldn't find the filename element.");
}
else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
write("Please select a file before clicking 'Show Modified'");
}
else {
file = input.files[0];
write("The last modified date of file '" + file.name + "' is " + new Date(file.lastModified));
}
function write(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='filename'>
<input type='button' id='btnShowModified' value='Show Modified' onclick='showFileModified();'>
</form>
</body>
</html>
The reason you couldn't get the time from the uploaded file on the server is that only the content of the file is transmitted in the request, not the client's filesystem metadata.
JavaScript does not have access to the local filesystem, so you can't get to this information without using Flash, Java or Active-x.
Perhaps you could use javascript to get the last modified time, then use that in some other javacript to sort on that. This time will be in GMT.
var xmlhttp = createXMLHTTPObject();
xmlhttp.open("HEAD", "http://myurl/interesting_image.jpg" ,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert("Last modified: "+
var lastModTimeForInterestingImage = xmlhttp.getResponseHeader("Last-Modified"))
}
}
xmlhttp.send(null);

How to correctly parse XML urls with requests in Python?

I would like to parse an XML file from a URL.
By doing the following:
req = requests.get('https://www.forbes.com/news_sitemap.xml')
Instead of getting the proper XML file, I get:
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en_US">
<script type="text/javascript">
(function () {
function isValidUrl(toURL) {
// Regex taken from welcome ad.
return (toURL || '').match(/^(?:https?:?\/\/)?(?:[^.(){}\\\/]*)?\.?forbes\.com(?:\/|\?|$)/i);
}
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
function consentIsSet(message) {
console.log(message);
var result = JSON.parse(message.data);
if(result.message == "submit_preferences"){
var toURL = getUrlParameter("toURL");
if(!isValidUrl(toURL)){
toURL = "https://www.forbes.com/";
}
location.href=toURL;
}
}
var apiObject = {
PrivacyManagerAPI:
{
action: "getConsent",
timestamp: new Date().getTime(),
self: "forbes.com"
}
};
var json = JSON.stringify(apiObject);
window.top.postMessage(json,"*");
window.addEventListener("message", consentIsSet, false);
})();
</script>
</head>
<div id='teconsent'>
<script async="async" type="text/javascript" crossorigin src='//consent.truste.com/notice?domain=forbes.com&c=teconsent'></script>
</div>
<body>
</body>
</html>
Is there also a better way to handle the XML file (for example, if it is compressed, or by parsing it recursively if the file is too big...)? Thanks!
This site checks a cookie for GDPR if you give that cookie to request you can get XML file.
Try this code, works fine to me.
import requests
url = "https://www.forbes.com/news_sitemap.xml"
news_sitemap = requests.get(url, headers={"Cookie": "notice_gdpr_prefs=0,1,2:1a8b5228dd7ff0717196863a5d28ce6c"})
print(news_sitemap.text)
Using requests module I get the xml file. You can then use an xml parser library to do what you want.
import requests
url = "https://www.forbes.com/news_sitemap.xml"
x = requests.get(url)
print(x.text)

How to get file contents of a file automatically with AJAX?

I am using AJAX to get the contents of a file when I press a button(I am very new to AJAX.) , Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "data.dat", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">
<p>- - -</p>
</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
And here is the python to change the file(This is not the python code i am using, but it still does the same thing, almost):
from time import *
a = 0
while True:
print(a)
file = open("data.dat","w")
file.write("<p>"+str(a)+"</p>")
file.close()
sleep(1)
a+=1
I would like to get the file contents every second, How would I Do that? Any help is good.
You could use setInterval() to periodically run the function which updates your document.
var intervalID = setInterval(loadXMLDoc, 1000); // Every 1s

Django refresh data [duplicate]

I am converting one layout to html; once I make the changes in code/html/css, every time I have to hit F5. Is there any simple javascript/jQuery solution for this? I.e. after I add the script, reload the whole page every 5 seconds (or some other specific time).
<meta http-equiv="refresh" content="5; URL=http://www.yourdomain.com/yoursite.html">
If it has to be in the script use setTimeout like:
setTimeout(function(){
window.location.reload(1);
}, 5000);
To reload the same page you don't need the 2nd argument. You can just use:
<meta http-equiv="refresh" content="30" />
This triggers a reload every 30 seconds.
For auto reload and clear cache after 3 second you can do it easily using javascript setInterval function. Here is simple code
$(document).ready(function() {
setInterval(function() {
cache_clear()
}, 3000);
});
function cache_clear() {
window.location.reload(true);
// window.location.reload(); use this if you do not remove cache
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p>Auto reload page and clear cache</p>
and you can also use meta for this
<meta http-equiv="Refresh" content="5">
setTimeout(function () { location.reload(1); }, 5000);
But as development tools go, you are probably better off with a tab reloading extension.
There's an automatic refresh-on-change tool for IE. It's called ReloadIt, and is available at http://reloadit.codeplex.com . Free.
You choose a URL that you'd like to auto-reload, and specify one or more directory paths to monitor for changes. Press F12 to start monitoring.
After you set it, minimize it. Then edit your content files. When you save any change, the page gets reloaded. like this:
Simple. easy.
Answer provided by #jAndy should work but in Firefox you may face problem, window.location.reload(1); might not work, that's my personal experience.
So i would like to suggest:
setTimeout(function() { window.location=window.location;},5000);
This is tested and works fine.
A decent alternative if you're using firefox is the XRefresh plugin. It will reload your page everytime it detect the file has been modified. So rather than just refreshing every 5 seconds, it will just refresh when you hit save in your HTML editor.
Alternatively there's the application called LiveReload...
If you are developing and testing in Firefox, there's a plug-in called "ReloadEvery" is available, which allows you to reload the page at the specified intervals.
This will work on 5 sec.
5000 milliseconds = 5 seconds
Use this with target _self or what ever you want and what ever page you want including itself:
<script type="text/javascript">
function load()
{
setTimeout("window.open('http://YourPage.com', '_self');", 5000);
}
</script>
<body onload="load()">
Or this with automatic self and no target code with what ever page you want, including itself:
<script type="text/javascript">
function load()
{
setTimeout("location.href = 'http://YourPage.com';", 5000);
}
</script>
<body onload="load()">
Or this if it is the same page to reload itself only and targeted tow hat ever you want:
<script type="text/javascript">
function load()
{
setTimeout("window.open(self.location, '_self');", 5000);
}
</script>
<body onload="load()">
All 3 do similar things, just in different ways.
function reload() {
document.location.reload();
}
setTimeout(reload, 5000);

Categories

Resources