• 01 上节回顾
  • 02 后台管理布局
  • 03 按钮权限控制的简单形式
  • 04 修改表结构
  • 05 重构数据结构
  • 06 限制权限颗粒度

01 上节回顾

1.1 项目的组织架构;

1.2 项目组件的版本说明;

  使用的是Django1.11.1与最新的Django有区别,请注意。另外Pycharm创建的Django项目一般都是最新的,2018版本Pycharm自带virtualenv环境,无需个人再次安装。如需执行Django版本,可在本机的Python解释器环境下,pip install django=="1.11.1",然后通过Pycharm创建Django项目的时候指定一下内置的Python解释器,见下图。

1.3 settings.py文件说明;

自行配置TEMPLATES中的DIRS;

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

settings.py

"""
Django settings for s9day82_rbac project. Generated by 'django-admin startproject' using Django 1.11.1. For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0s(th#!ewf^xik5n&bqkqqjadz#q*vt+!hq(kzk5*-!t6@^0^i' # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
'rbac.apps.RbacConfig',
] MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'rbac.service.rbac.ValidPermission',
]
from django.middleware.security import SecurityMiddleware ROOT_URLCONF = 's9day82_rbac.urls' TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
] WSGI_APPLICATION = 's9day82_rbac.wsgi.application' # Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} # Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
] # Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/'

1.4 urls.py;

"""s9day82_rbac URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^users/$', views.users),
url(r'^users/add', views.add_user),
url(r'^roles/', views.roles),
url(r'^login/', views.login),
]

1.5 views.py;

import re
from django.shortcuts import render, HttpResponse # Create your views here. from rbac.models import *
from rbac.service.permissions import * def users(request):
user_list = User.objects.all()
return render(request, "users.html", locals()) def add_user(request):
return HttpResponse("Add User......") def roles(request):
role_list = Role.objects.all()
return render(request, "roles.html......", locals()) def login(request):
if request.method == "POST":
user_obj = request.POST.get("user")
pwd = request.POST.get("pwd")
user = User.objects.filter(name=user_obj, pwd=pwd).first()
if user:
# #################在session中注册用户ID###########################;
request.session["user_id"] = user.pk
initial_session(user, request)
'''
此处的values()相当于:
temp = []#定义一个空列表;
for role in user.roles.all();#values属性,相当于循环该对象[<Role: 保洁>, <Role: 销售>]>
temp.append({
"title":role.title,
"permissions__url":role.permissions.all()
})
'''
return HttpResponse("登录成功!")
return render(request, "login.html", locals())

1.6 models.py;

from django.db import models

# Create your models here.

class User(models.Model):
name = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
roles = models.ManyToManyField(to="Role") def __str__(self):
return self.name class Role(models.Model):
title = models.CharField(max_length=32)
permissions = models.ManyToManyField(to="Permission") def __str__(self):
return self.title class Permission(models.Model):
title = models.CharField(max_length=32)
url = models.CharField(max_length=32) def __str__(self):
return self.title

1.7 templates模板文件;

login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h4>登录页面</h4> <form action="" method="post">
{% csrf_token %}
用户名:<input type="text" name="user">
密码:<input type="password" name="pwd">
<input type="submit">
</form>
</body>
</html>

roles.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Users</title>
</head>
<body>
<h4>角色列表</h4>
<ul>
{% for role in role_list %}
<p>{{ role }}</p>
{% endfor %} </ul>
</body>
</html>

1.8 permissions.py

def initial_session(user, request):
# #################在session注册权限列表###########################;
# 查询当前登录用户的所有角色;
ret = user.roles.all()
print("ret", ret) # <QuerySet [<Role: 保洁>, <Role: 销售>]> # 查询当前用户的所有权限;
permissions = user.roles.all().values(
"permissions__url").distinct() # ret_role <QuerySet [{'permissions__url': '/users/'},
# {'permissions__url': '/users/add'}]> # 进行数据的处理,生成列表;
permission_list = []
for item in permissions:
permission_list.append(item["permissions__url"])
print("permission_list", permission_list) # permission_list ['/users/', '/users/add'] request.session["permission_list"] = permission_list

02 后台管理布局

login.html;

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h4>登录页面</h4> <form action="" method="post">
{% csrf_token %}
用户名:<input type="text" name="user">
密码:<input type="password" name="pwd">
<input type="submit">
</form>
</body>
</html>

