如何将 int 从 html 文件(模板)传递到 py 文件(烧瓶)?

How do i pass an int from html file (template) to py file (flask)?

我正在尝试创建一个本地站点(只是为了了解 Flask 的基础知识),我想点击一个按钮并将点击次数存储在一个 txt 文件中。我点击了按钮,可以将点击次数发送到 html 文件,但我不知道如何将该 int 发送回 py 文件以更新 txt 文件。

在下面的代码中,我使用 localStorage 作为替代,但我希望它从 txt 文件中获取数据,并在按下按钮时将数据发送回 txt 文件。

html 文件-

<body>
<button type="button" onclick="buttonPress()">Click Me!</button>
<button type="button" onclick="reset()">Reset</button>

<script type="text/javascript">
    var clicks = {{ sClicks }}

    localStorage.setItem('sClicks', clicks);
    updateText();

    function buttonPress(){
        clicks += 1;
        localStorage.setItem('sClicks', clicks);
        updateText();
    }

    function reset(){
        localStorage.clear();
        clicks = 0;
        localStorage.setItem('sClicks', clicks);
        updateText();
    }

    function updateText(){
        document.getElementById("carrier").innerHTML = localStorage.getItem('sClicks');
    }
</script>
</body>

py文件-

app = Flask(__name__)
clicks = open('Clicks.txt').read()

@app.route('/')
def test():
    return render_template('index.html', sClicks=clicks)

if __name__ == '__main__':
    app.run(debug=True, host='my ip adress')

下面是一个示例,说明如何使用 javascript xhr 请求发送事件,该请求将 post 请求发送到 /clicks 路由。

请注意,在 POST 请求中,我没有向请求正文添加任何数据,而只是使用 POST 请求调用路由这一事实作为通知计数器应增加 1。

from flask import Flask, request
from os import path

app = Flask(__name__)


@app.route("/clicks", methods=["POST", "GET"])
def click_collector():
    # POST logic
    if request.method == "POST":
        current_count = read_click_db()
        if current_count is not None:
            new_count = int(current_count) + 1
            return write_click_db(new_count)
        return write_click_db(1)

    # GET logic
    elif request.method == "GET":
        current_count = read_click_db()
        if current_count is not None:
            return current_count
        return "0"


def read_click_db() -> str:
    if not path.isfile("Clicks.txt"):
        print("File doesn't exist")
        return
    with open("Clicks.txt", "rt") as f:
        click_counter = f.readline()
        f.close()
    return click_counter


def write_click_db(counter: int):
    with open("Clicks.txt", "wt") as f:
        f.write(str(counter))
        f.close()
        return str(counter)


if __name__ == "__main__":
    app.run(host="localhost", port=5000)

在浏览器控制台中执行以下 JavaScript 函数。

function notify_click_event() {
    req = new XMLHttpRequest();
    req.open("POST", "http://localhost:5000/clicks")
    req.send()
}