翻页时刷新网页

2024-06-26 02:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

每次文件上载到文件夹时,我都要刷新网页。

我在flask中编写了一个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);

这很管用[几乎管用]。 我的问题是:有没有更好的方法[必须有]?

我对技术选择持开放态度,不管它们是什么[节点、角度等]


Tags: 文件函数import文件夹网页flaskifos
2条回答

我就是这么做的。你知道吗

首先感谢 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"

创建单独的线程以保持套接字打开。emit将消息从服务器发送到客户端。。。你知道吗

@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})

这里是客户端

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)
                });

如果我错了,请纠正我。你知道吗

是的,你可以使用websockets(flask socketio),这样你就可以在你和服务器之间建立一个开放的连接,每当文件夹中有一张新照片时,它就会显示在一个选定的div上

http://flask-socketio.readthedocs.io/en/latest/
https://pypi.python.org/pypi/Flask-SocketIO/2.9.1

相关问题 更多 >