简化接口中模型必要的参数的解析,根据请求方法判断,更新可缺少

删除数据库相关的模型、解析方法、视图和路由,归类到中间件和实例中
This commit is contained in:
chenzuoqing 2021-12-27 16:58:53 +08:00
parent b354fe14bf
commit f9d08d0125
11 changed files with 108 additions and 465 deletions

View File

@ -1,7 +1,7 @@
from flask import Blueprint from flask import Blueprint
from flask_restful import Api from flask_restful import Api
from controller.asset import views from controller.asset import host
from controller.asset import instance from controller.asset import instance
from controller.asset import middleware from controller.asset import middleware
from controller.asset import credential from controller.asset import credential
@ -11,8 +11,8 @@ asset = Blueprint('asset', __name__, url_prefix="/asset")
# 增加路由 # 增加路由
api = Api(asset) api = Api(asset)
api.add_resource(views.HostViews, '/host/', endpoint="host") api.add_resource(host.HostViews, '/host/', endpoint="host")
api.add_resource(views.HostDetailViews, '/host/<string:pk>/', endpoint="host-detail") api.add_resource(host.HostDetailViews, '/host/<string:pk>/', endpoint="host-detail")
# 凭据相关视图 # 凭据相关视图
api.add_resource(credential.CredentialViews, '/credential/', endpoint="cred-all") api.add_resource(credential.CredentialViews, '/credential/', endpoint="cred-all")

View File

@ -1,5 +1,5 @@
from flask_restful import marshal from flask_restful import marshal
from common.serializer import marshal as marshal_fields from common.serializer import marshal_fields
from functools import reduce from functools import reduce

View File

