为什么这个 python 网络应用程序页面不能正确地重定向我?

Why won't this python web app page redirect me properly?

我正在尝试使用 postgresql 数据库使用 flask 和 psycopg2 在 python 上创建一个登录页面,并且在登录时它应该重定向到一个页面或者如果没有找到登录名则重定向到注册页面,但它赢了'重定向... 我已经注册工作并将用户名和密码存储在数据库中。最终目标是创建一个具有注册和登录功能的杂货店应用程序。我已经尝试了几种不同的方式来写这个,但页面就是不会重定向。我想如果查询不起作用,它至少会带我去注册,但它只会重新打开主页...请帮忙。

主页HTML

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
   <title> Homepage </title>
 </head>
 <body>
 Login or Register for your username and password (*required)<br>
  <form method="POST" >
    Login Information<br>
    Enter username*: <input type="text" class="form-control" placeholder="UserName", name="username" required><br> 
        Enter password*: <input type="text"class ="form-control" placeholder="Password", name="password",  type = "Password" required><br>
    
    <input type="submit" value="Submit">
    </form>
    <a href = "/register" >Register</a>
</body>
</html>

注册页面html

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
     <title> You must create a username and password to login </title>
 </head>
 <body>
 Please input your information to register (*required)<br>
    <form method="POST" >
        Type in all fields below<br>
        Enter id*: <input type="text" placeholder="Customer ID" name="customer_id" required><br>
        Enter name*: <input type="text" placeholder="First name" name = "customer_name" required><br> 
        Enter balance*: <input type="text" placeholder="Type 0" name = "balance" required><br>
        Enter name*: <input type="text" placeholder="Type A12" name = "address_id" required><br>
        Enter username*: <input type="text" placeholder="UserName" name="username" required><br> 
        Enter password*: <input type="text" placeholder="Password" name="password" required><br> 
      
        
        <input type="submit" value="Submit">
    </form>
   </body>
</html>

python代码

import psycopg2, psycopg2.extras
from flask import Flask, flash, redirect, render_template, request
from table_defs import * #ProductTable, Customer

app = Flask(__name__)

# conn and cur as global variables
conn = psycopg2.connect(host="localhost",
                            database="FreshCart",
                            user="postgres",
                            password="Alfred45"
                            )
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

# TODO: decide if it's ok not to close cursor or conn
# cur.close()
# conn.close()

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

@app.route('/product_search')
def product_search():
    return render_template('product_search.html', **locals())

@app.route('/product_search_response', methods=['POST'])
def product_search_response():
    # get form input
    sku = request.form.get("sku")
    description = request.form.get("description")
    category = request.form.get("category")

    #TODO: right now these queries are very brittle; consider what makes sense to add for ilikes and wildcards
    #TODO: distinguish between partial matches and exact matches?
    #TODO: make these safe queries like he talked about in class
    if sku:
        cur.execute("SELECT * FROM product WHERE sku='{}'".format(sku))
    elif description:
        cur.execute("SELECT * FROM product WHERE description='{}'".format(description))
    elif category:
        cur.execute("SELECT * FROM product WHERE category='{}'".format(category))
    else:
        pass
        # TODO: do we need any action here?  If not, remove else block

    if cur.description != None:
        table = ProductTable(cur)
    else:                   # in the case of no cursor execution, gracefully return 'No Items' instead of crashing
        table = ProductTable({})

    return render_template('product_search.html', **locals())

@app.route('/add_product')
def add_product():
    return render_template('add_product.html', **locals())

@app.route('/add_product_response', methods=['POST'])
def add_product_response():
    # get form input
    sku = request.form.get("sku")
    description = request.form.get("description")
    category = request.form.get("category")
    size = request.form.get("size")
    abv = request.form.get("abv")
    calories = request.form.get("calories")
    fat = request.form.get("fat")
    carbohydrates = request.form.get("carbohydrates")
    protein = request.form.get("protein")

    # TODO: change response to execute product add and then display new record
    # TODO: add data validation checks if needed
    # TODO: add logic to check if the sku already exists and provide a link to the edit page
    # product_nutrition_alcohol_query =  "SELECT product.sku, description, category, product_size, \
    #         calories, fat, carbohydrates, protein, abv \
    #     FROM product \
    #         JOIN alcohol_content ON product.sku = alcohol_content.sku \
    #         JOIN nutrition_information ON product.sku = nutrition_information.sku \
    #     WHERE product.sku='{}'"

    #queries
    check_query = "SELECT * FROM {} WHERE sku='{}'"
    product_insert_query = "INSERT INTO product (sku, description, category, product_size) \
            VALUES ('{}', '{}', '{}', {})"
    alcohol_insert_query = "INSERT INTO alcohol_content (abv, sku) \
            VALUES ({}, '{}')"
    nutrition_insert_query = "INSERT INTO nutrition_information (calories, fat, carbohydrates, protein, sku) \
            VALUES ('{}', '{}', '{}', {})"

    # insert into product if sku doesn't already exist
    cur.execute(check_query.format("product", sku))
    if cur.fetchone() == None:
        try:
            cur.execute(product_insert_query.format(sku, description, category, size))
            conn.commit()
            cur.execute(check_query.format("product", sku))
            prod_table = ProductTable(cur)
            prod_message = "Product added!"
        except Exception as e:
            print("Could not insert into product")
            conn.rollback()
            prod_table = ProductTable({})
            prod_message = "Product could not be added"
