简体   繁体   English

Flask POST 404 错误和动态数据更新

[英]Flask POST 404 Error and Dynamic Data Update

I'm trying to make a Flask web that has a pomodoro timer where the user can set the timer themselves.我正在尝试制作一个 Flask web ,它有一个番茄计时器,用户可以自己设置计时器。

Here's my code: app.py这是我的代码:app.py

import time
from flask import Flask, render_template, url_for, flash, redirect, request, jsonify
app = Flask(__name__)


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


# Get is for loading that page; Post is for submitting the "form" / set timer
@app.route("/pomodoro.html", methods=["GET", "POST"])
def pomodoro():

    if request.method == "POST":

        # Cast user inputs as int and store in variables
        hours = int(request.form.get("hours"))
        minutes = int(request.form.get("minutes"))
        seconds = int(request.form.get("seconds"))

        # Check if user input is valid aka no negative numbers
        if hours < 0 or minutes < 0 or seconds < 0:
            return apology("There is no negative time...", 400)
        
        # Check if the input is blank. If so, replace with 0
        if not hours:
            hours = 0
        elif not minutes:
            minutes = 0
        elif not seconds:
            seconds = 0

        # Calculate total number of seconds from the user inputs
        totalTime = hours * 3600 + minutes * 60 + seconds
        print(totalTime)

        # Countdown timer
        while(totalTime > -1):
            # Call the function to start countdown
            hours, minutes, seconds = runTimer(totalTime)
            totalTime -= 1
            return jsonify({'hours' : hours, 'minutes' : minutes, 'seconds' : seconds})
        
        # Let the user know if the time has expired 
        if(totalTime == 0):
            flash("Time's up")       

    # User reached route via GET (as by clicking a link or via redirect)
    else:
        return render_template("pomodoro.html")


# Figure out how many h, m, s there are and store them in total variables
def runTimer(totaltime):

    # Divmod returns 2 values. Ex. 10/5 then totalMin will be 2 and totalSec, or the remainder, will be 0
    # Parameter is totaltime / 60
    totalMinutes, totalSeconds = divmod(totaltime, 60)

    totalHours = 0
    if(totalMinutes > 60):
        totalHours, totalMinutes = divmod(totalMinutes, 60)

    return totalSeconds, totalMinutes, totalHours


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

pomodoro.html番茄钟.html

{% extends "layout.html" %}

{% block title %}
    Pomodoro
{% endblock %}

{% block script %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
<script type="text/javascript">
    // This function will be executed after the HTML is loaded
    $(document).ready(function() {

        // When the submit button is clicked, the function with AJAX starts
        $('#start_button').on('submit',  function(e) {
            // Prevent event default before starting an ajax call
            e.preventDefault();
            console.log("Hello");

            $.ajax({
                data : {
                // Key : value pair. 
                sec : $('#seconds').val(),
                min : $('#minutes').val(),
                hr : $('#hours').val(),
                },
                type : 'POST',
                // Where to get the data
                url : '/pomodoro',
                // After data is obtained, update values
                success: function(data) {
                $('#hours').val(data.hours);
                $('#minutes').val(data.minutes);
                $('#seconds').val(data.seconds);
                } 
            });
        })
    });

</script>
{% endblock %}

{% block main %}
    <form action="/pomodoro" method="post">
        <div id="countdown_container">
            <ul>
                <li><input type="number" id="hours" name="hours" placeholder="Hours" value="{{ request.form.hours }}"></li>
                <li><input type="number" id="minutes" name="minutes" placeholder="Minutes"></li>
                <li><input type="number" id="seconds" name="seconds" placeholder="Seconds"></li>
            </ul>
        </div>

        <div id="buttons_container">
            <button id="start_button" type="submit" class="btn btn-secondary">Start</button>
            <button id="cancel_button" type="button" class="btn btn-secondary">Cancel</button>
        </div>
    </form>

{% endblock %}

I have 2 questions about my code.我对我的代码有 2 个问题。

  1. I'm getting a POST 404 error.我收到 POST 404 错误。 My GET works fine.我的 GET 工作正常。 I tried printing in app.py and pomodoro.html but neither showed up.我尝试在 app.py 和 pomodoro.html 中打印,但都没有出现。 I tried using the debugger but perhaps I was doing it wrong, the debugger wouldn't let me go into my def pomodoro function to check the specifics.我尝试使用调试器,但也许我做错了,调试器不允许我将 go 放入我的 def pomodoro function 以检查细节。 I double checked my spelling and syntax so hopefully there's no careless mistake.我仔细检查了我的拼写和语法,所以希望没有粗心的错误。

  2. Right now, my pomodoro is being calculated in app.py then the information is sent over to pomodoro.html.现在,我的番茄时间正在 app.py 中计算,然后信息被发送到 pomodoro.html。 Am I on the right track?我在正确的轨道上吗? I'm not sure if this will allow dynamic data update on the webpage.我不确定这是否允许网页上的动态数据更新。

Thank you!谢谢!

Your app route is "/pomodoro.html" and your form is posting to "/pomodoro", I don't think the form can actually properly post anywhere.您的应用程序路线是“/ pomodoro.html”并且您的表单正在发布到“/ pomodoro”,我认为该表单实际上不能正确地发布到任何地方。 Try matching your route in app.py and where the form posts to in pomodoro.html尝试在 app.py 中匹配您的路线以及在 pomodoro.html 中的表单发布位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM