烧瓶表格未发送发布请求

时间:2020-10-18 17:09:20

标签: python-3.x flask post

当我按下下面HTML表单中的三个输入按钮中的任何一个时,它不会向我的messages()函数发送POST请求。我一直试图弄清楚如何指定表单中哪个输入按钮被按下,这就是为什么函数中每个按钮都有不同的if语句的原因。我已经搜索了好几天,直到意识到它甚至根本没有发送POST请求。

我意识到还有其他问题与此标题几乎相同,但是我已经仔细阅读了所有问题,没有一个可以帮助我解决我的问题,所以请不要将此问题标记为重复的帖子。

如果您需要更多的代码,只问一下!谢谢!

@app.route("/messages", methods=["POST", "GET"])
def messages():
    values = users.query.all()
    try:
        using = session['username']
        passing = session['password']
    except:
        flash("You Need To Log In First!")
        return redirect(url_for("login"))
    tic_value = ""
    global driver
    price_list = []
    count = -1
    user_ticker_db = users.query.filter_by(username=using, password=passing).first()
    db.session.commit()
    for p in user_ticker_db.tick_values:
        if p != " ":
            tic_value += p 
        if p == " ":
            price_list.append(tic_value)
            tic_value = ""
    my_prices = []
    my_news = []
    while True:
        for x in price_list:
            count += 1
            driver.get(f"https://www.google.com/search?client=firefox-b-1-d&q={price_list[count]}+stock+price")
            price = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[10]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div/div/g-card-section/div/g-card-section/span[1]/span/span[1]").text
            driver.get(f"https://www.google.com/search?q={price_list[count]}+stock+price&client=firefox-b-1-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwi4nJvnz6fsAhXSXM0KHR4gBTgQ_AUoAnoECCcQBA&biw=1036&bih=569&dpr=1.5")
            news = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[9]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/g-card/div/div/div[2]/a/div/div[2]/div[2]").text
            my_prices.append(f"${price}")
            my_news.append(news)
        return render_template("messages.html", my_stock = zip(price_list, my_prices, my_news), amount = len(price_list))
        if request.method == "POST":
            #It never reaches here...
            print("post request")
            if request.form.get("Reload_Prices"):
                print("its working")
                for x in price_list:
                    count += 1
                    driver.get(f"https://www.google.com/search?client=firefox-b-1-d&q={price_list[count]}+stock+price")
                    price = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[10]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div/div/g-card-section/div/g-card-section/span[1]/span/span[1]").text
                    driver.get(f"https://www.google.com/search?q={price_list[count]}+stock+price&client=firefox-b-1-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwi4nJvnz6fsAhXSXM0KHR4gBTgQ_AUoAnoECCcQBA&biw=1036&bih=569&dpr=1.5")
                    news = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[9]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/g-card/div/div/div[2]/a/div/div[2]/div[2]").text
                    my_prices.append(f"${price}")
                    my_news.append(news)
                return render_template("messages.html", my_stock = zip(price_list, my_prices, my_news), amount = len(price_list))
            elif "Remove_Ticker" in request.form:
                ticker_request = request.form["tick_value"]
                try:
                    remove_ticker_db = users.query.filter_by(username=using, password=passing).first()
                    remove_ticker_db.tick_values = remove_ticker_db.tick_values - (ticker_request + " ")
                    db.session.commit()
                    flash("Ticker Removed")
                except:
                    flash("Ticker Not Saved")
            elif request.form["action"] == "Add_Ticker":
                print("loading")
                ticker_request = request.form["tick_value"]
                try:
                    print("worked")
                    driver.get(f"https://www.google.com/search?client=firefox-b-1-d&q={ticker_request}+stock+price")
                    price = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[10]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div/div/g-card-section/div/g-card-section/span[1]/span/span[1]").text
                    add_ticker_db = users.query.filter_by(username=using, password=passing).first()
                    add_ticker_db.tick_values = add_ticker_db.tick_values + (ticker_request + " ")
                    db.session.commit()
                    flash("Ticker Added")
                except:
                    print("Broken")
                    flash("Invalid Ticker Symbol")
                    pass
                #item.tick_values
                # Need to add the values from the ticker input box to the database so that when a specific user logs on it will show their stocks
                # Will also add a column of text with the names of the tickers you have selected and you can type it into the box and click remove to get rid of it from database
    else:
        print("failed")
        return render_template("messages.html", my_prices=f"$aapl price", my_news="aapl News")

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

我的HTML文件。

    <form action="{{ url_for('messages') }}" method='POST'>
        <input type='submit', name='action', value='Reload_Prices'>
        <br>
        <input type='submit', name='action', value='Add_Ticker'>
        <input type='text', name='tick_value'>
        <input type='submit', name='action', value='Remove_Ticker'> 
        {% for ticker in ticker_values %}
            <br>
            <input type='text', value=ticker>
        {% endfor %}
    </form>

1 个答案:

答案 0 :(得分:0)

甚至不能确切地确定错误的出处,但我完全重写了代码,这次看起来工作正常,有一些小错误。无论如何,这里都是...如果您发现有任何错误,请随时发布。

@app.route("/messages", methods=["POST", "GET"])
def messages():
    values = users.query.all()
    try:
        using = session['username']
        passing = session['password']
    except:
        flash("You Need To Log In First!")
        return redirect(url_for("login"))
    tic_value = ""
    global driver
    global my_prices
    global my_news
    global price_list
    price_list = []
    count = -1
    user_ticker_db = users.query.filter_by(username=using, password=passing).first()
    db.session.commit()
    for p in user_ticker_db.tick_values:
        if p != " ":
            tic_value += p 
        if p == " ":
            price_list.append(tic_value)
            tic_value = ""
    my_prices = []
    my_news = []
    for x in price_list:
        try:
            count += 1
            driver.get(f"https://www.google.com/search?client=firefox-b-1-d&q={price_list[count]}+stock+price")
            price = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[10]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div/div/g-card-section/div/g-card-section/span[1]/span/span[1]").text
            driver.get(f"https://www.google.com/search?q={price_list[count]}+stock+price&client=firefox-b-1-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwi4nJvnz6fsAhXSXM0KHR4gBTgQ_AUoAnoECCcQBA&biw=1036&bih=569&dpr=1.5")
            news = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[9]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/g-card/div/div/div[2]/a/div/div[2]/div[2]").text
            my_prices.append(f"${price}")
            my_news.append(news)
        except:
            print("Error loading tickers/news")
        
    if request.form.get('reload', False) == "Reload_Prices":
        count = -1
        print("its working")
        for x in price_list:
            try:
                count += 1
                driver.get(f"https://www.google.com/search?client=firefox-b-1-d&q={price_list[count]}+stock+price")
                price = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[10]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div/div/g-card-section/div/g-card-section/span[1]/span/span[1]").text
                driver.get(f"https://www.google.com/search?q={price_list[count]}+stock+price&client=firefox-b-1-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwi4nJvnz6fsAhXSXM0KHR4gBTgQ_AUoAnoECCcQBA&biw=1036&bih=569&dpr=1.5")
                news = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[9]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/g-card/div/div/div[2]/a/div/div[2]/div[2]").text
                my_prices.append(f"${price}")
                my_news.append(news)
            except:
                print("Error loading tickers/news")
        return render_template("messages.html", my_stock = zip(price_list, my_prices, my_news), amount = len(price_list))
        count = 0
    elif request.form.get('remove', False) == "Remove_Ticker":
        print("removing")
        ticker_request = request.form["tick_value"]
        try:
            remove_ticker_db = users.query.filter_by(username=using, password=passing).first()
            remove_ticker_db.tick_values = str(remove_ticker_db.tick_values).replace(str(ticker_request + " "), "")
            db.session.commit()
        except:
            print("error when removing")
        return render_template("messages.html", my_stock = zip(price_list, my_prices, my_news), amount = len(price_list))
                   
    elif request.form.get('add', False) == "Add_Ticker":
        print("adding")
        ticker_request = request.form["tick_value"]
        try:
            driver.get(f"https://www.google.com/search?client=firefox-b-1-d&q={ticker_request}+stock+price")
            price = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[10]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div/div/g-card-section/div/g-card-section/span[1]/span/span[1]").text
            add_ticker_db = users.query.filter_by(username=using, password=passing).first()
            add_ticker_db.tick_values = str(add_ticker_db.tick_values) + str(ticker_request + " ")
            db.session.commit()
        except:
            print("error when adding")
        return render_template("messages.html", my_stock = zip(price_list, my_prices, my_news), amount = len(price_list))
        
    else:
        for x in price_list:
            driver.get(f"https://www.google.com/search?client=firefox-b-1-d&q={price_list[count]}+stock+price")
            price = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[10]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div/div/g-card-section/div/g-card-section/span[1]/span/span[1]").text
            driver.get(f"https://www.google.com/search?q={price_list[count]}+stock+price&client=firefox-b-1-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwi4nJvnz6fsAhXSXM0KHR4gBTgQ_AUoAnoECCcQBA&biw=1036&bih=569&dpr=1.5")
            news = driver.find_element_by_xpath("/html/body/div[8]/div[2]/div[9]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/g-card/div/div/div[2]/a/div/div[2]/div[2]").text
            my_prices.append(f"${price}")
            my_news.append(news)
    
        return render_template("messages.html", my_stock = zip(price_list, my_prices, my_news))

然后这是我的HTML

<form action="{{url_for('messages')}}", method='POST'>  
    <input type='submit', name='reload', value='Reload_Prices'>
    <br>
    <input type='submit', name='add', value='Add_Ticker'>
    <input type='text', name='tick_value'>
    <input type='submit', name='remove', value='Remove_Ticker'>
</form>