python 使用 flask 应用程序动态更新变量

6ss1mwsb  于 2023-02-11  发布在  Python
关注(0)|答案(1)|浏览(273)

我正在尝试创建一个脚本与flask,增加或减少一个值10通过点击一个按钮。我已经有一个脚本,这样做的后端,但我有麻烦显示和动态更新这个值在前端。基本上,我想改变这个值在前端和后端在同一时间没有刷新页面。
以下是后端代码(缩短后包含相关页面):
app.py-培养瓶应用程序

from flask import Flask, render_template, url_for, request, jsonify

app = Flask(__name__) 
#motor = Motor(17, 18)

def setBPM(current, change=0):
    return ((current < 200) & (change > 0))*(current+change) + ((current > 30) & (change < 0))*(current+change)

@app.route('/pulse')
def pulse():
    return render_template("pulse.html")

@app.route('/pulseUP', methods=['POST'])
def pulseUp():
    BPM = setBPM(BPM, 10)
    return (render_template('pulse.html', get_BPM_var=BPM))

@app.route('/pulseDOWN', methods=['POST'])
def pulseDwn():
    BPM = setBPM(BPM, -10)
    return (render_template('pulse.html', get_BPM_var=BPM))

@app.context_processor
def get_BPM_var():
    return dict(get_BPM_var=BPM)

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

前端-pulse.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=800px, inital-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"
</head>

<body>
    <div class="parent">
        <div class="child">
<div id="grid-pulse">
    <div class="cell-pulse">
        <form action="/pulseUP/" method="post"><input type="submit" value="+" /></form>
    </div>
    <div class="cell-pulse"></div>
    <div class="cell-pulse">
        <div class="numbkgnd">
            <h3 id="BPMID">{{ get_BPM_var }}&#13;BPM</h3>
        </div>
    </div>
    <div class="cell-pulse"></div>
    <div class="cell-pulse">
        <form action="/pulseDOWN/" method="post"><input type="submit" value="-" /></form>
    </div>
    <div class="cell-pulse"></div>
</div>
</div>
    </div>
<script>
    $("#BPMID").keyup(function () {
        var text = $(this).val();

        $.ajax({
            url: "/pulse",
            type: "get",
            data: { jsdata: text },
            success: function (response) {
                $("#BPMID").html(response);
            },
            error: function (xhr) {

            }
        });
    });
</body>
</html>

我试着用 AJAX 来更新值,但是我一点也不懂javascript。任何帮助都会非常感谢!!

iqjalb3h

iqjalb3h1#

我的示例基于range slider,它的值对应于发送到服务器的速度,该值可以以10为增量增加或减少。
当触发一个change事件时,浏览器使用Fetch API向服务器发送一个AJAX POST类型的请求,这个JSON格式的请求包含了滑块的当前值。
服务器设置接收到的值,只要在允许的范围内,并以当前的速度以JSON格式回复,收到回复后,现在调整浏览器中的输出,即将值输出为文本,并设置为滑块的新值。
除了滑块外,还有两个按钮可以用来设置值,按下按钮可以设置滑块的值并触发其change事件,之后的过程保持不变。

from flask import (
    Flask, 
    jsonify, 
    render_template, 
    request
)

class Motor:
    def __init__(self):
        self._rpm = 30

    @property
    def rpm(self):
        return self._rpm
    
    @rpm.setter
    def rpm(self, value):
        if 30 <= value <= 200:
            self._rpm = value
        else:
            raise ValueError('Value range must be between 30 and 200.')

app = Flask(__name__)
motor = Motor()

@app.route('/')
def index():
    v = motor.rpm
    return render_template('index.html', **locals())

@app.post('/adjust-speed')
def adjust_speed():
    v = motor.rpm
    try:
        motor.rpm = int(request.get_json(force=True).get('v'))
        v = motor.rpm
    finally:
        return jsonify(**locals())
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Control</title>
</head>
<body>

    <input type="range" min="30" max="200" value="{{ v }}" step="10" id="speed">
    <p>Velocity: <output id="value">{{ v }}</output></p>
    <button id="btn-dec">-</button>
    <button id="btn-acc">+</button>

    <script type="text/javascript">
        (() => {
            
            /** Send the expected speed to the server. */
            const adjustSpeed = async (value) => {
                const data = await fetch('/adjust-speed', {
                    method: 'post', 
                    body: JSON.stringify({ v: value })
                }).then(resp => resp.ok && resp.json());
                if (!data || !data.v) throw new Error('Error adjusting speed.');
                return data.v;
            };

            const outputValue = document.getElementById('value');
            const speedSlider = document.getElementById('speed');
            speedSlider.addEventListener('change', async function(evt) {
                // Send the slider's value to the server and 
                // output the actual speed obtained.
                try {
                    const v = await adjustSpeed(Number(this.value));
                    this.value = v;
                    outputValue.innerText = v;
                } catch(err) {
                    console.error(err);
                }
            });

            const buttonAcc = document.getElementById('btn-acc');
            buttonAcc.addEventListener('click', () => {
                // Set the new value of the slider and trigger the change event. 
                const value = Number(speedSlider.value), step = Number(speedSlider.step);
                speedSlider.value = value + step;
                speedSlider.dispatchEvent(new Event('change'));
            });

            const buttonDec = document.getElementById('btn-dec');
            buttonDec.addEventListener('click', () => {
                // Set the new value of the slider and trigger the change event. 
                const value = Number(speedSlider.value), step = Number(speedSlider.step);
                speedSlider.value = value - step;
                speedSlider.dispatchEvent(new Event('change'));
            });

        })();
    </script>
</body>
</html>

相关问题