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()
運行結果: