1.文件结构:
2.最后实验效果:
登录成功之后的界面: 管理员登录成功之后同样显示成功界面:
3.主文件:main.py:
import os
from sqlalchemy import and_
from flask_wtf import FlaskForm
from flask_wtf.csrf import CSRFProtect
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from wtforms.validators import DataRequired,EqualTo,Length
from wtforms import StringField,SubmitField,PasswordField,TelField
from sqlalchemy import String,Integer,Column,create_engine,ForeignKey
from flask import Flask,flash,render_template,redirect,request,url_for,abort,jsonify
app=Flask(__name__)
app.secret_key='UserRoles'
csrf=CSRFProtect()
csrf.init_app(app)
class Config:
"""相关配置"""
SQLALCHEMY_DATABASE_URI='mysql+pymysql://root:root@127.0.0.1:3306/flaskdb'
SQLALCHEMY_TRACK_MODIFICATIONS=True
WTF_CSRF_CHECK_DEFAULT = False
app.config.from_object(Config)
mysql=SQLAlchemy(app)
#用户类表单
class UserForm(FlaskForm):
id=StringField(label='账号: ',validators=[DataRequired(),Length(min=1,max=8)])
name=StringField(label='用户名: ',validators=[DataRequired(),Length(min=6,max=16)])
password=PasswordField(label='密码: ',validators=[DataRequired(),Length(min=6,max=12)])
password_2=PasswordField(label='确认密码: ',validators=[DataRequired(),Length(min=6,max=8),EqualTo('password')])
role_id = StringField(label='role_id: ', validators=[DataRequired(), Length(1,3)])
submit=SubmitField(label='提交')
#管理员类表单
class RoleForm(FlaskForm):
id = StringField(label='账号: ', validators=[DataRequired(), Length(min=1, max=8)])
name = StringField(label='用户名: ', validators=[DataRequired(), Length(min=6, max=16)])
submit = SubmitField(label='提交')
class Role(mysql.Model):
__tablename='role'
id=Column(Integer,primary_key=True)
name=Column(String(32),unique=True)
#一对多的关联
user=relationship('User',backref='role')
#自定义输出的方式
def __repr__(self):
return '<Role: %s:%s>' % (self.id,self.name)
class User(mysql.Model):
__tablename='user'
#默认设置自增长
id=Column(Integer,primary_key=True)
name=Column(String(128),unique=True)
password=Column(String(128),unique=True)
#表关系
role_id=Column(Integer,ForeignKey('role.id'))
#自定义输出的方式
def __repr__(self):
return '<User: %s:%s:%s>'%(self.id,self.name,self.password)
#添加用户
@app.route('/<int:id>/<string:name>/<string:password>/<int:role_id>',methods=['POST','GET'])
def Insert_Users(id,name,password,role_id):
data=User.query.filter(and_(User.id==id,User.name==name,User.password==password)).all()
if data==[]:
#如果数据库不存在此用户就创建用户
new_user=User(id=id,name=name,password=password,role_id=role_id)
#添加和提交用户
mysql.session.add(new_user)
mysql.session.commit()
mysql.session.close()
return jsonify('Add The User Successed!')
else:
return render_template('login_success.html')
#天剑管理员
@app.route('/<int:id>/<string:name>',methods=['POST','GET'])
def Insert_Roles(id,name):
data=User.query.filter(and_(User.id==id,User.name==name)).all()
if data==[]:
#如果数据库不存在此用户就创建用户
new_role=Role(id=id,name=name)
#添加和提交用户
mysql.session.add(new_role)
mysql.session.commit()
mysql.session.close()
return jsonify('Add The Role Successed!')
else:
return render_template('login_success.html')
@app.route('/user',methods=['POST','GET'])
def Turn_User():
userform=UserForm()
if request.method=='POST':
if userform.validate_on_submit():
id=userform.id.data
name=userform.name.data
password=userform.password.data
role_id=userform.role_id.data
return redirect(url_for('Insert_Users', id=id, name=name, password=password,role_id=role_id))
return render_template('Users.html',userform=userform)
@app.route('/index',methods=['POST','GET'])
def App_User():
if request.method=='POST':
return redirect(url_for('Turn_User'))
return render_template('base.html')
@app.route('/role',methods=['POST','GET'])
def Turn_Role():
roleform=RoleForm()
if request.method=='POST':
if roleform.validate_on_submit():
id=roleform.id.data
name=roleform.name.data
return redirect(url_for('Insert_Roles', id=id, name=name))
return render_template('Roles.html',roleform=roleform)
@app.route('/login',methods=['POST','GET'])
def App_Role():
if request.method=='POST':
return redirect(url_for('Turn_Role'))
return render_template('base.html')
if __name__ == '__main__':
print('Pycharm')
#清除所有表,避免创建重复的表
# mysql.drop_all()
#创建所有的表
mysql.init_app(app)
mysql.create_all()
app.run(debug=True)
# #创建对象,插入数据
# role1=Role(id=1,name='admin')
# role2=Role(id=3,name='moster')
# #session记录到对象任务中
# mysql.session.add(role1)
# mysql.session.add(role2)
# #提交任务
# mysql.session.commit()
# # mysql.session.close()
# user1=User(id=1,name='tom',password='123',role_id=role1.id)
# user2 = User(id=2, name='zom', password='1234', role_id=role1.id)
# user3 = User(id=3, name='qom', password='1235', role_id=role2.id)
# mysql.session.add_all([user1,user2,user3])
# mysql.session.commit()
# data=User.query.filter(User.name=='yom').all()
# print(data)
# if data==[]:
# print('空列表')
# #查询之间的关联
# print('role1.user1: {}'.format(role1.user))
# print('role2.user1: {}'.format(role2.user))
# print('user1.role: {}'.format(user1.role))
# print('user2.role: {}'.format(user2.role))
# print('user3.role: {}'.format(user3.role))
#E:\conda_3\PyCharm\Flask\Flask数据库\test.py
4.前端文件:Users.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<style>
div {
width:300px;
height:200px;
margin:auto;
margin-top:200px;
font-size:15px;
font-weight:700;
border:2px solid #000000;
background:#FFFFFF;
}
div form input {
margin-top:10px;
}
.btn{
margin-left:100px;
cursor:pointer;
}
</style>
</head>
<body>
<div>
<form action="http://127.0.0.1:5000/user" method="POST">
<!-- <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />-->
{{userform.csrf_token()}}<br>
{{userform.id.label}}{{userform.id}}<br>
{{userform.name.label}}{{userform.name}}<br>
{{userform.password.label}}{{userform.password}}<br>
{{userform.password_2.label}}{{userform.password_2}}<br>
{{userform.role_id.label}}{{userform.role_id}}<br>
<!-- {{userform.submit}}-->
<input class="btn" type="submit" name="submit" value="提交"><br>
</form>
</div>
</body>
</html>
5.前端文件:Roles.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<style>
div {
width:250px;
height:150px;
margin:auto;
margin-top:200px;
font-size:15px;
font-weight:700;
border:2px solid #000000;
background:#FFFFFF;
}
div form input {
margin-top:10px;
}
.btn{
margin-left:100px;
cursor:pointer;
}
</style>
</head>
<body>
<div>
<form action="http://127.0.0.1:5000/role" method="POST">
<!-- <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />-->
{{roleform.csrf_token()}}<br>
{{roleform.id.label}}{{roleform.id}}<br>
{{roleform.name.label}}{{roleform.name}}<br>
<input class="btn" type="submit" name="submit" value="提交"><br>
</form>
</div>
</body>
</html>
6.前端文件:base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User/Moster</title>
<style>
.id {
width:500px;
height:90px;
margin:auto;
margin-top:100px;
color:#000000;
background:#FFFFFF;
border:2px solid #000000;
font-size:15px;
text-align:center;
}
.form {
width:200px;
height:100px;
margin:auto;
margin-top:50px;
color:#000000;
background:#FFFFFF;
border:2px solid #000000;
font-size:15px;
text-align:center;
}
.form {
position:relative;
}
.form1{
position:absolute;
margin-top:30px;
margin-left:30px;
}
.form2{
position:absolute;
margin-top:30px;
margin-left:119px;
}
</style>
</head>
<body>
<div class="id">
<h1>选择管理员/用户身份</h1>
</div>
<div class="form">
<form class="form1" action="http://127.0.0.1:5000/user" method="POST">
<input type="submit" name="submit" value="用户">
</form>
<form class="form2" action="http://127.0.0.1:5000/role" method="POST">
<input type="submit" name="submit" value="管理员">
</form>
</div>
</body>
</html>
<!--#E:\conda_3\PyCharm\Flask\Flask数据库\提交\templates-->
7.前端文件:login_success.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login_Success</title>
<style>
img {
width:1500px;
height:700px;
}
</style>
</head>
<body>
<img src="http://127.0.0.1:5000/static/login_success.png" title="登录成功" alt="登录成功">
</body>
</html>
|