我正在尝试创建一个用户注册页面来练习Flask。我设法使所有工作正常进行,但是我唯一遇到的问题是数据库。每当我在注册页面中输入虚拟文本并按提交时,都会出现此错误:
MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
我尝试了类似的解决方案,但无济于事。我尝试过刷新特权等,但我真的不太明白这是怎么回事。
到目前为止,这是我的代码:
from flask import Flask
from flask import render_template
from flask import flash
from flask import redirect
from flask import url_for
from flask import session
from flask import logging
from flask import request
from flask_mysqldb import MySQL
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from passlib.hash import sha256_crypt
app = Flask(__name__)
# Config MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'localhost'
app.config['MYSQL_DB'] = 'localhost'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
# init MYSQL
mysql = MySQL(app)
@app.route('/')
def index():
return render_template('home.html')
@app.route('/home')
def home():
return render_template('home.html')
class RegisterForm(Form):
name = StringField('Name', [validators.Length(min=1, max=50)])
username = StringField('Username', [validators.Length(min=4, max=25)])
email = StringField('Email', [validators.Length(min=6, max=50)])
reason_for_joining = StringField('Why Do You Want To Join?', [
validators.Length(min=50, max=280)
])
password = PasswordField('Password', [validators.DataRequired(), validators.EqualTo(
'confirm', message='Passwords do not match.')])
confirm = PasswordField('Confirm Password')
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if request.method == 'POST' and form.validate():
name = form.name.data
email = form.email.data
username = form.username.data
reason_for_joining = form.reason_for_joining.data
password = sha256_crypt.encrypt(str(form.password.data))
# Create cursor
cur = mysql.connection.cursor()
# Run query
cur.execute("INSERT INTO users(name, email, username, reason_for_joining, password) VALUES(%s, %s, %s, %s)",
(name, email, username, reason_for_joining, password))
# Commit to DB
mysql.connection.commit()
# Close connection
cur.close()
# Message that shows if user registered successfully
flash("Your registration will be reviewed.", "success")
redirect(url_for("index"))
return render_template('register.html', form=form)
return render_template('register.html', form=form)
if __name__ == '__main__':
app.secret_key = "XXXXXXXXXXX"
app.run(debug=True)
这是我得到的回溯错误: https://imgur.com/psKFYbU
答案 0 :(得分:0)
如果遇到错误,例如错误1044(42000):尝试创建数据库时,拒绝用户'your_name'@'localhost'对数据库'menagerie'的访问,这意味着您的用户帐户没有必要的访问权限这样做的特权。与管理员讨论此问题,或参阅第6.2节“Access Control and Account Management”。
另请参阅this dock