上次发的一篇文章,有很多朋友私信我要后面的部分,那咱们就今天来一起学习一下吧,因为我的数据库这门课选中的课题是学生管理系统,所以今天就以这个课题为例子,从0到1去实现一个管理系统。数据库设计部分我会专门出一个博客的,敬请期待吧~~~
这里我就不细讲了,感兴趣的可以看下面这个博客
(5条消息) python Web开发 flask轻量级Web框架实战项目--实现功能--账号密码登录界面(连接数据库Mysql)_flask web开发实战_吴永畅的博客-CSDN博客
这次有点不同的是 需要把登录功能封装成一个login函数,然后我为了省事呢就把数据库连接放在外部。
# 初始化
app = flask.Flask(__name__)
# 使用pymysql.connect方法连接本地mysql数据库
db = pymysql.connect(host='localhost', port=3306, user='root',
password='root', database='student', charset='utf8')
# 操作数据库,获取db下的cursor对象
cursor = db.cursor()
# 存储登陆用户的名字用户其它网页的显示
users = []
@app.route("/", methods=["GET", "POST"])
def login():
# 增加会话保护机制(未登陆前login的session值为空)
flask.session['login'] = ''
if flask.request.method == 'POST':
user = flask.request.values.get("user", "")
pwd = flask.request.values.get("pwd", "")
# 防止sql注入,如:select * from admins where admin_name = '' or 1=1 -- and password='';
# 利用正则表达式进行输入判断
result_user = re.search(r"^[a-zA-Z]+$", user) # 限制用户名为全字母
result_pwd = re.search(r"^[a-zA-Z\d]+$", pwd) # 限制密码为 字母和数字的组合
if result_user != None and result_pwd != None: # 验证通过
msg = '用户名或密码错误'
# 正则验证通过后与数据库中数据进行比较
# sql = "select * from sys_user where username='" + \
# user + "' and password='" + pwd + "';"
sql1 = "select * from admins where admin_name='" + \
user + " ' and admin_password='" + pwd + "';"
# cursor.execute(sql)
cursor.execute(sql1)
result = cursor.fetchone()
# 匹配得到结果即管理员数据库中存在此管理员
if result:
# 登陆成功
flask.session['login'] = 'OK'
users.append(user) # 存储登陆成功的用户名用于显示
return flask.redirect(flask.url_for('student'))
# return flask.redirect('/file')
else: # 输入验证不通过
msg = '非法输入'
else:
msg = ''
user = ''
return flask.render_template('login.html', msg=msg, user=user)
这里我们可以录入的信息是学生学号、学生姓名、班级、性别等。
首先用户登录成功之后,跳转到学生信息录入界面,系统需要显示出学生表信息。
if flask.request.method == 'GET':
sql_list = "select * from students_infos"
cursor.execute(sql_list)
results = cursor.fetchall()
if flask.request.method == 'POST':
# 获取输入的学生信息
student_id = flask.request.values.get("student_id", "")
student_class = flask.request.values.get("student_class", "")
student_name = flask.request.values.get("student_name", "")
student_sex = flask.request.values.get("student_sex")
print(student_id, student_class, student_name, student_sex)
插入数据只需要写入sql语句,并且执行该语句就可以,异常处理是个人习惯,在插入失败是系统给予提示,这里的sql语句都是写活的,真正的数据是来源于页面输入,其实就是调用了sql语句插入成功后,学生表就会自动同步显示在前端页面上。
@app.route('/student', methods=['GET', "POST"])
def student():
# login session值
if flask.session.get("login", "") == '':
# 用户没有登陆
print('用户还没有登陆!即将重定向!')
return flask.redirect('/')
insert_result = ''
# 当用户登陆有存储信息时显示用户名,否则为空
if users:
for user in users:
user_info = user
else:
user_info = ''
# 获取显示数据信息
if flask.request.method == 'GET':
sql_list = "select * from students_infos"
cursor.execute(sql_list)
results = cursor.fetchall()
if flask.request.method == 'POST':
# 获取输入的学生信息
student_id = flask.request.values.get("student_id", "")
student_class = flask.request.values.get("student_class", "")
student_name = flask.request.values.get("student_name", "")
student_sex = flask.request.values.get("student_sex")
print(student_id, student_class, student_name, student_sex)
try:
# 信息存入数据库
sql = "create table if not exists students_infos(student_id varchar(10) primary key,student_class varchar(100),student_name varchar(32),student_sex VARCHAR(4));"
cursor.execute(sql)
sql_1 = "insert into students_infos(student_id, student_class, student_name, student_sex )values(%s,%s,%s,%s)"
cursor.execute(sql_1, (student_id, student_class, student_name, student_sex))
insert_result = "成功存入一条学生信息"
print(insert_result)
except Exception as err:
print(err)
insert_result = "学生信息插入失败"
print(insert_result)
pass
db.commit()
# POST方法时显示数据
sql_list = "select * from students_infos"
cursor.execute(sql_list)
results = cursor.fetchall()
return flask.render_template('student.html', insert_result=insert_result, user_info=user_info, results=results)
学生成绩管理系统
如图所示 吴永畅现在的班级是软件工程212 现在要修改为软件工程213 那么就在下拉框里选择修改学生班级,然后把学生学号和姓名填入,在学生班级那里填入修改后的班级。
原理都是一样的,执行对应的sql语句即可,这里就不赘述了。
@app.route('/updata_student', methods=['GET', "POST"])
def updata_student():
# login session值
if flask.session.get("login", "") == '':
# 用户没有登陆
print('用户还没有登陆!即将重定向!')
return flask.redirect('/')
insert_result = ''
# 获取显示学生数据信息(GET方法的时候显示数据)
if flask.request.method == 'GET':
sql_list = "select * from students_infos"
cursor.execute(sql_list)
results = cursor.fetchall()
# 当用户登陆有存储信息时显示用户名,否则为空
if users:
for user in users:
user_info = user
else:
user_info = ''
if flask.request.method == 'POST':
# 获取输入的学生信息
student_id = flask.request.values.get("student_id", "")
student_class = flask.request.values.get("student_class", "")
student_name = flask.request.values.get("student_name", "")
# student_sex = flask.request.values.get("student_sex", "")
student_id_result = re.search(r"^\d{8,}$", student_id) # 限制用户名为全字母
# 验证通过
if student_id_result != None: # 验证通过
# 获取下拉框的数据
select = flask.request.form.get('selected_one')
if select == '修改学生班级':
try:
sql = "update students_infos set student_class=%s where student_id=%s;"
cursor.execute(sql, (student_class, student_id))
insert_result = "学生" + student_id + "的班级修改成功!"
except Exception as err:
print(err)
insert_result = "修改学生班级失败!"
pass
db.commit()
if select == '修改学生姓名':
try:
sql = "update students_infos set student_name=%s where student_id=%s;"
cursor.execute(sql, (student_name, student_id))
insert_result = "学生" + student_name + "的姓名修改成功!"
except Exception as err:
print(err)
insert_result = "修改学生姓名失败!"
pass
db.commit()
if select == '删除学生':
try:
sql_delete = "delete from students_infos where student_id='" + student_id + "';"
cursor.execute(sql_delete)
insert_result = "成功删除学生" + student_id
except Exception as err:
print(err)
insert_result = "删除失败"
pass
db.commit()
else: # 输入验证不通过
insert_result = "输入的格式不符合要求!"
# POST方法时显示数据
sql_list = "select * from students_infos"
cursor.execute(sql_list)
results = cursor.fetchall()
return flask.render_template('updata_student.html', user_info=user_info, insert_result=insert_result,
results=results)
前端页面 updata_student.html
学生成绩管理系统
如下图查询学号为20212248的学生成绩
这里我们设计几种常见的查询方式,大家也可以自己添加。
@app.route('/grade_infos', methods=['GET', 'POST'])
def grade_infos():
# login session值
if flask.session.get("login", "") == '':
# 用户没有登陆
print('用户还没有登陆!即将重定向!')
return flask.redirect('/')
query_result = ''
results = ''
# 当用户登陆有存储信息时显示用户名,否则为空
if users:
for user in users:
user_info = user
else:
user_info = ''
# 获取下拉框的数据
if flask.request.method == 'POST':
select = flask.request.form.get('selected_one')
query = flask.request.values.get('query')
print(select, query)
# 判断不同输入对数据表进行不同的处理
if select == '学号':
try:
sql = "select * from grade_infos where student_id = %s; "
cursor.execute(sql, query)
results = cursor.fetchall()
if results:
query_result = '查询成功!'
else:
query_result = '查询失败!'
except Exception as err:
print(err)
pass
if select == '姓名':
try:
sql = "select * from grade_infos where student_id in(select student_id from students_infos where student_name=%s);"
cursor.execute(sql, query)
results = cursor.fetchall()
if results:
query_result = '查询成功!'
else:
query_result = '查询失败!'
except Exception as err:
print(err)
pass
if select == '课程名称':
try:
sql = "select * from grade_infos where student_class_id in(select student_class_id from students_infos where student_class_id=%s);"
cursor.execute(sql, query)
results = cursor.fetchall()
if results:
query_result = '查询成功!'
else:
query_result = '查询失败!'
except Exception as err:
print(err)
pass
if select == "所在班级":
try:
sql = "select * from grade_infos where student_class_id in(select student_class_id from students_infos where student_class=%s);"
cursor.execute(sql, query)
results = cursor.fetchall()
if results:
query_result = '查询成功!'
else:
query_result = '查询失败!'
except Exception as err:
print(err)
pass
return flask.render_template('grade_infos.html', query_result=query_result, user_info=user_info, results=results)
前端页面 grade_infos.html
学生成绩管理系统
因为实现原理都是相似的,所以我就不一个个去写了,就把增删查改功能各写一遍,剩下感兴趣的可以自己去尝试写下,要相信自己!总体来说还是一个值得初学者去练习的项目。