python - python-flask登录页面KeyError
问题描述
我已经使用 python-flask 编写了登录、注册和联系的代码。我在尝试登录时收到 keyerror'0' 和 KeyError: 'UserId' in contact。当用户尝试联系时,我正在使用 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、名称、电子邮件、主题、消息
解决方案
这是一本字典。因此我们写 account("UserId") 而不是 account[0]。这将解决错误 keyerror:'0'。用键而不是索引号抓取。
推荐阅读
- angular - 在主应用程序组件中的对象的材质对话框中显示数据?
- javascript - 关键事件上的 event.preventDefault 在 Android 上的 Chrome 中不起作用
- c# - 使用异步/等待的彗星式 API 消耗
- java - 在 Java JSch Shell 中获得两次 shell 提示
- python - ExponentialDecay 位于具有嵌入权重的不同图中
- scala - Scala Map 上是否明确定义了 take 函数?
- spring - 过滤器(在 Spring Boot Web 应用程序中)能否根据所有定义的 RequestMapping 验证请求 URL?
- javascript - HTML文件中的Javascript不会输出变量
- r - 我无法在 R 中拼接降价,接收和错误;我该如何解决这个问题?更新:
- ruby-on-rails - ActiveAdmin 按嵌套关联排序