base.html;

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
.header {
width: 100%;
height: 60px;
background-color: #336699; } .menu {
background-color: bisque;
position: fixed;
top: 60px;
bottom: 0;
left: 0;
width: 200px;
} .content {
position: fixed;
top: 60px;
bottom: 0;
right: 0;
left: 200px;
overflow: auto;
padding: 30px;
}
</style>
</head>
<body>
<div class="header">
<p>{{ user.name }}</p>
</div>
<div class="contain"> <div class="menu">11</div>
<div class="content ">
{% block con %} {% endblock %}
</div> </div>
</body>
</html>

users.html;

{% extends 'base.html' %}
{% block con %}
<h4>用户列表</h4>
{% if per.add %}
<a href="/users/add/" class="btn btn-primary">添加用户</a>
{% endif %} <table class="table table-bordered table-striped">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>角色</th>
<th>操作</th>
</tr>
</thead>
<tbody> {% for user in user_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ user.name }}</td>
<td>
{% for role in user.roles.all %}
{{ role.title }}
{% endfor %}
</td>
<td>
{% if per.delete %}
<a href="/users/delete/{{ user.pk }}" class="btn btn-danger">删除</a>
{% endif %}
{% if per.edit %}
<a href="" class="btn btn-info">编辑</a>
{% endif %}
</td>
</tr>
{% endfor %} </tbody>
</table>
{% endblock %}

roles.html;

{% extends 'base.html' %}
{% block con %}
<h4>角色列表</h4>
{% if per.add %}
<a href="" class="btn btn-primary">添加角色</a>
{% endif %} <table class="table table-bordered table-striped">
<tbody>
{% for role in role_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ role.title }}</td>
<td>
<a href="/users/delete/{{ user.pk }}" class="btn btn-danger">删除</a>
<a href="" class="btn btn-info">编辑</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}

03 按钮权限控制的简单形式

1、引入CDN的Bootstrap;

    <meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

04 修改表结构

from django.db import models

# Create your models here.

class User(models.Model):
name = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
roles = models.ManyToManyField(to="Role") def __str__(self):
return self.name class Role(models.Model):
title = models.CharField(max_length=32)
permissions = models.ManyToManyField(to="Permission") def __str__(self):
return self.title class Permission(models.Model):
title = models.CharField(max_length=32)
url = models.CharField(max_length=32)
action = models.CharField(max_length=32, default="")
group = models.ForeignKey("PermissionGroup", default=1) def __str__(self):
return self.title class PermissionGroup(models.Model):
title = models.CharField(max_length=32) def __str__(self):
return self.title

05 重构数据结构

06 限制权限颗粒度

settings.py;

"""
Django settings for s9day82_rbac project. Generated by 'django-admin startproject' using Django 1.11.1. For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0s(th#!ewf^xik5n&bqkqqjadz#q*vt+!hq(kzk5*-!t6@^0^i' # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
'rbac.apps.RbacConfig',
] MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'rbac.service.rbac.ValidPermission',
]
from django.middleware.security import SecurityMiddleware ROOT_URLCONF = 's9day82_rbac.urls' TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
] WSGI_APPLICATION = 's9day82_rbac.wsgi.application' # Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} # Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
] # Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/'

urls.py;

"""s9day82_rbac URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^users/$', views.users),
url(r'^users/add', views.add_user),
url(r'^users/delete/(\d+)', views.del_user),
url(r'^roles/', views.roles),
url(r'^login/', views.login),

