介绍
使用 Flask 和 MySQL 的 Python Web 应用程序 CRUD 示例教程将向您展示基本的 CRUD 操作。
CRUD 表示创建、读取、更新和删除操作。在下面的示例中,我将创建新记录、读取现有记录、更新现有记录并删除现有记录。
我将使用 MySQL 数据库作为执行此类基本 CRUD 操作的永久存储。我将使用 Flask 模块来处理来自最终用户或客户端的请求和响应,并且该模块将用作 Python 的 Web 应用程序框架。
默认情况下,Flask 模块不随 Python 安装一起提供,您必须在 Windows 环境中从 cmd 提示符(以管理员模式打开)使用命令pip install flask单独安装它。
准备工作区
准备工作区是您可以做的第一件事,以确保您有一个良好的开端。第一步是检查您的工作目录。
当您在 Python 终端中工作时,您需要首先导航到您的文件所在的目录,然后启动 Python,即您必须确保您的文件位于您要工作的目录中。
为此,使用 Flask 和 MySQL 的 Python Web 应用程序 CRUD 示例,您需要模块,例如table、flask、mysql。模块表需要在HTML视图上以表格格式显示数据,模块flask作为Web框架工作,需要mysql模块与MySQL数据库建立连接并使用Python编程语言查询数据库。
如果您发现任何所需的模块不存在,那么您需要安装它。您可以在下面的屏幕截图中找到我如何安装以下必需的模块 – table 和 mysql。
这是 MySQL 数据库表 - tbl_user具有以下结构并插入数据:
-- 导出 test 的数据库结构
CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `test`;
-- 导出 表 test.tbl_user 结构
CREATE TABLE IF NOT EXISTS `tbl_user` (
`user_id` bigint NOT NULL AUTO_INCREMENT,
`user_name` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`user_email` varchar(45) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`user_password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- 正在导出表 test.tbl_user 的数据:~1 rows (大约)
/*!40000 ALTER TABLE `tbl_user` DISABLE KEYS */;
INSERT INTO `tbl_user` (`user_id`, `user_name`, `user_email`, `user_password`) VALUES
(3, '姓名', 'admin@admin.com', 'pbkdf2:sha256:260000$sEf5rwGtCt7b54m6$cb88423151075b285c1f6201dfa83f2e4bb5ece154fa05b763e9203c6c8cb2e0');
CRUD 示例
在下图中,您会看到我打开了一个 cmd 提示符并导航到我必须创建 Python 脚本以使用 Flask MySQL 实现 Python Web 应用程序 CRUD 示例的目录。
请按照以下步骤使用 Flask MySQL 实现 Python Web 应用程序 CRUD 示例:
1.首先创建目录。顶层目录或项目根目录,如上图准备工作区部分所示。然后在这个目录中创建python-flask-mysql-crud目录。在这个python-flask-mysql-crud目录中创建templates目录。templates目录将包含所有 html 模板文件,例如您需要多个 HTML 文件来创建 CRUD 操作。
2.创建下面的app.py脚本(py 是表示 Python 脚本的扩展名),我在其中导入了Flask模块。这个文件应该在python-flask-mysql-crud目录下创建。注意我是如何创建烧瓶实例的。我已经配置了一个密钥,这是您的应用程序会话所必需的。
from flask import Flask
app = Flask(__name__)
app.secret_key = "secret key"
3. 我在python-flask-mysql-crud下创建了以下Python 脚本db_config.py 来设置 MySQL 数据库配置以连接到数据库。我需要使用flask模块配置数据库连接,这就是为什么我导入了app模块并使用flask模块设置了MySQL配置。
from app import app
from flaskext.mysql import MySQL
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'test'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)
4.接下来你需要在python-flask-mysql-crud目录下的main.py脚本,它将定义执行 CRUD 操作的所有 URI 或 Action 路径。它还将连接到 MySQL 数据库服务器并查询数据库以进行读取、插入、更新和删除。
该脚本是使用 Flask 和 MySQL 的 Python Web 应用程序 CRUD 示例的完美实例。在此脚本中,我通过用户交互执行 CRUD 操作,显示所有记录,添加新记录,更新现有记录,并根据需要从表格数据中删除记录。
我首先将所需的模块导入到脚本中。然后我定义端点/new_user以显示用户将添加新记录的视图。接下来我需要验证用户输入数据并将这些输入数据保存到 MySQL 数据库中,因此我定义了另一个端点 /add。我使用 http 方法 GET 显示视图,使用 POST 方法将数据发送到服务器端。如果不指定 http 方法,默认情况下 http 方法是 GET。我使用flask 中的render_template函数来显示视图。最初当没有用户信息时,您将不会在主页上看到任何用户信息。
您可以从主页上显示的添加用户链接添加新用户,您将看到主页上显示数据。我不想将密码存储为纯文本,所以我使用generate_password_hash()函数来屏蔽密码。
接下来,我使用根端点 /在视图users.html 中显示 MySQL 数据库中的所有记录。请注意,当我渲染视图时,我还将表数据作为第二个参数发送给render_template函数。另请注意,我已将 MySQL 连接配置为 pymysql.cursors.DictCursor以获取行作为数据字典,以便我将每个列值检索为键/值对(列名/列值),这将帮助您以表格形式显示数据使用flask' table API 格式化。
然后我显示编辑表单,用户在单击HTML 表数据中的编辑链接时更新他的信息。我定义了 /update 端点以将更新的信息保存到 MySQL 数据库中。更新后,我重定向到主页,其中显示了 HTML 表中的用户列表。
接下来我定义删除端点,用户在点击HTML 表格数据中的删除链接时删除他的信息。最后重定向到主页。
当我添加、更新或删除用户时,我会重定向到主页并向用户显示相应的消息。
import pymysql
from app import app
from tables import Results
from db_config import mysql
from flask import flash, render_template, request, redirect
from werkzeug.security import generate_password_hash, check_password_hash
@app.route('/new_user')
def add_user_view():
return render_template('add.html')
@app.route('/add', methods=['POST'])
def add_user():
conn = None
cursor = None
try:
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
# validate the received values
if _name and _email and _password and request.method == 'POST':
#do not save password as a plain text
_hashed_password = generate_password_hash(_password)
# save edits
sql = "INSERT INTO tbl_user(user_name, user_email, user_password) VALUES(%s, %s, %s)"
data = (_name, _email, _hashed_password,)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
flash('User added successfully!')
return redirect('/')
else:
return 'Error while adding user'
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/')
def users():
conn = None
cursor = None
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT * FROM tbl_user")
rows = cursor.fetchall()
table = Results(rows)
table.border = True
return render_template('users.html', table=table)
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/edit/<int:id>')
def edit_view(id):
conn = None
cursor = None
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT * FROM tbl_user WHERE user_id=%s", id)
row = cursor.fetchone()
if row:
return render_template('edit.html', row=row)
else:
return 'Error loading #{id}'.format(id=id)
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/update', methods=['POST'])
def update_user():
conn = None
cursor = None
try:
_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']
_id = request.form['id']
# validate the received values
if _name and _email and _password and _id and request.method == 'POST':
#do not save password as a plain text
_hashed_password = generate_password_hash(_password)
print(_hashed_password)
# save edits
sql = "UPDATE tbl_user SET user_name=%s, user_email=%s, user_password=%s WHERE user_id=%s"
data = (_name, _email, _hashed_password, _id,)
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
flash('User updated successfully!')
return redirect('/')
else:
return 'Error while updating user'
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/delete/<int:id>')
def delete_user(id):
conn = None
cursor = None
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("DELETE FROM tbl_user WHERE user_id=%s", (id,))
conn.commit()
flash('User deleted successfully!')
return redirect('/')
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == "__main__":
app.run()
5.现在在python-flask-mysql-crud 目录下创建tables.py脚本,在主页的HTML模板文件中以表格格式显示用户数据列表。请注意我如何使用Flask模块中的LinkCol添加两个链接来更新和删除表数据中的记录。
在下面的脚本中,我声明了一个类 Results,其中赋值的左侧表示表列名称,赋值的右侧表示我想在 HTML 表中作为标题显示的内容。我不想显示user_id和user_password,这就是我使用show=False作为第二个参数的原因。
我在最右边的列中添加了两个更新和删除链接,用于更新和删除现有用户。
from flask_table import Table, Col, LinkCol
class Results(Table):
user_id = Col('Id', show=False)
user_name = Col('Name')
user_email = Col('Email')
user_password = Col('Password', show=False)
edit = LinkCol('Edit', 'edit_view', url_kwargs=dict(id='user_id'))
delete = LinkCol('Delete', 'delete_user', url_kwargs=dict(id='user_id'))
6.现在创建users.html文件并将其放在templates目录下。请注意我如何使用 Flask EL 表达式来使用变量将数据显示到 HTML 文件中。
我添加了一个链接,用户可以使用该链接添加新用户。
我还会检查任何成功或错误消息并显示它们。我显示来自 flash 范围的消息,为此我需要会话,而对于会话,我需要密钥,这就是我在app.py脚本中配置密钥的原因。
最后我将用户数据显示到 HTML 表格中。
<doctype html>
<title>List of users - Python Flask MySQL CRUD</title>
<p><a href="{{ url_for('.add_user_view') }}"> Add User </a></p>
<p>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</p>
{{ table }}
7.使用以下代码创建下面的add.html文件并将其放在templates目录下。这里的动作定义了在main.py脚本中添加的端点,当用户单击表单上的提交按钮时将调用它。
<doctype html>
<title>Add User - Python Flask MySQL CRUD</title>
<h2>Add User</h2>
<form method="post" action="/add">
<dl>
<p>
<input name="inputName" value="" type="text" placeholder="Name" autocomplete="off" required>
</p>
<p>
<input name="inputEmail" value="" type="text" placeholder="Email" autocomplete="off" required>
</p>
<p>
<input name="inputPassword" value="" type="password" placeholder="Password" autocomplete="off" required>
</p>
</dl>
<p>
<input type="submit" value="Submit">
</p>
</form>
8.使用以下代码创建下面的edit.html文件并将其放在templates目录下。请注意当用户想要更新现有信息时我如何显示 MySQL 数据库中的数据。它将帮助他们知道数据库中已经存在哪些数据,如果用户不想更新所有信息,那么他/她可以只更新他/她需要的信息。
<doctype html>
<title>Edit User - Python Flask MySQL CRUD</title>
<h2>Edit User</h2>
<form method="post" action="/update">
<dl>
<p>
<input name="inputName" value="{{ row['user_name'] }}" type="text" placeholder="Name" autocomplete="off" required>
</p>
<p>
<input name="inputEmail" value="{{ row['user_email'] }}" type="text" placeholder="Email" autocomplete="off" required>
</p>
<p>
<input name="inputPassword" value="" type="password" placeholder="Password" autocomplete="off" required>
</p>
</dl>
<p>
<input name="id" value="{{ row['user_id'] }}" type="hidden">
<input type="submit" value="Submit">
</p>
</form>
您不需要创建任何模板视图来删除用户信息,因为我使用端点操作删除并重定向到主页。
测试应用程序
现在导航到python-flask-mysql-crud目录并执行命令python main.py,您的服务器将在默认端口5000上启动。如果要更改端口,则可以将行app.run()更改 为 app.run(port=50001),其中5001是新端口。
现在,当您在浏览器中打开 URL http://localhost:5000 时,您应该看到类似于下图的内容:
现在您可以添加、编辑、删除用户。就这样。希望您理解使用 Flask 和 MySQL 的 Python Web 应用程序 CRUD 示例。