rbac应用——报障系统

rbac组件应用之报障创建


settings配置:

# ############################## RBAC权限相关配置开始 ##############################
# # 无需权限控制的URL
RBAC_NO_AUTH_URL = [
    '/login.html',
    '/index.html',
    '/register.html',
    '/admin.*',
    '/rbac.*',
]

# session中保存权限信息的Key
RBAC_PERMISSION_SESSION_KEY = "rbac_permission_session_key"

# Http请求中传入的参数,根据其获取GET、POST、EDIT等检测用户是否具有相应权限
# 例如:
#       http://www.example.com?md=get   表示获取
#       http://www.example.com?md=post  表示添加
#       http://www.example.com?md=del   表示删除
RBAC_QUERY_KEY = "md"
RBAC_DEFAULT_QUERY_VALUE = "look"  # 默认操作方法是look

# 无权访问时,页面提示信息
RBAC_PERMISSION_MSG = "无权限访问"

# Session中保存菜单和权限信息的Key
RBAC_MENU_PERMISSION_SESSION_KEY = "rbac_menu_permission_session_key"
RBAC_MENU_KEY = "rbac_menu_key"
RBAC_MENU_PERMISSION_KEY = "rbac_menu_permission_key"

# 菜单主题
RBAC_THEME = "default"
# ############################## RBAC权限相关配置结束 ##############################

urls:

url(r'^login.html$', views.login),
url(r'^index.html$', views.index),
url(r'^problem.html$', views.problem),

views:

from django.shortcuts import render
from django.shortcuts import redirect
from app01 import models
from rbac.service import initial_permission


# Create your views here.
def login(request):
    """
    用户登陆
    :param request: 
    :return: 
    """
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        obj = models.UserInfo.objects.filter(user__username=username, user__password=password).first()
        if obj:
            # 登陆成功后,将用户信息保存到session当中
            request.session['user_info'] = {'username': username, 'nickname': obj.nickname, 'nid': obj.id}
            initial_permission(request, obj.user_id)  # 初始化用户对应的权限
            return redirect('/index.html')
        else:
            return render(request, 'login.html')


def index(request):
    """
    显示首页
    :param request: 
    :return: 
    """
    if not request.session['user_info']:
        return redirect('/login.html')
    return render(request, 'index.html')


def problem(request):
    """
    报障功能
    :param request: 
    :return: 
    """
    if request.permission_code == 'LOOK':  # 该值在中间件已经处理成request字典中的一个值
        problem_list = models.Order.objects.filter(create_user_id=request.session['user_info']['nid'])
        return render(request, 'problem.html', {'problem_list': problem_list})
    elif request.permission_code == 'DEL':
        nid = request.GET.get('nid')
        models.Order.objects.filter(create_user_id=request.session['user_info']['nid'], id=nid).delete()
        return redirect('/problem.html')
    elif request.permission_code == 'POST':
        if request.method == 'GET':
            return render(request, 'problem_add.html')
        else:
            title = request.POST.get('title')
            content = request.POST.get('content')
            models.Order.objects.create(title = title, detail = content, create_user_id=request.session['user_info']['nid'])
            return redirect('/problem.html')

html:

  • layout.html模版:
{% load rbac %}

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <style>
        body {
            margin: 0;
        }

        .pd-header {
            height: 80px;
            background-color: red;
        }

        .pd-body .menu {
            float: left;
            width: 20%;

        }

        .pd-body .content {
            float: left;
            width: 80%;

        }

        {% rbac_css %}
    style>
    {% block css %}{% endblock %}
