本文介绍了带动态服务器日志文件内容的flask应用程序更新预标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用长时间计算产生的日志文件,并将其刷新到pre标签中.

Using a logfile that is produced by a long computation and refresh it into a pre tag.

使用可打开或关闭而不是始终打开的JS函数(非内联)编写脚本.

Scripted with a JS function (not inline) that can be toggled on or off, instead of always on.

我已尝试从此处接受的答案中改编解决方案,由于未呈现,因此无法正常工作.

I have tried to adapt solution from the accepted answer here Display the contents of a log file as it is updated into function and it does not work as expected because it does not render.

日志文件已由其他软件相应地更改.

Log File is changed by another software accordingly.

烧瓶Python

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html',
                            str_log = url_for('static',log.txt"))

@app.route('/', methods=['POST'])
def all_forms_post():
    if request.method == 'POST':
        if request.form['id_form'] == 'I.2':
            #do code that changes log.txt
            index
            return redirect(request.url)
    return redirect(request.url)

HTML

<form method="post" action="/" enctype="multipart/form-data">
    <input type="hidden" name="id_form" value="I.2" />
    <input type="submit" name="btn" value="simulate" onclick="refreshPre('{{ str_log }}', true)" />
</form>
<pre id="contents"> 
    Hello click button to start simulation and update this
</pre>

JS

// global JavaScript Variables here
var timerId;

/*Fetches*/
function refreshPre(url, blRefresh = true) {
    if (blRefresh) {
        // declare and assign setInterval
        timerId = window.setInterval(populatePre(url),1000);
    } else {
        // stop setInterval
        window.clearInterval(timerId);
        timerId = null;
    }
}

function populatePre(url) {
    var output = document.getElementById('contents');
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.send();
}

想法是非常值得赞赏的欢呼.

Ideas are very appreciated cheers.

推荐答案

您需要重写setInterval回调函数并添加xhr.onload回调,如下所示:

You need to rewrite the setInterval callback function and add an xhr.onload callback like this:

//global JavaScript Variables here
var timerId;

/*Fetches*/
function refreshPre(url, blRefresh = true) {
    if (blRefresh) {
        //declare and assign setInterval
        timerId = window.setInterval(function(){ populatePre(url) },1000);
    } else {
        //stop setInterval
        window.clearInterval(timerId);
        timerId = null; 
    }
}

function populatePre(url) {
    var output = document.getElementById('contents');
    var xhr = new XMLHttpRequest();
    // Listen to xhr events for response:
    xhr.onload = function(){
        output.innerText = xhr.response;
    }    
    xhr.open('GET', url);
    xhr.send();
}

XMLHttpRequest参考

这篇关于带动态服务器日志文件内容的flask应用程序更新预标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 19:30