flask简单示例:学生信息添加展示

项目地址:https://github.com/snjl/python.flask.student_item.git

使用的是flask-sqlalchemy,需要使用pip安装然后导入

1
from flask_sqlalchemy import SQLAlchemy

前置

第1步 - 安装Flask-SQLAlchemy扩展。

1
2

pip install flask-sqlalchemy

Shell第2步 - 需要从该模块导入SQLAlchemy类。

1
from flask_sqlalchemy import SQLAlchemy

Python第3步 - 现在创建一个Flask应用程序对象并为要使用的数据库设置URI。

1
2
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'

Python第4步 - 然后用应用程序对象作为参数创建一个SQLAlchemy类的对象。 该对象包含ORM操作的辅助函数。 它还提供了一个使用其声明用户定义模型的父级模型类。 在下面的代码片段中,创建了一个学生模型。

1
2
3
4
5
6
7
8
9
10
11
12
13
db = SQLAlchemy(app)
class students(db.Model):
id = db.Column('student_id', db.Integer, primary_key = True)
name = db.Column(db.String(100))
city = db.Column(db.String(50))
addr = db.Column(db.String(200))
pin = db.Column(db.String(10))

def __init__(self, name, city, addr,pin):
self.name = name
self.city = city
self.addr = addr
self.pin = pin

Python第5步 - 要创建/使用URI中提到的数据库,请运行create_all()方法。db.create_all()

1
db.create_all()

控制层与显示层

SQLAlchemy的Session对象管理ORM对象的所有持久性操作。以下会话方法执行CRUD操作

  • db.session.add(模型对象)将一条记录插入到映射表中
  • db.session.delete(模型对象)从表中删除记录
  • model.query.all()从表中检索所有记录(对应于SELECT查询)

可以使用filter属性将筛选器应用于检索到的记录集。

例如,要在students表中检索city =’Haikou’的记录,请使用以下语句

1
Students.query.filter_by(city = 'Haikou').all()

了这么多的背景知识,现在我们将为我们的应用程序提供视图函数来添加学生数据。应用程序的入口点是绑定到URL => ‘/‘的show_all()函数。学生的记录集作为参数发送给HTML模板。 模板中的服务器端代码以HTML表格形式呈现记录。

1
2
3
@app.route('/')
def show_all():
return render_template('show_all.html', students = students.query.all() )

Python模板的HTML脚本(show_all.html)就像这样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask示例</title>
</head>
<body>

<h3>
<a href = "{{ url_for('show_all') }}">学生列表 - Flask
SQLAlchemy示例</a>
</h3>

<hr/>
{%- for message in get_flashed_messages() %}
{{ message }}
{%- endfor %}

<h3>学生 (<a href = "{{ url_for('new') }}">添加
</a>)</h3>

<table>
<thead>
<tr>
<th>姓名</th>
<th>城市</th>
<th>地址</th>
<th>Pin</th>
</tr>
</thead>

<tbody>
{% for student in students %}
<tr>
<td>{{ student.name }}</td>
<td>{{ student.city }}</td>
<td>{{ student.addr }}</td>
<td>{{ student.pin }}</td>
</tr>
{% endfor %}
</tbody>
</table>

</body>
</html>

此处的get_flashed_messages是获取后台传输过来的信息。
HTML上面的页面包含一个指向URL:/new 映射new()函数的超链接。点击后,它会打开一个学生信息表单。 数据在POST方法中发布到相同的URL。模板文件:new.html 的代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Flask示例</title>
</head>
<body>
<h3>学生信息 - Flask SQLAlchemy示例</h3>
<hr/>

{%- for category, message in get_flashed_messages(with_categories = true) %}
<div class = "alert alert-danger">
{{ message }}
</div>
{%- endfor %}

<form action = "{{ request.path }}" method = "post">
<label for = "name">姓名</label><br>
<input type = "text" name = "name" placeholder = "Name" /><br>
<label for = "email">城市</label><br>
<input type = "text" name = "city" placeholder = "city" /><br>
<label for = "addr">地址</label><br>
<textarea name = "addr" placeholder = "addr"></textarea> <br>
<label for = "PIN">城市</label><br>
<input type = "text" name = "pin" placeholder = "pin" /><br>
<input type = "submit" value = "提交" />
</form>

</body>
</html>

HTML当检测到http方法为POST时,表单数据将插入到students表中,并且应用程序返回到显示数据的主页。

1
@app.route('/new', methods = ['GET', 'POST'])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def new():
if request.method == 'POST':
if not request.form['name'] or not request.form['city'] or not request.form['addr']:
flash('Please enter all the fields', 'error')
else:
student = students(request.form['name'], request.form['city'],
request.form['addr'], request.form['pin'])

db.session.add(student)
db.session.commit()

flash('Record was successfully added')
return redirect(url_for('show_all'))
return render_template('new.html')

Python下面给出的是完整的应用程序代码(app.py)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.sqlite3'
app.config['SECRET_KEY'] = "random string"

db = SQLAlchemy(app)

class students(db.Model):
id = db.Column('student_id', db.Integer, primary_key = True)
name = db.Column(db.String(100))
city = db.Column(db.String(50))
addr = db.Column(db.String(200))
pin = db.Column(db.String(10))

def __init__(self, name, city, addr,pin):
self.name = name
self.city = city
self.addr = addr
self.pin = pin

@app.route('/')
def show_all():
return render_template('show_all.html', students = students.query.all() )

@app.route('/new', methods = ['GET', 'POST'])
def new():
if request.method == 'POST':
if not request.form['name'] or not request.form['city'] or not request.form['addr']:
flash('Please enter all the fields', 'error')
else:
student = students(request.form['name'], request.form['city'],request.form['addr'], request.form['pin'])
print(student)
db.session.add(student)
db.session.commit()
flash('Record was successfully added')
return redirect(url_for('show_all'))
return render_template('new.html')

if __name__ == '__main__':
db.create_all()
app.run(debug = True)

flask-SQLAlchemy和SQLAlchemy使用区别

使用前者,需要配置在app里:

1
2
3
4
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:123456@localhost:3306/test'
app.config['SECRET_KEY'] = "random string"
db = SQLAlchemy(app)

而且使用的字段,是调用的db,如下所示:

1
2
3
4
5
6
class students(db.Model):
id = db.Column('student_id', db.Integer, primary_key=True)
name = db.Column(db.String(100))
city = db.Column(db.String(50))
addr = db.Column(db.String(200))
pin = db.Column(db.String(10))

使用后者,使用engine配置:

1
2
3
4
5
6
# 初始化数据库连接:
engine = create_engine('mysql+mysqlconnector://root:snjlSHU@139.224.113.131:3306/stock_test')
# 创建DBSession类型:
DBSession = sessionmaker(bind=engine)

app = Flask(__name__)

使用字段,用的是SQLAlchemy的包:

1
2
3
4
5
6
7
8
9
10
from sqlalchemy import Column, String, create_engine, Integer

# Address对象:
class Address(Base):
# 表的名字:
__tablename__ = 'address'
# 表的结构:
id = Column(Integer, primary_key=True)
address = Column(String(20))
status = Column(Integer)

-------------本文结束 感谢您的阅读-------------