head>
<body>
<div class="pd-header">div>
{# 导航条 #}

<div class="pd-body">
    <div class="menu">{% rbac_menu request %}div>
    {#    request作为参数传入 rbac_menu函数中#}
    <div class="content">{% block content %}{% endblock %}div>
div>
<script src="/static/jquery-1.12.4.js">script>
<script>{% rbac_js %}script>
{% block js %}{% endblock %}
body>
html>
  • login.html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<form action="login.html", method="post">
    {% csrf_token %}
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="submit" value="提交">

form>
body>
html>
  • index.html
{% extends 'layout.html' %}
{% block content %}
    欢迎登陆:{{ request.session.user_info.nickname }}
{% endblock %}
  • 报障单页面:problem.html
{% extends 'layout.html' %}
{% block content %}
    <div>
        {% if 'POST' in request.permission_code_list %}
            <a href="/problem.html?md=post">添加a>
        {% endif %}
        <div>
            <table border="1">
                {% for row in problem_list %}
                    <tr>
                        <td>{{ row.title }}td>
                        <td>{{ row.status }}td>
                        <td>
                            {% if 'EDIT' in request.permission_code_list %}
                                <a href="/problem.html?md=edit&nid={{ row.id }}">编辑a>
                            {% endif %}
                            {% if 'DEL' in  request.permission_code_list %}
                                <a href="/problem.html?md=del&nid={{ row.id }}">删除a>
                            {% endif %}
                            {% if 'DETAIL' in  request.permission_code_list %}
                                <a href="/problem.html?md=del&nid={{ row.id }}">查看详细a>
                            {% endif %}
                        td>
                    tr>
                {% endfor %}
            table>

        div>
    div>

{% endblock %}
  • 添加报障单:problem_add.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>title>
head>
<body>
    <form action="/problem.html?md=post" method="POST">
        {% csrf_token %}
        <input type="text" name="title" />
        <textarea name="content">textarea>
        <input type="submit" value="提交" />
    form>
body>
html>

二十一、rbac组件应用之报障的处理


urls:

    url(r'^problem-kill.html$', views.problem_kill),

views:

def problem_kill(request):
    """
    处理报障单
    :param request:
    :return:
    """
    nid = request.session['user_info']['nid']  # 获得登陆用户的Id
    if request.permission_code == 'LOOK':
        # 查看列表,未解决,当前用户已经解决或正在解决
        from django.db.models import Q
        problem_list = models.Order.objects.filter(Q(status=1) | Q(processor_id=nid)).order_by('status')
        return render(request, 'problem_kill_look.html', {'problem_list': problem_list})

    elif request.permission_code == 'EDIT':
        # http://127.0.0.1:8000/trouble-kill.html?md=edit&nid=1
        if request.method == 'GET':  # 跳转到处理页面
            order_id = request.GET.get('nid')
            # 用户已经抢到过,处于处理中状态
            if models.Order.objects.filter(id=order_id, processor_id=nid, status=2):
                obj = models.Order.objects.filter(id=order_id).first()
                return render(request, 'problem_kill_edit.html', {'obj': obj})
            # 没有人抢到过,处于未处理状态,
            res = models.Order.objects.filter(id=order_id, status=1).update(processor_id=nid, status=2)
            if not res:
                return HttpResponse("已经有人在处理了")
            else:
                obj = models.Order.objects.filter(id=order_id).first()
                return render(request, 'problem_kill_edit.html', {'obj': obj})
        else:
            order_id = request.GET.get('nid')
            solution = request.POST.get('solution')
            models.Order.objects.filter(id=order_id, processor_id=nid).update(solution=solution, status=3,
                                                                              ptime=datetime.datetime.now())
            return redirect('/problem_kill.html')

html:

  • 展示页面:problem_kill_look.html
{% extends 'layout.html' %}
{% block content %}
    {% for row in problem_list %}
        <tr>
            <td>{{ row.title }}td>
            <td>{{ row.create_user.nickname }}td>
            <td>{{ row.ctime | date:'Y-m-d H:i:s' }}td>
            {# 获得字段的文字展示,而非数字#}
            <td>{{ row.get_status_display }}td>

            {% if 'EDIT' in request.permission_code_list %}
                <td><a href="/problem-kill.html?md=edit&nid={{ row.id }}">处理a>td>
            {% endif %}

        tr>
    {% endfor %}
{% endblock %}
  • 编辑页面:problem_kill_edit.html
{% extends 'layout.html' %}

{% block content %}
    <form action="/problem-kill.html?md=edit&nid={{ obj.id }}" method="POST">
        {% csrf_token %}
        <div>
            <p>{{ obj.title }}p>
            <p>{{ obj.detail }}p>
            <p>{{ obj.ctime }}p>
        div>
        <textarea name="solution">textarea>
        <input type="submit" value="提交" />
    form>
{% endblock %}

二十二、rbac组件应用之报表的计算(包含highchart组件)


urls:

    url(r'^report.html$', views.report),

views:

def report(request):
    if request.permission_code == 'LOOK':   # 用户权限操作为LOOK时
        if request.method == 'GET':
            return render(request, 'report.html')
        else:
            from django.db.models import Count
            # 组装饼图所需要的数据格式
            result = models.Order.objects.filter(status=3).values_list('processor__nickname').annotate(ct=Count('id'))
            # 分组:select * from xx group by processor_id,ptime(2017-11-11)
            # 折线图
            # strftime('%%s',strftime('%%Y-%%m-%%d',ptime)) 表示将2017-02-03 12:30:20转换成2017-02-03,再转换成折线图所需要的时间戳格式
            # mysql:models.Event.objects.extra(
    select={'date': "date_format(create_time, '%%Y-%%m-%%d')"}).values('date').annotate(total=Count('id')).filter(on_time=1)

            ymd_list = models.Order.objects.filter(status=3).extra(select={'ymd':"strftime('%%s',strftime('%%Y-%%m-%%d',ptime))"}).values('processor_id','processor__nickname','ymd').annotate(ct=Count('id'))
            ymd_dict = {}
            for row in ymd_list:
                key = row['processor_id']
                if key in ymd_dict:
                    ymd_dict[key]['data'].append(float(row['ymd']*1000),row['ct'])
                else:
                    # 折线图需要*1000的数据
                    ymd_dict[key] = {'name':row['processor__nickname'],'data':[[float(row['ymd'])*1000, row['ct']], ]}
            response={
                'zhexian': list(ymd_dict.values()),
                'pie': [['方少伟', 45.0], ['吴永强', 40.0], ['友情并', 3], ['尹树林', 90]],
            }
            return HttpResponse(json.dumps(response))

html:

{% extends 'layout.html' %}
{% block content %}
    <div id="container" style="min-width:300px;height:300px">div>
    <div id="container2" style="min-width:500px;height:500px">div>
{% endblock %}

{% block js %}
    <script src="https://img.hcharts.cn/highcharts/highcharts.js">script>
    <script src="https://img.hcharts.cn/highcharts/modules/exporting.js">script>
    <script src="https://img.hcharts.cn/highcharts-plugins/highcharts-zh_CN.js">script>

    <script>
        $(function () {
            Highcharts.setOptions({
                global: {
                    useUTC: false
                }
            });
            $.ajax({
                url: '/report.html',
                type: "POST",
                data: {'csrfmiddlewaretoken': '{{ csrf_token }}'},
                dataType: 'JSON',
                {#返回的数据从字符串转换为字典格式#}
                success: function (arg) {
                    console.log(arg);

                    $('#container').highcharts({
                        chart: {
                            plotBackgroundColor: null,
                            plotBorderWidth: null,
                            plotShadow: false
                        },
                        title: {
                            text: '运维人员处理报障占比'
                        },
                        tooltip: {
                            headerFormat: '{series.name}
'
, pointFormat: '{point.name}: {point.percentage:.1f}%' }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '{point.name}: {point.percentage:.1f} %', style: { color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black' } } } }, series: [{ type: 'pie', name: '运维人员处理报障占比', data: arg.pie }] }); Highcharts.chart('container2', { title: { text: '每日处理订单详细', x: -20 //center }, subtitle: { text: '...', x: -20 }, legend: { layout: 'horizontal', align: 'center', verticalAlign: 'bottom', borderWidth: 1 }, xAxis: { labels: { formatter: function () { return Highcharts.dateFormat("%Y-%m-%d", this.value); //return this.value; } }, minTickInterval: 24 }, series: arg.zhexian }); } }); })
script>
{% endblock %}

你可能感兴趣的:(python项目汇总)