I want to refresh my web page every time a file is uploaded to the folder.
I have a web service written in flask having the following handler
@app.route('/getlatest/')
def getlatest():
import os
import glob
newset = max(glob.iglob('static/*'),key=os.path.getctime)
Return newest;
This gives me the name of the latest file in the folder.
I have an Ajax call in my JS (client side) to constantly get data from above function.
function GetLatest()
{
$.ajax({
url: "http://localhost:5000/getlatest",
success: function(result)
{
if(previousName != result){
previousName = result;
$("#image").attr("src","/"+previousName);
}
}
});
}
function calling server every second.
(function myLoop (i) {
setTimeout(function () {
GetLatest();
if (--i) myLoop(i);
}, 1000)
})(100);
This Works fine (well almost). My Question is: Is there any better way to do it (there must be)?
I'm open to technology choices what every they may be (node, angualr etc).
-
\$\begingroup\$ If your use-case is actually "The server changed, now update the client", you could take a look into WebSockets. They have a good browser support nowadays. Also interesting: Send notification from server to client on server event. \$\endgroup\$insertusernamehere– insertusernamehere2017年07月26日 12:03:48 +00:00Commented Jul 26, 2017 at 12:03
1 Answer 1
Server side:
- There's no point in importing
os
andglob
inside the function. Local import is used for very specific cases and this is not one of them. - You're defining
newset
and then returningnewest
, did you test your code? - There's no point in defining
newest
(after fixing the typo), and then returning it in a separate line. Just return it in one line. - Add a space before
key=...
, as per Python conventions.
Client side:
What you've implemented here isn't very smart. You're constantly asking the server for updates, instead of having the server push updates to you when ever it detects them. You've essentially implemented a REST API, but for the wrong reasons. Take a look at websockets (flask-socketio is pretty good).
Explore related questions
See similar questions with these tags.