1. 需求
要求使用python实现某个用户登录成功后,查看自己所有的权限;
思路:创建权限表(都有哪些权限) 用户表(每个用户的用户名密码以及所拥有的权限 用户-权限关系表(存储用户和所拥有权限的对应关系)
2. 创建表
-- 创建权限表 create table authorization( id smallint not null auto_increment primary key, aid char(10) not null, name varchar(40) not null); desc authorization; show create table authorization; insert into authorization(aid,name) values("a00001","update_course"),("a00002","view_course"), ("a00003","uodate_teachers"),("a00004","view_teachers"),("a00005","update_students"),("a00006","view_teachers") select * from authorization; -- 创建用户表(三类用户,管理员,老师,学生) create table users( id smallint not null auto_increment primary key, uid char(10) not null, name varchar(40) not null); insert into users(uid,name) values("u00001","admin"),("u00002","teachers"),("u00003","students"); select * from users; -- 创建用户信息表(存储用户名,密码,以及对应的用户身份(管理员or 教师 or 学生) create table userinfo( id smallint not null auto_increment primary key, iid char(10) not null, name varchar(40) not null, password varchar(20) not null, uid char(10) not null -- 跟用户user表的uid关联(表明该用户属于哪一种角色,admin teacher students) ); insert into userinfo(iid,name,password,uid) values("i00001","xuanxuan","123","u00001"), ("i00002","eva","123","u00002"),("i00003","egon","123","u00002"),("i00004","xixi","123","u00003"),("i00005","haha","123","u00003"),("i00006","hehe","123","u00003"); select * from userinfo; -- 创建关系表(管理员,老师,学生分别拥有什么权限) create table relations( id smallint not null auto_increment primary key, uid char(10) not null, aid char(10) not null) insert into relations(uid,aid) values("u00001","a00001"),("u00001","a00002"),("u00001","a00003"), ("u00001","a00004"),("u00001","a00005"),("u00001","a00006"),("u00002","a00001"),("u00002","a00002"), ("u00002","a00006"),("u00003","a00002"); select * from relations;
运行结果:
3. 代码实现
import pymysql usm=input("username:") pwd=input("password:") conn=pymysql.connect(host="localhost",user="root",password="*****",database="db666") cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) sql="select * from userinfo where name=%s and password=%s" # 查看用户名密码是否正确,在userinfo表中就可以登录成功 cursor.execute(sql,[usm,pwd]) # cursor.execute()返回的是受影响的行数 result=cursor.fetchone() # 如果登录成功就会返回该用户的信息,才可以后续查看该用户拥有的权限 if result: print("恭喜您,登录成功") sql="select aid,name from authorization as t1 where t1.aid in(select aid from relations where uid=(select uid from userinfo where name=%s and password=%s))" cursor.execute(sql,[usm,pwd]) # 利用pymysql模块,执行sql语句,查看所登录用户具有的权限 result=cursor.fetchall() # select 查看需要cursor.fetchone()获取查看的信息(但是当增删改操作时需要提交 conn.commit()) print("你具有的权限为:",result) else: print("登录失败!") cursor.close() conn.close()
运行结果: