我无法查看此登录页面?

时间:2019-05-15 11:02:18

标签: html mysql python-3.x flask wsgi

我正在尝试使用flask和python创建一个登录页面,但无法路由到该页面,在我的情况下,它将直接返回语句并打印Hello。如果我尝试添加其他情况,它将进入其他情况并在其他情况下进行处理。如果我将主函数放在其他情况下,则会出现错误:

werkzeug.exceptions.HTTPException.wrap..newcls:400错误的请求:KeyError:'Employee_ID'

代码:

from flask import Flask, render_template, request, redirect,flash
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = "127.1.1.0"
app.config['MYSQL_USER'] = "root"
app.config['MYSQL_PASSWORD'] = "***"
app.config['MYSQL_DB'] ="users"

mysql = MySQL(app)
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        userDetails = request.form
        Employee_ID = userDetails['Employee_ID']
        password = userDetails['password']
        cur = mysql.connection.cursor()
        cur.execute("select * from user where Employee_ID=%s",(Employee_ID))
        EmpDetails=cur.fetchone()
        cur.close()
        if EmpDetails== password:
            flash('You have logged in successfully !!')
            return 0
    return "Hello"

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

HTML模板:     

</head>
<h1><center>Sign In!</center></h1>

<body>

<div class="login-page">
    <div class="form" >
<form class="register-form" method="post" action="login.html">
    <input type="text" id="Employee_ID" placeholder="Employee ID" />
    <input type="password" id="password" placeholder="password"/>

    <button>Enter</button>
        </form>
    </div>    

</div>

</body>


</html>

2 个答案:

答案 0 :(得分:1)

您在html输入中缺少 name 字段。使用输入名称字段来获取表单元素。您正在尝试使用id字段获取元素值,由于该字段引发了 KeyError ,因为找不到带有该键的表单中的元素。

将HTML文件更改为:

</head>
<h1><center>Sign In!</center></h1>

<body>

<div class="login-page">
    <div class="form" >
<form class="register-form" method="post" action="login.html">
    <input type="text" id="Employee_ID" name="Employee_ID" placeholder="Employee ID" /> <-- add name field
    <input type="password" id="password" name="password" placeholder="password"/> <--add name field

    <button>Enter</button>
        </form>
    </div>    

</div>

</body>


</html>

希望它对您有帮助。

答案 1 :(得分:0)

您正在执行错误的wtith html代码以运行python函数,并且需要以html形式定义以触发这样的操作。

正确的解决方案:

<form class="register-form" method="post" action="/login">
<input type="text" id="Employee_ID" placeholder="Employee ID" />
<input type="password" id="password" placeholder="password"/>
 <input type="submit"/>
    </form>
相关问题