Python Flask在网站中设置文本而无需重新加载



我创建了一个简单的flask应用程序。这里我就不展示了因为里面有很多Bootstrap的东西

我的网站应该是这样的:

Installation will be done...
> Installing Flask-Nav

安装第一个扩展后:

Installation will be done...
> Configuring Flask for Extensions

等等…

但是网站上也有一些bootstrap的东西。所以加载页面需要一些时间。但是我只想设置状态标签。我怎么能做到不刷新整个页面?

def install():
    download("flask-nav")
    config("flask-nav")
    setstatus("> Downloading next extensions") #How to do that???
    download("flask-appconfig")
    ....

这是Flask-SocketIO的一个非常简单的实现。您可以阅读本文以更好地理解

test.py

import time
from threading import Thread
from flask import Flask, render_template
from flask.ext.socketio import SocketIO, emit
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread = None

def background_thread():
    """Here is where you'll perform your installation"""
    count = 0
    # Call Install function 1 using time.sleep(10) to simulate installation
    time.sleep(10)
    count += 1
    socketio.emit('my response',
                      {'data': '1 installed', 'count': count},
                      namespace='/test')
    # Call Install function 2 using time.sleep(10) to simulate installation
    time.sleep(10)
    count += 1
    socketio.emit('my response',
                      {'data': '2 installed', 'count': count},
                      namespace='/test')
    # Call Install function 3 using time.sleep(10) to simulate installation
    time.sleep(10)
    count += 1
    socketio.emit('my response',
                      {'data': '3 installed', 'count': count},
                      namespace='/test')

@app.route('/')
def index():
    thread = Thread(target=background_thread)
    thread.start()
    return render_template('index.html')

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')

if __name__ == '__main__':
    socketio.run(app)

模板/index . html

<!DOCTYPE HTML>
<html>
<head>
    <title>Flask-SocketIO Test</title>
</head>
<body>
    <h1>Flask-SocketIO Test</h1>
    <div id="log1"></div>
    <div id="log2"></div>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function(){
            namespace = '/test';
            var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
            $('#log1').html('<br>Installing Software');
            $('#log2').html('<br> > ...');
            socket.on('my response', function(msg) {
                $('#log2').html('<br> > Received #' + msg.count + ': ' + msg.data);
            });
        });
    </script>
</body>
</html>

注意,background_thread()函数。在这个函数中,您将调用安装函数,并在安装完成时发出响应。

最新更新