我想每次文件上传到文件夹时刷新我的网页。
我有一个用烧瓶编写的web服务,它有以下处理程序
@app.route('/getlatest/')
def getlatest():
import os
import glob
newset = max(glob.iglob('static/*'),key=os.path.getctime)
Return newest;这给出了文件夹中最新文件的名称。
我在我的JS (客户端)中有一个Ajax调用来不断地从上面的函数中获取数据。
function GetLatest()
{
$.ajax({
url: "http://localhost:5000/getlatest",
success: function(result)
{
if(previousName != result){
previousName = result;
$("#image").attr("src","/"+previousName);
}
}
});
}函数每秒调用服务器。
(function myLoop (i) {
setTimeout(function () {
GetLatest();
if (--i) myLoop(i);
}, 1000)
})(100);这几乎工作得很好。我的问题是:有什么更好的方法吗?一定有
我对技术的选择是开放的,不管它们是什么节点,或者是什么,等等。
发布于 2017-07-28 11:12:25
我就是这样做的。
首先,感谢https://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent完美地解释了它。
我学到的是读几个博客。
使用http协议发起的所有通信都是客户端服务器通信,客户端始终是发起方。因此,在本例中,我们必须使用不同的协议:Web,它允许您创建一个全双工(双向)连接。
这是服务器代码;
socketio = SocketIO(app, async_mode=async_mode)
thread = None
prevFileName = ""
def background_thread():
prevFileName = ""
while True:
socketio.sleep(0.5)
if(isNewImageFileAdded(prevFileName) == "true"):
prevFileName = getLatestFileName()
socketio.emit('my_response',
{'data': prevFileName, 'count': 0},
namespace='/test');
def getLatestFileName():
return max(glob.iglob('static/*'),key=os.path.getctime)
def isNewImageFileAdded(prevFileName):
latestFileName = max(glob.iglob('static/*'),key=os.path.getctime)
if(prevFileName == latestFileName):
return "false"
else:
return "true"创建单独的线程以保持套接字打开。从服务器向客户端发送消息..。
@socketio.on('connect', namespace='/test')
def test_connect():
global thread
if thread is None:
thread = socketio.start_background_task(target=background_thread)
emit('my_response', {'data': 'Connected', 'count': 0})下面是带有以下代码的客户端Side.replaced ajax调用
var socket = io.connect(location.protocol + '//' + document.domain + ':' +
location.port + namespace);
socket.on('my_response', function(msg) {
setTimeout(function(){ $("#image").attr("src","/"+msg.data)},1000)
});如果我错了,请纠正我。
https://stackoverflow.com/questions/45323875
复制相似问题