【问题标题】:Why won't this python web app page redirect me properly?为什么这个 python 网页应用程序页面不能正确重定向我?
【发布时间】:2020-12-01 19:26:52
【问题描述】:

我正在尝试使用 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)** ```

【问题讨论】:

  • 如果注册失败,“主页”是重定向的目标吗(主页是注册页面)?并且 HTML 保存在一个名为“homepage.html”的文件中? / 中的任何内容都是成功登录的目标?
  • 首页已经提示用户注册(或登录),为什么还有单独的注册页面?只是将失败的登录重定向回注册页面,因为它显然是在做这两件事。
  • 目标重定向是 ("/"),它是允许其他功能的索引,也是成功登录的目标。对于不成功的登录,我希望它自动重定向到 register.html 抱歉,如果我似乎不太了解。我不。我是编程新手。

标签: python postgresql flask psycopg2


【解决方案1】:

您的链接指向尚未为其创建路由的端点。 (您在 Flask 应用程序中使用了两次“/homepage”)

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

你可能想要

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

【讨论】:

  • 谢谢!让我编辑问题。我没有提供我的全部代码。但这没有用。
【解决方案2】:

文档中的快速入门指南显示重定向与 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'))

?

【讨论】:

    【解决方案3】:

    解决方法是更改​​路线。我有两条通往同一个地方的路线,所以不是

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

    应该是的

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

    由于名称相同,它在做一些奇怪的事情,查询没有获取数据,而是重新启动主页。

    【讨论】:

      猜你喜欢
      • 2011-12-24
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多