Home > Enterprise >  Flask Dynamic URL routing - bad request 400
Flask Dynamic URL routing - bad request 400

Time:02-12

I'm using Flask to build a web app and having issues with dynamic routing with variables. I'm getting a bad request when I run the program.

The whole goal is to create a dynamic URL. The hope is to get dynamic URLs based on user selection. Running the program shows the correct URL (webapp.com/result/ko) but will not show the contents of the page.

Python:

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

app = Flask(__name__)
# This saves the users requested ticker choice in a varible to be used later
def users_request():
    global ticker_choice
    ticker_choice = request.form["variable"]
    return("Your choosen ticker: "   ticker_choice.upper())

class companySearch:

    # Stock price function
    def stock_price_func(self):
        try:
            with urlopen(base_url   quote   ticker_choice.upper()   api_key) as response:
                source = response.read()
                data = json.loads(source)

            price = "$"   str((data[0]["price"]))
            return(price)
        except:
            return("-")

# Routing to the homepage
@app.route("/", methods = ["GET", "POST"])
def market_hours_today():
    if request.method == "POST":
        result = request.form["variable"]
        return redirect(url_for("ticker_result", variable=result))

    return render_template(
        "index.html")

# Routing to the result page
@app.route("/result/<variable>", methods = ["GET", "POST"])
def ticker_result(variable):
    users_ticker_choice = users_request()
    stock_price = companySearch().stock_price_func()
    if request.method == "POST":
        result = request.form["variable"]
        return render_template(
            "result.html", 
            result=result, 
            users_ticker_choice=users_ticker_choice,
            stock_price=stock_price)

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

HTML:

<!DOCTYPE html>
<html lang="en">
</head>
<body>
    <div >
        <div  id="cell-1-2">
            <span  style="text-align: center;">
                <form action="{{ url_for('market_hours_today') }}" method="POST">
                <input type="text" name="variable" placeholder="search ticker or company" maxlength="4" font-size="24px" onkeypress="return (event.charCode > 64 && 
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" style="text-transform:uppercase">
                <input  type="submit" value="Search" onclick="tickerSymbol();">
                </form>
            </span>
        </div>
    </div>  
</body>
</html>

enter image description here

CodePudding user response:

as far as I can see the ticker_result function does not return anything for GET requests.

CodePudding user response:

That's because you have return for only POST requests. You don't return anything for get requests

  • Related