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

时间:2015-10-26 09:03:47

标签: python python-2.7 flask

我创建了一个简单的烧瓶应用程序。 我不会在这里展示它,因为它里面有很多Bootstrap。

我的网站看起来如此:

<li>

安装第一个扩展程序后:

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

等等......

但网站上也有引导程序。因此加载页面需要一些时间。但我只想设置状态标签。如何在不刷新整个页面的情况下做到这一点?

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

1 个答案:

答案 0 :(得分:3)

这是Flask-SocketIO的一个非常简单的实现。您可以按照此article进行更好的理解

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()功能。这是您调用安装功能并在安装完成时发出响应的函数。