【问题标题】:Flask: How to update values on a web pageFlask:如何更新网页上的值
【发布时间】:2022-07-21 23:44:47
【问题描述】:

我有以下代码:


app = Flask(__name__)


@app.route("/")
def Tracking():

    lower = np.array([35, 192, 65])
    upper = np.array([179, 255, 255])

    video = cv2.VideoCapture(1, 0)

    times = []  
    total = 0  
    is_round = False  

    while True:
        success, img = video.read()
        image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        mask = cv2.inRange(image, lower, upper)
        blur = cv2.GaussianBlur(mask, (15, 15), 0)

        circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, 1, 14,
                                   param1=34, param2=10, minRadius=4, maxRadius=10)

        circles = np.uint16(np.around(circles))


        if (len(circles[0, :]) == 7) and not is_round:
            start_time = time.time()  
            is_round = True
            curr_count = 0 
            round_total = 0  


        elif is_round:
            if len(circles[0, :]) == 1:
                end_time = time.time()  
                is_round = False
                time_taken = end_time - start_time
                print('Round time: ', str(
                    datetime.timedelta(seconds=time_taken))[2:7])

                times.append(time_taken)
                average = sum(times) / len(times)
                print('Average time: ', str(
                    datetime.timedelta(seconds=average))[2:7])

            elif len(circles[0, :]) < 7:
                curr_count = (7 - round_total) - len(circles[0, :])
                total += curr_count 
                round_total += curr_count 

            for i in circles[0, :]:
                cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2)
                cv2.circle(img, (i[0], i[1]), 2, (0, 0, 255), 3)


        return render_template('theme1.html', output2=total)


if __name__ == "__main__":
    app.run(debug=True)

HTML 代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <meta http-equiv="refresh" content="10" >

    <link rel= "stylesheet"  href= "{{ url_for('static', filename='styles.css')}}">

    

</head>
<body>


        <div class="data">
        <p>{{  output2  }}</p>

        </div>
   




 
</body>
</html>

我需要这些值每 10 秒左右更新一次,建议我使用 ajax 但我不知道如何应用它,非常感谢任何帮助,python 脚本使用 opencv 来检测实时提要中的对象, "total" 将对象的数量打印为整数,这是我试图在我的网页上更新的内容。

【问题讨论】:

    标签: javascript python ajax flask websocket


    【解决方案1】:

    函数会在遇到 return 语句时停止,因此您的代码将在第一次迭代时停止。

    所以改为创建两条路由,首先传递网页,然后仅传递数据。

    在主网页中创建一个周期性函数,该函数将使用 get 方法从第二个路由中获取数据。

    http-eqiv=refresh 也会在每次获取新数据时刷新网页。但是这个实现不会刷新网页,仍然会动态更新网页。

    由于您的开放式 cv 代码处于循环中,您可以创建一个生成器函数,该函数将在每次调用时给出下一个值。我会把它留给你。

    这是我的实现

    app = Flask(__name__)
    
    
    @app.route("/")
    def home():
        return render_template('theme1.html')
    
    @app.get("/update")
    def update():
    
        total = str(random.random()) ## replace this with what you want to send
    
        return total
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Document</title>
        <link rel= "stylesheet"  href= "{{ url_for('static', filename='styles.css')}}">
    
    </head>
    <body>
    
        <div class="data">
        <p id="output"></p>
        </div>
    
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
        <script>
            function update(){
                $.get("/update", function(data){
                    $("#output").html(data)
                });
            }
            update()
            var intervalId = setInterval(function() {
                update()
            }, 10000);
    
        </script>
            
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 2013-01-30
      • 1970-01-01
      • 2017-12-05
      相关资源
      最近更新 更多