RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
Django之入门CMDB系统(六)前后端分离之后端

Django之入门 CMDB系统 (六) 前后端分离之后端


前言

作者: 何全,github地址: https://github.com/××× QQ交流群: ×××

成都创新互联是一家业务范围包括IDC托管业务,网页空间、主机租用、主机托管,四川、重庆、广东电信服务器租用,服务器机柜租赁,成都网通服务器托管,成都服务器租用,业务范围遍及中国大陆、港澳台以及欧美等多个国家及地区的互联网数据服务公司。

通过此教程完成从零入门,能够独立编写一个简单的CMDB系统。

目前主流的方法开发方式,分为2种:mvc 和 mvvc方式。本教程为 mvvc(前后端分离)的入门教程。

教程项目地址: https://github.com/×××/panda/

教程文档地址: https://github.com/×××/pandaAdmin

基础

主要使用 djangorestframework 模块,提供 api。 drf 中文文档 http://drf.jiuyou.info/#/drf/requests

基础环境配置 可以看前面的 第一篇 。

mvvc 后端 和mvc 后端,基本配置信息部分差不多,以下是列出不一样的部分。

  • 模块
django-cors-headers
django-crispy-forms
django-filter
django-pure-pagination
djangorestframework
django-rest-swagger
  • settings
AUTH_USER_MODEL = 'system.users'   #更改user表

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'system.apps.SystemConfig',
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'django_filters',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

## rest api
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer'  # 注释掉 可以关闭  api web界面
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        # 'rest_framework.permissions.AllowAny',
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'
}

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
    '*',
)
MIDDLEWARE_CLASSES = ('system.views.DisableCSRFCheck',)
  • system.views.DisableCSRFCheck
class DisableCSRFCheck(object):
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)
  • urls.py
from django.contrib import admin
from django.urls import path
from rest_framework.authtoken import views
from rest_framework.documentation import include_docs_urls
from django.conf.urls import include

API_TITLE = '文档'
API_DESCRIPTION = '文档'

urlpatterns = [
    path('system/', include('system.urls', namespace='system')),
    path('admin/', admin.site.urls, ),
    path('token', views.obtain_auth_token),
    path('docs', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION, authentication_classes=[],
                                        permission_classes=[])),
]

例子

  • 新建app system

  • models.py
from django.db import models
from django.contrib.auth.models import AbstractUser, Group, User

class Users(AbstractUser):
    """
    基于django表  添加字段 , 如有需要调用user的情况,请使用此表
    """
    position = models.CharField(max_length=64, verbose_name='职位信息', blank=True, null=True)
    avatar = models.CharField(max_length=256, verbose_name='头像', blank=True, null=True)
    mobile = models.CharField(max_length=11, verbose_name='手机', blank=True, null=True)

    class Meta:
        db_table = 'users'
        verbose_name = '用户信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

class Test(models.Model):
    date = models.CharField(max_length=96, verbose_name='日期', blank=True, null=True, )
    name = models.CharField(max_length=96, verbose_name='姓名', blank=True, null=True, )
    address = models.CharField(max_length=96, verbose_name='地址', blank=True, null=True, )

    # c_time = models.DateTimeField(auto_now_add=True, null=True, verbose_name='创建时间', blank=True)
    # u_time = models.DateTimeField(auto_now=True, null=True, verbose_name='更新时间', blank=True)

    class Meta:
        db_table = "test"
        verbose_name = "测试"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name
  • serializers.py
from rest_framework import serializers
from system.models import Test

class TestSerializer(serializers.ModelSerializer):
    class Meta:
        model = Test
        fields = '__all__'
  • views.py
class TestList(generics.ListCreateAPIView):
    queryset = Test.objects.get_queryset().order_by('id')
    serializer_class = TestSerializer
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_fields = ('id', 'date','name')
    search_fields = ('id', 'name',)
    permission_classes = (permissions.DjangoModelPermissions,)  # 继承 django的权限

class TestDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Test.objects.get_queryset().order_by('id')
    serializer_class = TestSerializer
    permission_classes = (permissions.DjangoModelPermissions,)

class UserInfo(APIView):
    """
    获取用户信息
    """
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request):
        token = (json.loads(request.body))['token']
        obj = Token.objects.get(key=token).user
        result = {
            'name': obj.username,
            'user_id': obj.id,
            'access': list(obj.get_all_permissions()) + ['admin'] if obj.is_superuser else list(
                obj.get_all_permissions()),
            'token': token,
            'avatar': ''
        }
        return HttpResponse(json.dumps(result))

class UserLogout(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request):
        token = (json.loads(request.body))['token']
        obj = Token.objects.get(key=token)
        obj.delete()
        result = {
            "status": True
        }
        return HttpResponse(json.dumps(result))
  • urls.py
app_name = "system"

urlpatterns = [
    path('user_info', UserInfo.as_view()),
    path('logout', UserLogout.as_view()),
    path('test', TestList.as_view()),
    path('test/', TestDetail.as_view())
]
  • admin.py
from django.contrib import admin
from system.models import Users, Test
from django.contrib.auth.admin import UserAdmin

class UsersAdmin(UserAdmin):
    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        ('基本信息', {'fields': ('first_name', 'last_name', 'email')}),
        ('权限', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
        ('登录时间', {'fields': ('last_login', 'date_joined')}),
        ('其他信息', {'fields': (
            'position', 'avatar', 'mobile',)}),
    )

    @classmethod
    def show_group(self, obj):
        return [i.name for i in obj.groups.all()]

    @classmethod
    def show_user_permissions(self, obj):
        return [i.name for i in obj.user_permissions.all()]

    list_display = ('username', 'show_group', 'show_user_permissions')
    list_display_links = ('username',)
    search_fields = ('username',)
    filter_horizontal = ('groups', 'user_permissions')

admin.site.register(Users, UsersAdmin)
admin.site.register(Test)

admin.site.site_header = '管理后台'
admin.site.site_title = admin.site.site_header

部署

pip3 install -r requirements.txt ## 安装所有模块,如有增加模块,需要加到这里面

初始化数据库

python3.6 -u /opt/manage.py runserver 192.168.100.99:8000

启动前端


分享题目:Django之入门CMDB系统(六)前后端分离之后端
网页地址:http://lswzjz.com/article/jdiegp.html