#TODO: can't use same cursor for different things that need to be rendered - figure out a better way
        # insert into alcohol
        # if abv:
        #     try:
        #         cur.execute(alcohol_insert_query.format(abv, sku))
        #         conn.commit()
        #         cur.execute(check_query.format("alcohol_content", sku))
        #         alcohol_table = AlcoholTable(cur)
        #         alcohol_message = "alcohol information:"
        #     except Exception as e:
        #         print("Could not insert into alcohol_content")
        #         conn.rollback()
        #         # cur.execute(check_query.format("product", sku))
        #         alcohol_table = AlcoholTable({})
        #         alcohol_message = "Product could not be added"

        # insert into nutrition_information
        # if all([calories, fat, carbohydrates, protein]):
        #     pass    #add to nutrition query
        # elif any([calories, fat, carbohydrates, protein]) and not all(calories, fat, carbohydrates, protein):
        #     pass
    else:
        prod_table = ProductTable({})
        prod_message = "Product with this sku already exists; please try again"

    return render_template('add_product.html', **locals())

**#TODO: Create Login Page (we may have to create a registration page as well could serve to give User role ability to update schema/add new users)
        # pages run but code doesn't do what I want in db... 
        #   login page code  to check that login is valid - shakey, but just to get something started
        #   must create safe/prepared query for pw 
@app.route("/homepage", methods = ['GET', 'POST'])   
def homepage():
    return render_template("/homepage.html")
#TODO figure out why this wont redirect to another page once submit is hit
@app.route("/register", methods=['GET', 'POST'])   
def checklogin():
    UN = request.form.get('username')
    PW = request.form.get('password')
   # query to check if the username exists from input
    query1 = "SELECT username, password FROM customer WHERE username = '{}' AND password = '{}'"
#check if login exists if not send user to registration
    rows = cur.execute(query1.format(UN, PW))   
    rows = rows.fetchall() 
    if len(rows)== 1:
        return redirect ("/") #once you login switch to current index/ product add/search
    else: 
        return redirect ("/register")
#TODO: Create a registration page which incorporates User Role to allow them to update data on Customer Schema           
@app.route("/register",  methods=['GET', 'POST'])
def registration():
    if request.method == "POST":
        id = request.form.get ('customer_id')
        name = request.form.get ('customer_name')
        balance = request.form.get('balance')
        address_id = request.form.get('address_id')
        dUN = request.form.get('username')
        dPW = request.form.get('password')
        query2 = "INSERT into customer (customer_id, customer_name, balance, address_id, username, password)  VALUES  ('{}', '{}', {}, '{}', '{}', '{}')"
        cur.execute(query2.format(id, name, balance, address_id, dUN, dPW))
        conn.commit()
        return redirect ("/homepage")
    return render_template("register.html", **locals())
           
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)** ```

您的 link 指向一个没有创建路由的端点。 (您在 Flask 应用中使用了两次“/homepage”)

<a href = "/register" >Register</a>

你可能想要

@app.route("/register", methods=['GET', 'POST'])   
def checklogin():
    ...

文档中的快速入门指南显示重定向与 url_for() 函数结合使用。

像这样:

@app.route('/')
def index():
    return redirect(url_for('login'))

在此处的“重定向和错误”下:https://flask.palletsprojects.com/en/1.1.x/quickstart/

你试过更新吗

return redirect ("/register")

return redirect(url_for('register'))

?

解决方法是更改​​路线。我有两条路线去同一个地方所以而不是

@app.route("/register", methods=['GET', 'POST'])   
def checklogin():

应该是

@app.route("/checklogin", methods=['GET', 'POST'])   
def checklogin():

由于名称相同,所以在查询未获取数据而只是重新启动主页的地方做了一些奇怪的事情。