From cff1ecbe00cecd6f7457deffd0d7d5fe9c251b87 Mon Sep 17 00:00:00 2001 From: caoqianming Date: Mon, 11 Apr 2022 10:41:26 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=89=E6=96=B9=E8=B0=83=E7=94=A8=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/develop/urls.py | 11 +++++++---- apps/develop/views.py | 10 +++++++++- apps/system/serializers.py | 30 ++++++------------------------ apps/third/erros.py | 1 + apps/third/serializers.py | 7 ++++--- apps/third/tapis.py | 16 ++++++++++++++++ apps/third/views.py | 34 ++++++++++++++++++++-------------- apps/utils/dahua.py | 7 ++++++- apps/utils/mixins.py | 2 +- server/settings.py | 4 ++-- server/urls.py | 1 + 11 files changed, 73 insertions(+), 50 deletions(-) create mode 100644 apps/third/erros.py create mode 100644 apps/third/tapis.py diff --git a/apps/develop/urls.py b/apps/develop/urls.py index a3ff037e..90caa4e4 100644 --- a/apps/develop/urls.py +++ b/apps/develop/urls.py @@ -4,10 +4,13 @@ from django.urls import path, include from rest_framework.routers import DefaultRouter from apps.develop.views import BackupDatabase, BackupMedia, ReloadServerGit, ReloadServerOnly +API_BASE_URL = 'api/develop/' +HTML_BASE_URL = 'develop/' + urlpatterns = [ - path('reload_server_git/', ReloadServerGit.as_view()), - path('reload_server_only/', ReloadServerOnly.as_view()), - path('backup_database/', BackupDatabase.as_view()), - path('backup_media/', BackupMedia.as_view()) + path(API_BASE_URL + 'reload_server_git/', ReloadServerGit.as_view()), + path(API_BASE_URL + 'reload_server_only/', ReloadServerOnly.as_view()), + path(API_BASE_URL + 'backup_database/', BackupDatabase.as_view()), + path(API_BASE_URL + 'backup_media/', BackupMedia.as_view()) ] diff --git a/apps/develop/views.py b/apps/develop/views.py index c1e732de..427672a4 100644 --- a/apps/develop/views.py +++ b/apps/develop/views.py @@ -13,7 +13,9 @@ class ReloadServerGit(APIView): permission_classes = [IsAdminUser] def post(self, request): """ - 拉取代码并重启服务 + 拉取后端代码并重启服务 + + 拉取后端代码并重启服务 """ completed = reload_server_git() if completed.returncode == 0: @@ -25,6 +27,8 @@ class ReloadServerOnly(APIView): permission_classes = [IsAdminUser] def post(self, request): """ + 仅重启服务 + 仅重启服务 """ completed = reload_server_only() @@ -38,6 +42,8 @@ class BackupDatabase(APIView): permission_classes = [IsAdminUser] def post(self, request): """ + 备份数据库到指定位置 + 备份数据库到指定位置 """ completed = backup_database() @@ -50,6 +56,8 @@ class BackupMedia(APIView): permission_classes = [IsAdminUser] def post(self, request): """ + 备份资源到指定位置 + 备份资源到指定位置 """ completed = backup_media() diff --git a/apps/system/serializers.py b/apps/system/serializers.py index 0a0b018e..2a79005a 100644 --- a/apps/system/serializers.py +++ b/apps/system/serializers.py @@ -1,3 +1,4 @@ +import json import re from django_celery_beat.models import PeriodicTask, CrontabSchedule, IntervalSchedule from rest_framework import serializers @@ -9,6 +10,7 @@ from .models import (Dict, DictType, File, Dept, Permission, Post, Role, User, UserPost) from rest_framework.exceptions import ParseError, APIException from django.db import transaction +from apps.third.tapis import dhapis class IntervalSerializer(CustomModelSerializer): class Meta: @@ -195,15 +197,9 @@ class DeptCreateUpdateSerializer(CustomModelSerializer): "name":validated_data['name'], "service":"ehs" } - ok, res = dhClient.request('/evo-apigw/evo-brm/1.0.0/department/add', - 'post',json=data) - if ok == 'success': - third_info = {'dh_id':str(res['id'])} - validated_data['third_info'] = third_info - elif ok == 'fail': - raise ParseError(**res) - else: - raise APIException(**res) + _, res = dhClient.request(**dhapis['dept_create'],json=data) + third_info = {'dh_id':str(res['id'])} + validated_data['third_info'] = third_info return super().create(validated_data) @@ -217,14 +213,7 @@ class DeptCreateUpdateSerializer(CustomModelSerializer): "parentId":1, "name":validated_data['name'] } - ok, res = dhClient.request('/evo-apigw/evo-brm/1.0.0/department/update', - 'put',json=data) - if ok == 'success': - pass - elif ok == 'fail': - raise ParseError(**res) - else: - raise APIException(**res) + dhClient.request(**dhapis['dept_update'],json=data) return super().update(instance, validated_data) class UserSimpleSerializer(CustomModelSerializer): @@ -244,13 +233,6 @@ class UserListSerializer(CustomModelSerializer): model = User exclude = ['password'] - @staticmethod - def setup_eager_loading(queryset): - """ Perform necessary eager loading of data. """ - queryset = queryset.select_related('superior', 'belong_dept') - queryset = queryset.prefetch_related('posts') - return queryset - def phone_check(phone): re_phone = '^1[358]\d{9}$|^147\d{8}$|^176\d{8}$' if not re.match(re_phone, phone): diff --git a/apps/third/erros.py b/apps/third/erros.py new file mode 100644 index 00000000..f60c82a0 --- /dev/null +++ b/apps/third/erros.py @@ -0,0 +1 @@ +TAPI_CODE_WRONG = {"code":"tapi_code_wrong", "detail":"三方接口请求标识有误"} \ No newline at end of file diff --git a/apps/third/serializers.py b/apps/third/serializers.py index 0879cec3..4d27a090 100644 --- a/apps/third/serializers.py +++ b/apps/third/serializers.py @@ -8,7 +8,8 @@ class RequestCommonSerializer(serializers.Serializer): ('put','put'), ('delete','delete') ) - url = serializers.CharField(label='请求地址') - method = serializers.ChoiceField(label='请求方法', choices=method_choice) + url = serializers.CharField(label='请求地址', required=False) + method = serializers.ChoiceField(label='请求方法', choices=method_choice, required=False) params = serializers.JSONField(label='请求参数', required=False, allow_null=True) - json = serializers.JSONField(label='请求body', required=False, allow_null=True) \ No newline at end of file + json = serializers.JSONField(label='请求body(json格式)', required=False, allow_null=True) + code = serializers.CharField(label='请求短标识', required=False) \ No newline at end of file diff --git a/apps/third/tapis.py b/apps/third/tapis.py new file mode 100644 index 00000000..c90979e1 --- /dev/null +++ b/apps/third/tapis.py @@ -0,0 +1,16 @@ +# 大华API接口 +dhapis = { + "dept_create":{ + "url":"/evo-apigw/evo-brm/1.0.0/department/add", + "method":"post" + }, + "dept_update":{ + "url":"/evo-apigw/evo-brm/1.0.0/department/update", + "method":"put" + } +} + +# 寻息API接口 +xxapis = { + +} \ No newline at end of file diff --git a/apps/third/views.py b/apps/third/views.py index 741f56a6..e7f5ca48 100644 --- a/apps/third/views.py +++ b/apps/third/views.py @@ -1,4 +1,6 @@ from rest_framework.exceptions import ParseError, APIException +from apps.third import tapis +from apps.third.erros import TAPI_CODE_WRONG from apps.utils.dahua import dhClient from apps.utils.errors import XX_REQUEST_ERROR from apps.utils.xunxi import xxClient @@ -81,17 +83,19 @@ class XxCommonViewSet(CreateModelMixin, CustomGenericViewSet): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) vdata = serializer.validated_data - ok, res = xxClient.request( + if vdata.get('code', ''): + try: + dhapi = tapis.dhapis[vdata['code']] + except: + raise ParseError(**TAPI_CODE_WRONG) + vdata['url'] = dhapi['url'] + vdata['method'] = dhapi['method'] + _, res = xxClient.request( url=vdata['url'], method=vdata.get('method', 'post'), params=vdata.get('params', {}), json=vdata.get('data', {})) - if ok == 'success': - return Response(res) - elif ok == 'fail': - raise ParseError(**res) - else: - raise APIException(**res) + return Response(res) class DhCommonViewSet(CreateModelMixin, CustomGenericViewSet): @@ -105,14 +109,16 @@ class DhCommonViewSet(CreateModelMixin, CustomGenericViewSet): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) vdata = serializer.validated_data - ok, res = dhClient.request( + if vdata.get('code', ''): + try: + xxapi = tapis.xxapis[vdata['code']] + except: + raise ParseError(**TAPI_CODE_WRONG) + vdata['url'] = xxapi['url'] + vdata['method'] = xxapi['method'] + _, res = dhClient.request( url=vdata['url'], method=vdata.get('method', 'post'), params=vdata.get('params', {}), json=vdata.get('data', {})) - if ok == 'success': - return Response(res) - elif ok == 'fail': - raise ParseError(**res) - else: - raise APIException(**res) + return Response(res) diff --git a/apps/utils/dahua.py b/apps/utils/dahua.py index cd3b4e2f..c9ac95a7 100644 --- a/apps/utils/dahua.py +++ b/apps/utils/dahua.py @@ -65,7 +65,7 @@ class DhClient: self.isRuning = False self.t.join() - def request(self, url:str, method:str, params=dict(), json=dict(), timeout=20): + def request(self, url:str, method:str, params=dict(), json=dict(), timeout=20, raise_exception=True): if self.isGetingToken: req_num = 0 while True: @@ -91,8 +91,13 @@ class DhClient: else: if ret['code'] not in ['0', '100', '00000', '1000', 0, 100, 1000]: detail = '{}|{}{}'.format(str(ret['code']), ret.get('errMsg',''), ret.get('desc', '')) + err_detail = dict(detail=detail, code='dh_'+str(ret['code'])) + if raise_exception: + raise ParseError(**err_detail) return 'fail', dict(detail=detail, code='dh_'+str(ret['code'])) return 'success', ret['data'] + if raise_exception: + raise APIException(**DH_REQUEST_ERROR) return 'error', DH_REQUEST_ERROR dhClient = DhClient() \ No newline at end of file diff --git a/apps/utils/mixins.py b/apps/utils/mixins.py index 28be0ba7..aef5a27a 100644 --- a/apps/utils/mixins.py +++ b/apps/utils/mixins.py @@ -142,7 +142,7 @@ class MyLoggingMixin(object): "response_ms": self._get_response_ms(), "response": self._clean_data(rendered_content), "status_code": response.status_code, - "agent": self._get_agent(), + "agent": self._get_agent(request), } ) try: diff --git a/server/settings.py b/server/settings.py index afb850e0..a5aa5985 100644 --- a/server/settings.py +++ b/server/settings.py @@ -176,8 +176,8 @@ REST_FRAMEWORK = { 'DATETIME_FORMAT': '%Y-%m-%d %H:%M:%S', 'DATE_FORMAT': '%Y-%m-%d', 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', - 'UNAUTHENTICATED_USER': None, - 'UNAUTHENTICATED_TOKEN': None, + # 'UNAUTHENTICATED_USER': None, + # 'UNAUTHENTICATED_TOKEN': None, 'EXCEPTION_HANDLER': 'apps.utils.exceptions.custom_exception_hander', } # simplejwt配置 diff --git a/server/urls.py b/server/urls.py index 67076a58..98748efe 100644 --- a/server/urls.py +++ b/server/urls.py @@ -46,6 +46,7 @@ urlpatterns = [ path('', include('apps.wf.urls')), path('', include('apps.third.urls')), path('', include('apps.utils.urls')), + path('', include('apps.develop.urls')),