1. 程式人生 > >python學習筆記 day45 python實現使用者許可權管理

python學習筆記 day45 python實現使用者許可權管理

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()

 

 執行結果: