python-flask登录页面KeyError

python-flask login page KeyError

我已经使用 python-flask 编写了登录、注册和联系的代码。我收到键盘错误“0” 当我尝试登录时出现 KeyError: 'UserId' 联系。我正在使用 remoteMysql 并在用户尝试联系时使用 smtp 向管理员发送邮件。 这是我的 apps.py

@app.route('/',methods =['GET', 'POST'])
def Registration():
    msg = ''
    if request.method =="POST":
        name = request.form["name"]
        email = request.form["email"]
        password = request.form["password"]
        cursor = mysql.connection.cursor()
        cursor.execute('SELECT * FROM tableone WHERE name = % s', (name, ))
        account = cursor.fetchone()
        print(account)
        if account:
            msg = 'Account already exists !'
        elif not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            msg = 'Invalid email address !'
        elif not re.match(r'[A-Za-z0-9]+', name):
            msg = 'name must contain only characters and numbers !'
        else:
            cursor.execute('INSERT INTO tableone VALUES(NULL,% s,% s,% s)',(name,email,password))
            mysql.connection.commit()
            msg = "you have sucessfully got registered"
            TEXT = "Hello "+name + ",\n\n"+ """Thanks for applying registring at smartinterns """
            message  = 'Subject: {}\n\n{}'.format("smartinterns Carrers", TEXT)
            sendmail(TEXT,email)
            #sendgridmail(email,TEXT)
    elif request.method == 'POST':
        msg = 'Please fill out the form !'
    return render_template("Registration.html",msg = msg)

@app.route('/login',methods=['GET', 'POST'])
def Login():
    global UserId
    msg = ''
    if request.method == 'POST' and 'name' in request.form and 'password' in request.form:
        name = request.form['name']
        password = request.form['password']
        # Check if account exists using MySQL
        cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
        cursor.execute('SELECT * FROM tableone WHERE name = %s AND password = %s', (name, password,))
        # Fetch one record and return result
        account = cursor.fetchone()
        print (account)
        # If account exists in accounts table in out database
        if account:
            # Create session data, we can access this data in other routes
            session['loggedin'] = True
            session['id'] = account[0]
            UserId = account[0]
            session['name'] = account[1]
            # Redirect to home page
            msg = 'Logged in successfully!'
        else:
            # Account doesnt exist or username/password incorrect
            msg = 'Incorrect username/password!'
    # Show the login form with message (if any)
    return render_template('Login.html', msg=msg)
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/contact',methods=['GET','POST'])
def contact():
    msg=' '
    if request.method =="POST":
        name = request.form['name']
        email = request.form['email']
        subject= request.form['subject']
        message = request.form['message']
        cursor = mysql.connection.cursor()
        cursor.execute('SELECT * FROM contact WHERE id = % s', (session['UserId'],))
        #account = cursor.fetchone()
        #print(account)
        cursor = mysql.connection.cursor()
        cursor.execute('INSERT INTO contact VALUES (% s, % s, % s, % s,% s)', (session['UserId'],name, email,subject,message))
        mysql.connection.commit()
        msg = 'You have successfully applied for job !'
        session['loggedin'] = True
        TEXT = " "+message+"from"+email+" "
        sendmail(TEXT,"kavyapadala259@gmail.com")
        #sendgridmail("kavyapadala259@gmail.com",TEXT)
    elif request.method == 'POST':
        msg = 'Please fill out the form !'
    return render_template('contact.html', msg = msg)

remoteMysql包含 包含字段 UserId、名称、电子邮件、密码的表 联系字段 id,name,email,subject,message

这是一本字典。因此我们写 account("UserId") 而不是 account[0]。这将解决错误 keyerror:'0'。用键而不是索引号抓取。