From f9d08d0125684dc18d7fe8558a6cf43f42ee8225 Mon Sep 17 00:00:00 2001 From: chenzuoqing Date: Mon, 27 Dec 2021 16:58:53 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=80=E5=8C=96=E6=8E=A5=E5=8F=A3=E4=B8=AD?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E5=BF=85=E8=A6=81=E7=9A=84=E5=8F=82=E6=95=B0?= =?UTF-8?q?=E7=9A=84=E8=A7=A3=E6=9E=90=EF=BC=8C=E6=A0=B9=E6=8D=AE=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E6=96=B9=E6=B3=95=E5=88=A4=E6=96=AD=EF=BC=8C=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E5=8F=AF=E7=BC=BA=E5=B0=91=20=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E7=9B=B8=E5=85=B3=E7=9A=84=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E3=80=81=E8=A7=A3=E6=9E=90=E6=96=B9=E6=B3=95=E3=80=81?= =?UTF-8?q?=E8=A7=86=E5=9B=BE=E5=92=8C=E8=B7=AF=E7=94=B1=EF=BC=8C=E5=BD=92?= =?UTF-8?q?=E7=B1=BB=E5=88=B0=E4=B8=AD=E9=97=B4=E4=BB=B6=E5=92=8C=E5=AE=9E?= =?UTF-8?q?=E4=BE=8B=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/api/v1/asset.py | 6 +- src/common/formatter.py | 2 +- src/common/serializer.py | 4 +- src/controller/asset/credential.py | 22 +-- src/controller/asset/host.py | 56 ++++++ src/controller/asset/instance.py | 22 +-- src/controller/asset/middleware.py | 20 +- src/controller/asset/parsers.py | 71 -------- src/controller/asset/views.py | 284 ----------------------------- src/controller/project/parsers.py | 54 +++--- src/controller/project/views.py | 32 ---- 11 files changed, 108 insertions(+), 465 deletions(-) create mode 100644 src/controller/asset/host.py delete mode 100644 src/controller/asset/parsers.py delete mode 100644 src/controller/asset/views.py diff --git a/src/api/v1/asset.py b/src/api/v1/asset.py index 152a713..7616892 100644 --- a/src/api/v1/asset.py +++ b/src/api/v1/asset.py @@ -1,7 +1,7 @@ from flask import Blueprint from flask_restful import Api -from controller.asset import views +from controller.asset import host from controller.asset import instance from controller.asset import middleware from controller.asset import credential @@ -11,8 +11,8 @@ asset = Blueprint('asset', __name__, url_prefix="/asset") # 增加路由 api = Api(asset) -api.add_resource(views.HostViews, '/host/', endpoint="host") -api.add_resource(views.HostDetailViews, '/host//', endpoint="host-detail") +api.add_resource(host.HostViews, '/host/', endpoint="host") +api.add_resource(host.HostDetailViews, '/host//', endpoint="host-detail") # 凭据相关视图 api.add_resource(credential.CredentialViews, '/credential/', endpoint="cred-all") diff --git a/src/common/formatter.py b/src/common/formatter.py index 56c0bd4..551c9e1 100644 --- a/src/common/formatter.py +++ b/src/common/formatter.py @@ -1,5 +1,5 @@ from flask_restful import marshal -from common.serializer import marshal as marshal_fields +from common.serializer import marshal_fields from functools import reduce diff --git a/src/common/serializer.py b/src/common/serializer.py index a1d323c..1807c08 100644 --- a/src/common/serializer.py +++ b/src/common/serializer.py @@ -1,7 +1,8 @@ +from flask_restful import marshal from collections import OrderedDict -def marshal(data, fields, envelope=None, only_exist=False, required_fields=None, **kwargs): +def marshal_fields(data, fields, envelope=None, only_exist=False, required_fields=None, **kwargs): """Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields. @@ -54,7 +55,6 @@ def marshal(data, fields, envelope=None, only_exist=False, required_fields=None, # else make(v).output(k, data)) # for k, v in fields.items()) items = ((k, v) for k, v in map(parse, fields.items()) if k is not None) - print(items) return OrderedDict([(envelope, OrderedDict(items))]) if envelope else OrderedDict(items) diff --git a/src/controller/asset/credential.py b/src/controller/asset/credential.py index 4b5a9e3..8de4261 100644 --- a/src/controller/asset/credential.py +++ b/src/controller/asset/credential.py @@ -14,8 +14,11 @@ class CredentialParse: # 给子类用的唯一字段,用于校验 # uniq_fields = ("name", "host") - def init_parse(self): + def __init__(self): + # 创建时必要的参数用此变量判断,更新默认都可以不传 + required = request.method == "POST" self.request_parse = reqparse.RequestParser() + self.request_parse.add_argument("name", required=required, type=str, location='json') self.request_parse.add_argument("class_name", required=False, type=str, location='json') @@ -42,21 +45,12 @@ class CredentialViews(CredentialParse, ListCreateViewSet): fields = CredentialFields filter_fields = (("name", "icontains"), ) - def __init__(self): - self.init_parse() - print(request.method) - self.request_parse.add_argument("name", required=True, type=str, location='json') - class CredentialDetail(CredentialParse, CredentialClassNameValidate, DetailViewSet): """凭据详情""" model = Credential fields = CredentialDetailFields - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=False, type=str, location='json') - class CredentialClassViews(CredentialParse, CredentialClassNameValidate, ListCreateViewSet): """凭据列表,带 class_name 参数""" @@ -64,17 +58,9 @@ class CredentialClassViews(CredentialParse, CredentialClassNameValidate, ListCre fields = CredentialFields filter_fields = (("name", "icontains"),) - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=True, type=str, location='json') - class CredentialClassDetail(CredentialParse, CredentialClassNameValidate, RetrieveClassMixin, DestroyClassMixin, UpdateClassMixin): """凭据详情,带 class_name 和 pk 参数""" model = Credential fields = CredentialDetailFields - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=False, type=str, location='json') diff --git a/src/controller/asset/host.py b/src/controller/asset/host.py new file mode 100644 index 0000000..1db5dd8 --- /dev/null +++ b/src/controller/asset/host.py @@ -0,0 +1,56 @@ +import datetime +import logging + +from flask import request +from flask_restful import reqparse + +from models.asset import fields as assetField +from models.asset import models as assetModel +from common.views import ListCreateViewSet, DetailViewSet +from common.permission import session_or_token_required + +logger = logging.getLogger("views") + + +class HostParse: + model = None + request_parse = None + uniq_fields = ("public_ip", "minion_id") + + def __init__(self): + # 创建时必要的参数用此变量判断,更新默认都可以不传 + required = request.method == "POST" + self.request_parse = reqparse.RequestParser() + # 创建时必须,修改时可选 + self.request_parse.add_argument("public_ip", type=str, required=required, + help='not public_ip provided', location='json') + self.request_parse.add_argument("private_ip", required=False, type=str, location='json') + self.request_parse.add_argument("minion_id", required=False, type=str, location='json') + self.request_parse.add_argument("weights", required=False, type=int, location='json') + self.request_parse.add_argument("cpu_num", required=False, type=int, location='json') + self.request_parse.add_argument("cpu_core", required=False, type=int, location='json') + self.request_parse.add_argument("memory", required=False, type=int, location='json') + self.request_parse.add_argument("tags", required=False, type=list, location='json') + self.request_parse.add_argument("data", required=False, type=dict, location='json') + self.request_parse.add_argument("labels", required=False, type=dict, location='json') + + def validate_fields(self, args: dict, create=True) -> dict: + if create: + args["created"] = datetime.datetime.now() + else: + if "created" in args: + args.pop("created") + return args + + +class HostViews(HostParse, ListCreateViewSet): + model = assetModel.Host + fields = assetField.HostFields + method_decorators = [session_or_token_required] + filter_fields = (("public_ip", "contains"), ("private_ip", "contains"), ("tags", "")) + + +class HostDetailViews(HostParse, DetailViewSet): + model = assetModel.Host + fields = assetField.HostFields + method_decorators = [session_or_token_required] diff --git a/src/controller/asset/instance.py b/src/controller/asset/instance.py index 1871250..9fb5390 100644 --- a/src/controller/asset/instance.py +++ b/src/controller/asset/instance.py @@ -1,3 +1,4 @@ +from flask import request from flask_restful import reqparse from models.asset.middleware import Middleware @@ -16,8 +17,11 @@ class InstanceParse: # 给子类用的唯一字段,用于校验 uniq_fields = (("name", "class_name"),) - def init_parse(self): + def __init__(self): + # 创建时必要的参数用此变量判断,更新默认都可以不传 + required = request.method == "POST" self.request_parse = reqparse.RequestParser() + self.request_parse.add_argument("name", required=required, type=str, location='json') self.request_parse.add_argument("class_name", required=False, type=str, location='json') self.request_parse.add_argument("middleware_id", required=False, type=str, location='json') self.request_parse.add_argument("credentials", required=False, type=list, location='json') @@ -54,29 +58,17 @@ class InstanceViews(InstanceParse, ListCreateViewSet): fields = InstanceFields filter_fields = (("name", "icontains"), ("class_name", "")) - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=True, type=str, location='json') - class InstanceDetailViews(InstanceParse, DetailViewSet): model = Instance fields = InstanceDetailFields - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=False, type=str, location='json') - class InstanceClassViews(InstanceParse, InstanceClassNameValidate, ListCreateViewSet): """某类别的实例列表""" model = Instance fields = InstanceFields - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=True, type=str, location='json') - def get_queryset(self, *args, **kwargs): self.queryset = self.model.objects(**kwargs) @@ -86,9 +78,5 @@ class InstanceClassDetail(InstanceParse, InstanceClassNameValidate, RetrieveClas model = Instance fields = InstanceDetailFields - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=False, type=str, location='json') - def get_queryset(self, *args, **kwargs): self.queryset = self.model.objects(**kwargs) diff --git a/src/controller/asset/middleware.py b/src/controller/asset/middleware.py index d1007f9..8213627 100644 --- a/src/controller/asset/middleware.py +++ b/src/controller/asset/middleware.py @@ -1,3 +1,4 @@ +from flask import request from flask_restful import reqparse from models.asset.middleware import Middleware @@ -16,7 +17,10 @@ class MiddlewareParse: uniq_fields = ("name", "host") def init_parse(self): + # 创建时必要的参数用此变量判断,更新默认都可以不传 + required = request.method == "POST" self.request_parse = reqparse.RequestParser() + self.request_parse.add_argument("name", required=required, type=str, location='json') self.request_parse.add_argument("class_name", required=False, type=str, location='json') self.request_parse.add_argument("host", required=False, type=str, location='json') @@ -46,10 +50,6 @@ class MiddlewareViews(MiddlewareParse, ListCreateViewSet): uniq_fields = ("name",) filter_fields = (("name", "icontains"), ("host", "icontains"), ("manage", "icontains"), ("class_name", "")) - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=True, type=str, location='json') - class MiddlewareDetail(MiddlewareParse, DetailViewSet): """分类别的视图""" @@ -57,10 +57,6 @@ class MiddlewareDetail(MiddlewareParse, DetailViewSet): fields = MiddlewareFields uniq_fields = ("name",) - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=True, type=str, location='json') - class MiddlewareClassViews(MiddlewareParse, MiddlewareClassNameValidate, ListCreateViewSet): """按分类的中间件视图,带 class_name 参数""" @@ -69,10 +65,6 @@ class MiddlewareClassViews(MiddlewareParse, MiddlewareClassNameValidate, ListCre uniq_fields = ("name",) filter_fields = (("name", "icontains"), ("host", "icontains"), ("manage", "icontains")) - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=True, type=str, location='json') - def get_queryset(self, *args, **kwargs): """按分类查找""" self.queryset = self.model.objects(**kwargs) @@ -84,7 +76,3 @@ class MiddlewareClassDetail(MiddlewareParse, MiddlewareClassNameValidate, model = Middleware fields = MiddlewareFields uniq_fields = ("name",) - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=False, type=str, location='json') diff --git a/src/controller/asset/parsers.py b/src/controller/asset/parsers.py deleted file mode 100644 index b3aaaa1..0000000 --- a/src/controller/asset/parsers.py +++ /dev/null @@ -1,71 +0,0 @@ -import datetime - -from flask_restful import reqparse - - -class HostParse: - model = None - request_parse = None - uniq_fields = ("public_ip", "minion_id") - - def init_parse(self): - self.request_parse = reqparse.RequestParser() - # 创建时必须,修改时可选 - # self.request_parse.add_argument("public_ip", type=str, required=True, - # help='not public_ip provided', location='json') - self.request_parse.add_argument("private_ip", required=False, type=str, location='json') - self.request_parse.add_argument("minion_id", required=False, type=str, location='json') - self.request_parse.add_argument("weights", required=False, type=int, location='json') - self.request_parse.add_argument("cpu_num", required=False, type=int, location='json') - self.request_parse.add_argument("cpu_core", required=False, type=int, location='json') - self.request_parse.add_argument("memory", required=False, type=int, location='json') - self.request_parse.add_argument("tags", required=False, type=list, location='json') - self.request_parse.add_argument("data", required=False, type=dict, location='json') - self.request_parse.add_argument("labels", required=False, type=dict, location='json') - - def validate_fields(self, args: dict, create=True) -> dict: - if create: - args["created"] = datetime.datetime.now() - else: - if "created" in args: - args.pop("created") - return args - - -class DatabaseServerParse: - request_parse = None - # 给子类用的唯一字段,用于校验 - uniq_fields = ("name", "host", "domain") - - def init_parse(self): - self.request_parse = reqparse.RequestParser() - self.request_parse.add_argument("domain", required=False, type=str, location='json') - self.request_parse.add_argument("data", required=False, type=dict, location='json') - self.request_parse.add_argument("tags", required=False, type=list, location='json') - self.request_parse.add_argument("labels", required=False, type=dict, location='json') - - -class DatabaseParse: - request_parse = None - - def init_parse(self): - self.request_parse = reqparse.RequestParser() - self.request_parse.add_argument("username", type=str, location='json') - self.request_parse.add_argument("password", type=str, location='json') - - self.request_parse.add_argument("data", required=False, type=dict, location='json') - self.request_parse.add_argument("tags", required=False, type=list, location='json') - self.request_parse.add_argument("labels", required=False, type=dict, location='json') - - -class MiddlewareParse: - request_parse = None - # 给子类用的唯一字段,用于校验 - uniq_fields = ("name", "host") - - def init_parse(self): - self.request_parse = reqparse.RequestParser() - # self.request_parse.add_argument("domain", required=False, type=str, location='json') - self.request_parse.add_argument("data", required=False, type=dict, location='json') - self.request_parse.add_argument("tags", required=False, type=list, location='json') - self.request_parse.add_argument("labels", required=False, type=dict, location='json') diff --git a/src/controller/asset/views.py b/src/controller/asset/views.py deleted file mode 100644 index 43262fd..0000000 --- a/src/controller/asset/views.py +++ /dev/null @@ -1,284 +0,0 @@ -import datetime -import logging - -from flask_restful import reqparse, marshal, Resource - -from models.asset import fields as assetField -from models.asset import models as assetModel -from common.views import ( - ListCreateViewSet, DetailViewSet, ListMixin, UpdateMixin, DestroyMixin, RetrieveMixin, - EncryptRequiredCreateView, EncryptRequiredUpdateView -) -from common.permission import session_or_token_required -from common.utils import abort_response -from controller.asset import parsers -from common.crypto import quick_crypto - -logger = logging.getLogger("views") - - -class HostViews(parsers.HostParse, ListCreateViewSet): - model = assetModel.Host - fields = assetField.HostFields - method_decorators = [session_or_token_required] - filter_fields = (("public_ip", "contains"), ("private_ip", "contains"), ("tags", "")) - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("public_ip", type=str, required=True, - help='not public_ip provided', location='json') - super(HostViews, self).__init__() - - -class HostDetailViews(parsers.HostParse, DetailViewSet): - model = assetModel.Host - fields = assetField.HostFields - method_decorators = [session_or_token_required] - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("public_ip", type=str, location='json') - super(HostDetailViews, self).__init__() - - -class MySQLInstanceViews(parsers.DatabaseServerParse, ListMixin, EncryptRequiredCreateView): - model = assetModel.MySQLInstance - fields = assetField.MySQLInstanceFields - method_decorators = [session_or_token_required] - filter_fields = (("name", "icontains"), ("host", "icontains"), ("manage", ""), ("tags", ""), - ("databases__name", ""), ) - encrypt_fields = ["password"] - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=True, type=str, location='json') - self.request_parse.add_argument("host", required=True, type=str, location='json') - self.request_parse.add_argument("manage", required=True, type=str, location='json') - - self.request_parse.add_argument("port", required=False, type=str, location='json') - self.request_parse.add_argument("username", required=True, type=str, location='json') - self.request_parse.add_argument("password", required=True, type=str, location='json') - self.request_parse.add_argument("storage", required=True, type=int, location='json') - self.request_parse.add_argument("memory", required=True, type=int, location='json') - self.request_parse.add_argument("core", required=True, type=int, location='json') - super(MySQLInstanceViews, self).__init__() - - -class MySQLInstanceDetail(parsers.DatabaseServerParse, RetrieveMixin, DestroyMixin, EncryptRequiredUpdateView): - model = assetModel.MySQLInstance - fields = assetField.MySQLInstanceFields - method_decorators = [session_or_token_required] - encrypt_fields = ["password"] - - def __init__(self): - """对象修改的参数解析""" - self.init_parse() - self.request_parse.add_argument("host", required=False, type=str, location='json') - self.request_parse.add_argument("name", required=False, type=str, location='json') - self.request_parse.add_argument("manage", required=False, type=str, location='json') - - self.request_parse.add_argument("port", required=False, type=str, location='json') - self.request_parse.add_argument("username", required=False, type=str, location='json') - self.request_parse.add_argument("password", required=False, type=str, location='json') - self.request_parse.add_argument("storage", required=False, type=int, location='json') - self.request_parse.add_argument("memory", required=False, type=int, location='json') - self.request_parse.add_argument("core", required=False, type=int, location='json') - super(MySQLInstanceDetail, self).__init__() - - -class DatabaseViews(parsers.DatabaseParse, Resource): - model = assetModel.DatabaseServer - db_model = assetModel.Database - db_fields = assetField.DatabaseFields - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", type=str, location='json', required=True) - - def post(self, pk): - """创建实例中的内嵌数据库对象""" - # 解析参数 - args = self.request_parse.parse_args() - - # 找到数据库服务器示例,传入的pk是数据库实例的id - try: - db_server = assetModel.DatabaseServer.objects(id=pk).first_or_404(message="db instance not found.") - except: - abort_response(404, code=1404, msg="db instance not found.") - return - - # 库名不能重复 - name = args.get("name") - exists = db_server.databases.filter(name=name).first() - if exists: - abort_response(400, 1400, msg=f"数据库{name}在实例中已存在!") - - # 加密存储密码 - if "password" in args: - password = args["password"] - if password: - args["password"] = quick_crypto(password) - - # 保存对象,追加到实例的数据库列表中 - try: - obj = self.db_model(**args) - db_server.databases.append(obj) - db_server.save() - except Exception as e: - logger.exception(f"{self.db_model} 创建对象失败! data={args}") - abort_response(500, 1500, msg=f"保存对象失败!{str(e)}") - return - # 返回创建信息 - return marshal(obj, self.db_fields) - - -class DatabaseDetailViews(parsers.DatabaseParse, Resource): - model = assetModel.DatabaseServer - db_model = assetModel.Database - db_fields = assetField.DatabaseFields - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", type=str, location='json', required=True) - - def put(self, pk, db): - """创建实例中的内嵌数据库对象""" - # 解析参数 - args = self.request_parse.parse_args() - # 找到数据库服务器示例,传入的pk是数据库实例的id,db为内嵌数据库列表的对象id - try: - db_server = assetModel.DatabaseServer.objects(id=pk).first_or_404(message="db instance not found.") - db_obj = db_server.databases.filter(id=db).first() - assert db_obj - except Exception as e: - print(e) - abort_response(404, code=1404, msg="db not found.") - return - name = args.get("name") - if name: - exists = db_server.databases.filter(name=name).first() - if exists and exists.id != db_obj.id: - abort_response(400, 1400, msg=f"数据库{name}在实例中已存在!") - - # 若更新密码,重新加密保存 - if "password" in args: - password = args["password"] - if password != db_obj.password: - args["password"] = quick_crypto(password) - # 去除id - args.pop("id", "") - - # 更新内嵌对象 - try: - db_server.databases.filter(id=db).update(**args) - db_server.save() - db_server.reload() - except Exception as e: - logger.exception(f"{self.db_model} 更新对象失败! data={args}") - abort_response(500, 1500, msg=f"更新对象失败!{str(e)}") - return - # 重载数据 - db_obj = db_server.databases.filter(id=db).first() - # 返回信息 - return marshal(db_obj, self.db_fields) - - -class RedisInstanceViews(parsers.DatabaseServerParse, ListMixin, EncryptRequiredCreateView): - model = assetModel.RedisInstance - fields = assetField.RedisInstanceFields - method_decorators = [session_or_token_required] - filter_fields = (("name", "icontains"), ("host", "icontains"), ("manage", ""), ("tags", "")) - encrypt_fields = ["password"] - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=True, type=str, location='json') - self.request_parse.add_argument("host", required=True, type=str, location='json') - self.request_parse.add_argument("manage", required=True, type=str, location='json') - - self.request_parse.add_argument("port", required=False, type=str, location='json') - self.request_parse.add_argument("memory", required=True, type=str, location='json') - self.request_parse.add_argument("password", required=False, type=str, location='json') - self.request_parse.add_argument("replicas", required=False, type=int, location='json') - super(RedisInstanceViews, self).__init__() - - -class RedisInstanceDetail(parsers.DatabaseServerParse, DestroyMixin, RetrieveMixin, EncryptRequiredUpdateView): - model = assetModel.RedisInstance - fields = assetField.RedisInstanceFields - method_decorators = [session_or_token_required] - encrypt_fields = ["password"] - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", required=False, type=str, location='json') - self.request_parse.add_argument("host", required=False, type=str, location='json') - self.request_parse.add_argument("manage", required=False, type=str, location='json') - - self.request_parse.add_argument("port", required=False, type=str, location='json') - self.request_parse.add_argument("memory", required=False, type=str, location='json') - self.request_parse.add_argument("password", required=False, type=str, location='json') - self.request_parse.add_argument("replicas", required=False, type=int, location='json') - super().__init__() - - -class NginxInstanceViews(parsers.MiddlewareParse, ListCreateViewSet): - model = assetModel.NginxInstance - fields = assetField.NginxInstanceFields - filter_fields = (("host", "icontains"), ("manage", ""), ("url", "icontains"), ("tags", "")) - method_decorators = [session_or_token_required] - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("host", required=True, type=str, location='json') - self.request_parse.add_argument("manage", required=True, type=str, location='json') - - self.request_parse.add_argument("port", required=False, type=str, location='json') - self.request_parse.add_argument("url", required=True, type=str, location='json') - super().__init__() - - -class NginxInstanceDetail(parsers.MiddlewareParse, DetailViewSet): - model = assetModel.NginxInstance - fields = assetField.NginxInstanceFields - method_decorators = [session_or_token_required] - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("host", required=False, type=str, location='json') - self.request_parse.add_argument("manage", required=False, type=str, location='json') - - self.request_parse.add_argument("port", required=False, type=str, location='json') - self.request_parse.add_argument("url", required=False, type=str, location='json') - super().__init__() - - -class CDNViews(ListCreateViewSet): - model = assetModel.CDN - fields = assetField.CDNFields - uniq_fields = ("domain",) - filter_fields = (("domain", "icontains"), ("tags", ""),) - method_decorators = [session_or_token_required] - - def __init__(self): - self.request_parse = reqparse.RequestParser() - self.request_parse.add_argument("domain", required=True, type=str, location='json') - - self.request_parse.add_argument("data", required=False, type=dict, location='json') - self.request_parse.add_argument("tags", required=False, type=list, location='json') - self.request_parse.add_argument("labels", required=False, type=dict, location='json') - - -class CDNDetail(DetailViewSet): - model = assetModel.CDN - fields = assetField.CDNFields - uniq_fields = ("domain",) - method_decorators = [session_or_token_required] - - def __init__(self): - self.request_parse = reqparse.RequestParser() - self.request_parse.add_argument("domain", required=False, type=str, location='json') - - self.request_parse.add_argument("data", required=False, type=dict, location='json') - self.request_parse.add_argument("tags", required=False, type=list, location='json') - self.request_parse.add_argument("labels", required=False, type=dict, location='json') diff --git a/src/controller/project/parsers.py b/src/controller/project/parsers.py index 3f10b8f..d6c77a4 100644 --- a/src/controller/project/parsers.py +++ b/src/controller/project/parsers.py @@ -3,19 +3,21 @@ 有使用到该父类的部分方法,主要抽出部分请求参数定义、解析后的进一步校验,供 `post` 和 `put 请求方法使用 """ -from flask import current_app as app -from flask_restful import reqparse +from flask import request +from flask_restful import reqparse, inputs -from models.asset import models as assetModel from models.project import models as projectModel -from common.utils import abort_response class ProjectParse: request_parse = None - def init_parse(self): + def __init__(self): + # 创建时必要的参数用此变量判断,更新默认都可以不传 + required = request.method == "POST" self.request_parse = reqparse.RequestParser() + self.request_parse.add_argument("name", type=inputs.regex(r'^\w{4}$'), location='json', required=required) + self.request_parse.add_argument("fork", type=inputs.regex(r'^\w{2}$'), location='json', required=required) self.request_parse.add_argument("domain", type=str, location='json') self.request_parse.add_argument("www_ip", type=str, location='json') self.request_parse.add_argument("ops_ip", type=str, location='json') @@ -32,8 +34,12 @@ class ProjectParse: class ChannelParse: request_parse = None - def init_parse(self): + def __init__(self): + # 创建时必要的参数用此变量判断,更新默认都可以不传 + required = request.method == "POST" self.request_parse = reqparse.RequestParser() + self.request_parse.add_argument("spid", type=str, location='json', required=required) + self.request_parse.add_argument("project_id", type=str, location='json', required=required) self.request_parse.add_argument("name", type=str, location='json') self.request_parse.add_argument("version", type=dict, location='json') @@ -59,15 +65,21 @@ class ServerParse: """views 中使用的解析、校验方法""" request_parse = None - def init_parse(self): + def __init__(self): + # 创建时必要的参数用此变量判断,更新默认都可以不传 + required = request.method == "POST" self.request_parse = reqparse.RequestParser() + + self.request_parse.add_argument("num", type=int, location='json', required=required) + self.request_parse.add_argument("channel_id", type=str, location='json', required=required) + self.request_parse.add_argument("data", type=dict, location='json') self.request_parse.add_argument("tags", type=list, location='json') self.request_parse.add_argument("labels", type=dict, location='json') self.request_parse.add_argument("host_id", type=str, location='json') - self.request_parse.add_argument("game_db_id", type=str, location='json') - self.request_parse.add_argument("admin_db_id", type=str, location='json') + # self.request_parse.add_argument("game_db_id", type=str, location='json') + # self.request_parse.add_argument("admin_db_id", type=str, location='json') self.request_parse.add_argument("domain", type=str, location='json', default="") # status是枚举 self.request_parse.add_argument("status", choices=projectModel.Server.STATUS.keys(), @@ -85,16 +97,16 @@ class ServerParse: for field in projectModel.Version._fields: defaults[field] = version.get(field, "") args["version"] = projectModel.Version(**defaults) - game_db_id = args.get("game_db_id") - if game_db_id: - try: - assert assetModel.DatabaseServer.objects(databases__id=game_db_id).first() - except: - abort_response(400, 1400, msg="game_db_id not exists") - admin_db_id = args.get("admin_db_id") - if admin_db_id: - try: - assert assetModel.DatabaseServer.objects(databases__id=admin_db_id).first() - except: - abort_response(400, 1400, msg="admin_db_id not exists") + # game_db_id = args.get("game_db_id") + # if game_db_id: + # try: + # assert assetModel.DatabaseServer.objects(databases__id=game_db_id).first() + # except: + # abort_response(400, 1400, msg="game_db_id not exists") + # admin_db_id = args.get("admin_db_id") + # if admin_db_id: + # try: + # assert assetModel.DatabaseServer.objects(databases__id=admin_db_id).first() + # except: + # abort_response(400, 1400, msg="admin_db_id not exists") return args diff --git a/src/controller/project/views.py b/src/controller/project/views.py index f79690e..1a0a3e8 100644 --- a/src/controller/project/views.py +++ b/src/controller/project/views.py @@ -19,11 +19,6 @@ class ProjectViews(parsers.ProjectParse, ListMixin, CreateMixin): method_decorators = [session_or_token_required] filter_fields = (("name", ""), ("fork", ""), ("ops_ip", ""), ("domain", "icontains"), ("tags", "")) - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", type=inputs.regex(r'^\w{4}$'), location='json', required=True) - self.request_parse.add_argument("fork", type=inputs.regex(r'^\w{2}$'), location='json', required=True) - class ProjectDetailViews(parsers.ProjectParse, DetailViewSet): model = Project @@ -31,11 +26,6 @@ class ProjectDetailViews(parsers.ProjectParse, DetailViewSet): uniq_fields = (("name", "fork"),) method_decorators = [session_or_token_required] - def __init__(self): - self.init_parse() - self.request_parse.add_argument("name", type=inputs.regex(r'^\w{4}$'), location='json', required=False) - self.request_parse.add_argument("fork", type=inputs.regex(r'^\w{2}$'), location='json', required=False) - class ChannelViews(parsers.ChannelParse, ListCreateViewSet): model = Channel @@ -45,12 +35,6 @@ class ChannelViews(parsers.ChannelParse, ListCreateViewSet): method_decorators = [session_or_token_required] filter_fields = (("name", ""), ("spid", ""), ("tags", "")) - def __init__(self): - self.init_parse() - self.request_parse.add_argument("spid", type=str, location='json', required=True) - self.request_parse.add_argument("project_id", type=str, location='json', required=True) - super().__init__() - def get_queryset(self): self.queryset = self.model.objects project_full_name = request.args.get("project") @@ -71,12 +55,6 @@ class ChannelDetailViews(parsers.ChannelParse, DetailViewSet): relation_fields = (("project_id", Project, True),) method_decorators = [session_or_token_required] - def __init__(self): - self.init_parse() - self.request_parse.add_argument("spid", type=str, location='json', required=False) - self.request_parse.add_argument("project_id", type=str, location='json', required=False) - super().__init__() - class ServerViews(parsers.ServerParse, ListCreateViewSet): model = Server @@ -86,11 +64,6 @@ class ServerViews(parsers.ServerParse, ListCreateViewSet): relation_fields = (("host_id", assetModel.Host, ""), ("channel_id", Channel, True)) filter_fields = (("num", ""), ("spid", ""), ("tags", ""), ("channel_id", ""), ("host_id", "")) - def __init__(self): - self.init_parse() - self.request_parse.add_argument("num", type=int, location='json', required=True) - self.request_parse.add_argument("channel_id", type=str, location='json', required=True) - def get_queryset(self): """这些都是有关联的查询,模型内部字段的匹配字段放在 `filter_fields` 中""" project = None @@ -122,8 +95,3 @@ class ServerDetailView(parsers.ServerParse, DetailViewSet): uniq_fields = (("num", "channel_id"),) method_decorators = [session_or_token_required] relation_fields = (("host_id", assetModel.Host, ""), ("channel_id", Channel, True)) - - def __init__(self): - self.init_parse() - self.request_parse.add_argument("num", type=int, location='json') - self.request_parse.add_argument("channel_id", type=str, location='json')