Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction to Django CMDB system (6) back-end separation of back-end

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

Introduction to Django CMDB system (6) Preface to the separation of front and rear ends

Author: he Quan, github address: https://github.com/ × × QQ Exchange Group: × × ×

Through this tutorial to complete from scratch, you can write a simple CMDB system independently.

At present, the mainstream methods of development are divided into two types: mvc and mvvc. This tutorial is an introduction to mvvc (front and rear separation).

Tutorial project address: https://github.com/ × × / panda/

Tutorial documentation address: https://github.com/ × × / pandaAdmin

Basics

It mainly uses djangorestframework module and provides api. Drf Chinese document http://drf.jiuyou.info/#/drf/requests

The basic environment configuration can be seen in the first article above.

The basic configuration information of mvvc backend is similar to that of mvc backend. The following is a list of different parts.

Module django-cors-headersdjango-crispy-formsdjango-filterdjango-pure-paginationdjangorestframeworkdjango-rest-swaggersettingsAUTH_USER_MODEL = 'system.users' # change user table 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 apiREST_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' # comments can close the api web interface),' 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 = TrueCORS_ORIGIN_ALLOW_ALL = TrueCORS_ORIGIN_WHITELIST = ('*,) MIDDLEWARE_CLASSES = ('system.views.DisableCSRFCheck',) system.views.DisableCSRFCheckclass DisableCSRFCheck (object): def process_request (self, request): setattr (request,' _ dont_enforce_csrf_checks') True) urls.pyfrom django.contrib import adminfrom django.urls import pathfrom rest_framework.authtoken import viewsfrom rest_framework.documentation import include_docs_urlsfrom django.conf.urls import includeAPI_TITLE = 'document' API_DESCRIPTION = 'document' 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= []),] example

Create a new app system

Models.pyfrom django.db import modelsfrom django.contrib.auth.models import AbstractUser, Group, Userclass Users (AbstractUser): "" add fields based on the django table. If you need to call user, use this table "position = models.CharField (max_length=64, verbose_name=' position information', blank=True, null=True) avatar = models.CharField (max_length=256, verbose_name=' avatar', blank=True, null=True) mobile = models.CharField (max_length=11 Verbose_name=' Mobile', blank=True, null=True) class Meta: db_table = 'users' verbose_name=' user Information' verbose_name_plural = verbose_name def _ str__ (self): return self.usernameclass Test (models.Model): date = models.CharField (max_length=96, verbose_name=' date', blank=True, null=True,) name= models.CharField (max_length=96, verbose_name=' name', blank=True, null=True ) address = models.CharField (max_length=96, verbose_name=' address', blank=True, null=True,) # c_time = models.DateTimeField (auto_now_add=True, null=True, verbose_name=' creation time', blank=True) # u_time = models.DateTimeField (auto_now=True, null=True, verbose_name=' update time' Blank=True) class Meta: db_table = "test" verbose_name = "Test" verbose_name_plural = verbose_name def _ _ str__ (self): return self.nameserializers.pyfrom rest_framework import serializersfrom system.models import Testclass TestSerializer (serializers.ModelSerializer): class Meta: model = Test fields ='_ all__'views.pyclass 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,) # inherits the permissions of django class TestDetail (generics.RetrieveUpdateDestroyAPIView): queryset = Test.objects.get_queryset (). Order_by ('id') serializer_class = TestSerializer permission_classes = (permissions.DjangoModelPermissions) ) class UserInfo (APIView): "" get user information "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.pyapp_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.pyfrom django.contrib import adminfrom system.models import Users, Testfrom django.contrib.auth.admin import UserAdminclass UsersAdmin (UserAdmin): fieldsets = (None, {'fields': (' username', 'password')}), (' basic information', {'fields': (' first_name', 'last_name') 'email')}), (' permission', {'fields': (' is_active', 'is_staff',' is_superuser', 'groups',' user_permissions')}), ('login time', {'fields': (' last_login', 'date_joined')}), (' other information', {'fields': (' position', 'avatar') ),) @ 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 =' manage backend 'admin.site.site_title = admin.site.site_header deployment

Pip3 install-r requirements.txt # # install all modules. If there are any additional modules, you need to add them to it.

Initialize the database

Python3.6-u / opt/manage.py runserver 192.168.100.99pur8000

Start the front end

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report