注意:要想在python脚本中访问mysql,必须不能使用mysql默认的密码,必须要手动修改下数据库的密码:
方法:
- 进入到mysql中:
mysql -u root -p
回车
- 修改mysql密码步骤:
(注意:一定要use mysql;)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| myflaskapp |
| mysql |
| performance_schema |
| test |
+--------------------+
5 rows in set (0.01 sec)
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> update user set password=password('test123') where user='root';
Query OK, 3 rows affected (0.06 sec)
Rows matched: 3 Changed: 3 Warnings: 0
3.配置数据库代码:
# from app import views
app = Flask(__name__)
# Config MySQL https://flask-mysqldb.readthedocs.io/en/latest/
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'test123'
app.config['MYSQL_DB'] = 'myflaskapp'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
# init MYSQL
mysql = MySQL(app)
'''
4.启动服务器
if name=='main':
app.secret_key = 'test123'
app.run(debug=True)
5. 此时因为也已经写好了连接mysql的代码:
User Register
@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
password = sha256_crypt.encrypt(str(form.password.data))
# Create cursor
cur = mysql.connection.cursor()
# Execute query
cur.execute("INSERT INTO users(name, email, username, password) VALUES(%s, %s, %s, %s)", (name, email, username, password))
# Commit to DB
mysql.connection.commit()
# Close connection
cur.close()
flash('You are now registered and can log in', 'success')
return redirect(url_for('index'))
return render_template('register.html', form=form)
6. 在页面上点击Register,会弹出来register.html页面,然后在页面行填写合适的信息后,点击submmit,mysql数据库中就会出现一条数据。
网友评论