Python-S9——Day83-ORM项目实战的更多相关文章

  1. Python爬虫开发与项目实战

    Python爬虫开发与项目实战(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/1MFexF6S4No_FtC5U2GCKqQ 提取码:gtz1 复制这段内容后打开百度 ...

  2. Python爬虫开发与项目实战pdf电子书|网盘链接带提取码直接提取|

    Python爬虫开发与项目实战从基本的爬虫原理开始讲解,通过介绍Pthyon编程语言与HTML基础知识引领读者入门,之后根据当前风起云涌的云计算.大数据热潮,重点讲述了云计算的相关内容及其在爬虫中的应 ...

  3. python工业互联网监控项目实战5—Collector到opcua服务

    本小节演示项目是如何从连接器到获取Tank4C9服务上的设备对象的值,并通过Connector服务的url返回给UI端请求的.另外,实际项目中考虑websocket中间可能因为网络通信等原因出现中断情 ...

  4. python工业互联网监控项目实战4—python opcua

    前面章节我们采用OPC作为设备到上位的信息交互的协议,本章我们介绍跨平台的OPC UA.OPC作为早期的工业通信规范,是基于COM/DCOM的技术实现的,用于设备和软件之间交换数据,最初,OPC标准仅 ...

  5. python金融反欺诈-项目实战

    python信用评分卡(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_camp ...

  6. python工业互联网监控项目实战2—OPC

    OPC(OLE for Process Control)定义:指为了给工业控制系统应用程序之间的通信建立一个接口标准,在工业控制设备与控制软件之间建立统一的数据存取规范.它给工业控制领域提供了一种标准 ...

  7. python数据分析美国大选项目实战(三)

    项目介绍 项目地址:https://www.kaggle.com/fivethirtyeight/2016-election-polls 包含了2015年11月至2016年11月期间对于2016美国大 ...

  8. Python工业互联网监控项目实战3—websocket to UI

    本小节继续演示如何在Django项目中采用早期websocket技术原型来实现把OPC服务端数据实时推送到UI端,让监控页面在另一种技术方式下,实时显示现场设备的工艺数据变化情况.本例我们仍然采用比较 ...

  9. Python轻松入门到项目实战-实用教程

    本课程完全基于Python3讲解,针对广大的Python爱好者与同学录制.通过本课程的学习,可以让同学们在学习Python的过程中少走弯路.整个课程以实例教学为核心,通过对大量丰富的经典实例的讲解.让 ...

  10. Python Django CMDB项目实战之-2创建APP、建模(models.py)、数据库同步、高级URL、前端页面展示数据库中数据

    基于之前的项目代码来编写 Python Django CMDB项目实战之-1如何开启一个Django-并设置base页index页文章页面 现在我们修改一个文章列表是从数据库中获取数据, 下面我们就需 ...

随机推荐

  1. 【作业留存】根据IATF框架,设计的一种中小型企业安全拓扑

  2. LeetCode Add Two Numbers 两个数相加

    /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode ...

  3. php生成纯数字、字母数字、图片、纯汉字的随机数验证码

    现在讲开始通过PHP生成各种验证码旅途,新手要开车了,请刷卡! 首先,我们开始先生成一个放验证码的背景图片 注:没有Imagejpg()这个函数,只有imagepng()函数 imagecreatet ...

  4. Liunx开发(Extjs4.1+desktop+SSH2超强视频教程实践)(1)

    下周一出差宁波了,周六日就折腾点视频: 跟着视频教程开发,不过开发环境换linux,上月找工作,某个吉祥物是松鼠的公司要求用linux开发,没用过的,连面试机会都不给,极其高冷:好吧,咱就试试,用li ...

  5. World Wind Java开发之十二——加载粗制三维模型(ExtrudedPolygon)(转)

    ww可以根据DLG图批量生成假三维模型,这对于小区等特征相似的建筑物模型的构建是非常有用的.下面来看如何一步步实现假三维模型的加载: 1.Shp文件的制作 首先在arcmap下数字化几个建筑物,并新建 ...

  6. js 实现纯前端将数据导出excel两种方式,亲测有效

    由于项目需要,需要在不调用后台接口的情况下,将json数据导出到excel表格,兼容chrome没问题,其他还没有测试过 通过将json遍历进行字符串拼接,将字符串输出到csv文件,输出的文件不会再是 ...

  7. C++手写快读详解(快速读入数字)

    众所周知,C++里是自带读入的(这不废话吗) 例如: int a; cin>>a; 这样的读入理解简单,适合初学者,但是非常慢. 再例如: int a; scanf("%d&qu ...

  8. CUDA核函数参数示意:Kernel<<<Dg,Db, Ns, S>>>(param list)

    核函数是GPU每个thread上运行的程序.必须通过__gloabl__函数类型限定符定义.形式如下: __global__ void kernel(param list){  } 核函数只能在主机端 ...

  9. ElasticSearch High Level REST API【4】多搜索

    1.Multi-Search多搜索请求 Multi-Search可同时添加多个search搜索请求,并行地在一个http请求中执行多个搜索请求,相较多次单请求查询可提升查询效率.ES客户掉通过mget ...

  10. Python Flask搭建一个视频网站实战视频教程

    点击了解更多Python课程>>> Python Flask搭建一个视频网站实战视频教程 第1章 课程介绍 第2章 预备开发环境 第3章 项目分析.建立目录及模型规划 第4章 建立前 ...