@ -1,7 +1,8 @@
from flask_restful import marshal
from collections import OrderedDict 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 """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. 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)) # else make(v).output(k, data))
# for k, v in fields.items()) # for k, v in fields.items())
items = ((k, v) for k, v in map(parse, fields.items()) if k is not None) 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) return OrderedDict([(envelope, OrderedDict(items))]) if envelope else OrderedDict(items)

View File

@ -14,8 +14,11 @@ class CredentialParse:
# 给子类用的唯一字段,用于校验 # 给子类用的唯一字段,用于校验
# uniq_fields = ("name", "host") # uniq_fields = ("name", "host")
def init_parse(self): def __init__(self):
# 创建时必要的参数用此变量判断,更新默认都可以不传
required = request.method == "POST"
self.request_parse = reqparse.RequestParser() 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("class_name", required=False, type=str, location='json')
@ -42,21 +45,12 @@ class CredentialViews(CredentialParse, ListCreateViewSet):
fields = CredentialFields fields = CredentialFields
filter_fields = (("name", "icontains"), ) 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): class CredentialDetail(CredentialParse, CredentialClassNameValidate, DetailViewSet):
"""凭据详情""" """凭据详情"""
model = Credential model = Credential
fields = CredentialDetailFields 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 CredentialClassViews(CredentialParse, CredentialClassNameValidate, ListCreateViewSet):
"""凭据列表,带 class_name 参数""" """凭据列表,带 class_name 参数"""
@ -64,17 +58,9 @@ class CredentialClassViews(CredentialParse, CredentialClassNameValidate, ListCre
fields = CredentialFields fields = CredentialFields
filter_fields = (("name", "icontains"),) 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, class CredentialClassDetail(CredentialParse, CredentialClassNameValidate,
RetrieveClassMixin, DestroyClassMixin, UpdateClassMixin): RetrieveClassMixin, DestroyClassMixin, UpdateClassMixin):
"""凭据详情,带 class_name 和 pk 参数""" """凭据详情,带 class_name 和 pk 参数"""
model = Credential model = Credential
fields = CredentialDetailFields fields = CredentialDetailFields
def __init__(self):
self.init_parse()
self.request_parse.add_argument("name", required=False, type=str, location='json')

View File

@ -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]

View File

@ -1,3 +1,4 @@
from flask import request
from flask_restful import reqparse from flask_restful import reqparse
from models.asset.middleware import Middleware from models.asset.middleware import Middleware
@ -16,8 +17,11 @@ class InstanceParse:
# 给子类用的唯一字段,用于校验 # 给子类用的唯一字段,用于校验
uniq_fields = (("name", "class_name"),) uniq_fields = (("name", "class_name"),)
def init_parse(self): def __init__(self):
# 创建时必要的参数用此变量判断,更新默认都可以不传
required = request.method == "POST"
self.request_parse = reqparse.RequestParser() 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("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("middleware_id", required=False, type=str, location='json')
self.request_parse.add_argument("credentials", required=False, type=list, location='json') self.request_parse.add_argument("credentials", required=False, type=list, location='json')
@ -54,29 +58,17 @@ class InstanceViews(InstanceParse, ListCreateViewSet):
fields = InstanceFields fields = InstanceFields
filter_fields = (("name", "icontains"), ("class_name", "")) 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): class InstanceDetailViews(InstanceParse, DetailViewSet):
model = Instance model = Instance
fields = InstanceDetailFields 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): class InstanceClassViews(InstanceParse, InstanceClassNameValidate, ListCreateViewSet):
"""某类别的实例列表""" """某类别的实例列表"""
model = Instance model = Instance
fields = InstanceFields 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): def get_queryset(self, *args, **kwargs):
self.queryset = self.model.objects(**kwargs) self.queryset = self.model.objects(**kwargs)
@ -86,9 +78,5 @@ class InstanceClassDetail(InstanceParse, InstanceClassNameValidate, RetrieveClas
model = Instance model = Instance
fields = InstanceDetailFields 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): def get_queryset(self, *args, **kwargs):
self.queryset = self.model.objects(**kwargs) self.queryset = self.model.objects(**kwargs)

View File

@ -1,3 +1,4 @@
from flask import request
from flask_restful import reqparse from flask_restful import reqparse
from models.asset.middleware import Middleware from models.asset.middleware import Middleware
@ -16,7 +17,10 @@ class MiddlewareParse:
uniq_fields = ("name", "host") uniq_fields = ("name", "host")
def init_parse(self): def init_parse(self):
# 创建时必要的参数用此变量判断,更新默认都可以不传
required = request.method == "POST"
self.request_parse = reqparse.RequestParser() 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("class_name", required=False, type=str, location='json')
self.request_parse.add_argument("host", 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",) uniq_fields = ("name",)
filter_fields = (("name", "icontains"), ("host", "icontains"), ("manage", "icontains"), ("class_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): class MiddlewareDetail(MiddlewareParse, DetailViewSet):
"""分类别的视图""" """分类别的视图"""
@ -57,10 +57,6 @@ class MiddlewareDetail(MiddlewareParse, DetailViewSet):
fields = MiddlewareFields fields = MiddlewareFields
uniq_fields = ("name",) 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 MiddlewareClassViews(MiddlewareParse, MiddlewareClassNameValidate, ListCreateViewSet):
"""按分类的中间件视图,带 class_name 参数""" """按分类的中间件视图,带 class_name 参数"""
@ -69,10 +65,6 @@ class MiddlewareClassViews(MiddlewareParse, MiddlewareClassNameValidate, ListCre
uniq_fields = ("name",) uniq_fields = ("name",)
filter_fields = (("name", "icontains"), ("host", "icontains"), ("manage", "icontains")) 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): def get_queryset(self, *args, **kwargs):
"""按分类查找""" """按分类查找"""
self.queryset = self.model.objects(**kwargs) self.queryset = self.model.objects(**kwargs)
@ -84,7 +76,3 @@ class MiddlewareClassDetail(MiddlewareParse, MiddlewareClassNameValidate,
model = Middleware model = Middleware
fields = MiddlewareFields fields = MiddlewareFields
uniq_fields = ("name",) uniq_fields = ("name",)
def __init__(self):
self.init_parse()
self.request_parse.add_argument("name", required=False, type=str, location='json')

View File

@ -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')

View File

@ -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是数据库实例的iddb为内嵌数据库列表的对象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')

View File

@ -3,19 +3,21 @@
有使用到该父类的部分方法主要抽出部分请求参数定义解析后的进一步校验 `post` `put 请求方法使用 有使用到该父类的部分方法主要抽出部分请求参数定义解析后的进一步校验 `post` `put 请求方法使用
""" """
from flask import current_app as app from flask import request
from flask_restful import reqparse from flask_restful import reqparse, inputs
from models.asset import models as assetModel
from models.project import models as projectModel from models.project import models as projectModel
from common.utils import abort_response
class ProjectParse: class ProjectParse:
request_parse = None request_parse = None
def init_parse(self): def __init__(self):
# 创建时必要的参数用此变量判断,更新默认都可以不传
required = request.method == "POST"
self.request_parse = reqparse.RequestParser() 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("domain", type=str, location='json')
self.request_parse.add_argument("www_ip", 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') self.request_parse.add_argument("ops_ip", type=str, location='json')
@ -32,8 +34,12 @@ class ProjectParse:
class ChannelParse: class ChannelParse:
request_parse = None request_parse = None
def init_parse(self): def __init__(self):
# 创建时必要的参数用此变量判断,更新默认都可以不传
required = request.method == "POST"
self.request_parse = reqparse.RequestParser() 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("name", type=str, location='json')
self.request_parse.add_argument("version", type=dict, location='json') self.request_parse.add_argument("version", type=dict, location='json')
@ -59,15 +65,21 @@ class ServerParse:
"""views 中使用的解析、校验方法""" """views 中使用的解析、校验方法"""
request_parse = None request_parse = None
def init_parse(self): def __init__(self):
# 创建时必要的参数用此变量判断,更新默认都可以不传
required = request.method == "POST"
self.request_parse = reqparse.RequestParser() 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("data", type=dict, location='json')
self.request_parse.add_argument("tags", type=list, 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("labels", type=dict, location='json')
self.request_parse.add_argument("host_id", type=str, 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("game_db_id", type=str, location='json')
self.request_parse.add_argument("admin_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="") self.request_parse.add_argument("domain", type=str, location='json', default="")
# status是枚举 # status是枚举
self.request_parse.add_argument("status", choices=projectModel.Server.STATUS.keys(), self.request_parse.add_argument("status", choices=projectModel.Server.STATUS.keys(),
@ -85,16 +97,16 @@ class ServerParse:
for field in projectModel.Version._fields: for field in projectModel.Version._fields:
defaults[field] = version.get(field, "") defaults[field] = version.get(field, "")
args["version"] = projectModel.Version(**defaults) args["version"] = projectModel.Version(**defaults)
game_db_id = args.get("game_db_id") # game_db_id = args.get("game_db_id")
if game_db_id: # if game_db_id:
try: # try:
assert assetModel.DatabaseServer.objects(databases__id=game_db_id).first() # assert assetModel.DatabaseServer.objects(databases__id=game_db_id).first()
except: # except:
abort_response(400, 1400, msg="game_db_id not exists") # abort_response(400, 1400, msg="game_db_id not exists")
admin_db_id = args.get("admin_db_id") # admin_db_id = args.get("admin_db_id")
if admin_db_id: # if admin_db_id:
try: # try:
assert assetModel.DatabaseServer.objects(databases__id=admin_db_id).first() # assert assetModel.DatabaseServer.objects(databases__id=admin_db_id).first()
except: # except:
abort_response(400, 1400, msg="admin_db_id not exists") # abort_response(400, 1400, msg="admin_db_id not exists")
return args return args

View File

@ -19,11 +19,6 @@ class ProjectViews(parsers.ProjectParse, ListMixin, CreateMixin):
method_decorators = [session_or_token_required] method_decorators = [session_or_token_required]
filter_fields = (("name", ""), ("fork", ""), ("ops_ip", ""), ("domain", "icontains"), ("tags", "")) 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): class ProjectDetailViews(parsers.ProjectParse, DetailViewSet):
model = Project model = Project
@ -31,11 +26,6 @@ class ProjectDetailViews(parsers.ProjectParse, DetailViewSet):
uniq_fields = (("name", "fork"),) uniq_fields = (("name", "fork"),)
method_decorators = [session_or_token_required] 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): class ChannelViews(parsers.ChannelParse, ListCreateViewSet):
model = Channel model = Channel
@ -45,12 +35,6 @@ class ChannelViews(parsers.ChannelParse, ListCreateViewSet):
method_decorators = [session_or_token_required] method_decorators = [session_or_token_required]
filter_fields = (("name", ""), ("spid", ""), ("tags", "")) 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): def get_queryset(self):
self.queryset = self.model.objects self.queryset = self.model.objects
project_full_name = request.args.get("project") project_full_name = request.args.get("project")
@ -71,12 +55,6 @@ class ChannelDetailViews(parsers.ChannelParse, DetailViewSet):
relation_fields = (("project_id", Project, True),) relation_fields = (("project_id", Project, True),)
method_decorators = [session_or_token_required] 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): class ServerViews(parsers.ServerParse, ListCreateViewSet):
model = Server model = Server
@ -86,11 +64,6 @@ class ServerViews(parsers.ServerParse, ListCreateViewSet):
relation_fields = (("host_id", assetModel.Host, ""), ("channel_id", Channel, True)) relation_fields = (("host_id", assetModel.Host, ""), ("channel_id", Channel, True))
filter_fields = (("num", ""), ("spid", ""), ("tags", ""), ("channel_id", ""), ("host_id", "")) 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): def get_queryset(self):
"""这些都是有关联的查询,模型内部字段的匹配字段放在 `filter_fields` 中""" """这些都是有关联的查询,模型内部字段的匹配字段放在 `filter_fields` 中"""
project = None project = None
@ -122,8 +95,3 @@ class ServerDetailView(parsers.ServerParse, DetailViewSet):
uniq_fields = (("num", "channel_id"),) uniq_fields = (("num", "channel_id"),)
method_decorators = [session_or_token_required] method_decorators = [session_or_token_required]
relation_fields = (("host_id", assetModel.Host, ""), ("channel_id", Channel, True)) 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')