Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

minor: 代码质量优化 --story=119534560 #1392

Merged
merged 2 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion iam/api/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,10 @@ def _http_request(
if not logger.isEnabledFor(logging.DEBUG) and len(content) > 200:
content = content[:200] + b"......"

message_format = "request: [method=`%s`, url=`%s`, data=`%s`] response: [status_code=`%s`, request_id=`%s`, content=`%s`]" # noqa
message_format = (
"request: [method=`%s`, url=`%s`, data=`%s`] "
"response: [status_code=`%s`, request_id=`%s`, content=`%s`]"
) # noqa
if resp.status_code != 200:
logger.error(
message_format
Expand Down
76 changes: 60 additions & 16 deletions iam/contrib/django/dispatcher/dispatchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,18 @@
from iam.resource.utils import get_page_obj, get_filter_obj
from iam.exceptions import AuthInvalidOperation

from iam.contrib.django.dispatcher.exceptions import InvalidPageException, KeywordTooShortException
from iam.contrib.django.dispatcher.exceptions import (
InvalidPageException,
KeywordTooShortException,
)

logger = logging.getLogger("iam")


def fail_response(code, message, request_id):
response = JsonResponse({"code": code, "result": False, "message": message, "data": None})
response = JsonResponse(
{"code": code, "result": False, "message": message, "data": None}
)
response["X-Request-Id"] = request_id
return response

Expand All @@ -52,14 +57,21 @@ def __init__(self, iam, system):

def register(self, provider_type, provider):
if not issubclass(type(provider), ResourceProvider):
raise AuthInvalidOperation("provider must be subclass of iam.resource.provider.ResourceProvider")
raise AuthInvalidOperation(
"provider must be subclass of iam.resource.provider.ResourceProvider"
)

if provider_type in self._provider:
raise AuthInvalidOperation("provider {} already been registered".format(provider_type))
raise AuthInvalidOperation(
"provider {} already been registered".format(provider_type)
)

self._provider[provider_type] = provider

def as_view(self, decorators=[]):
def as_view(self, decorators=None):
if decorators is None:
decorators = []

@csrf_exempt
def view(request):
return self._dispatch(request)
Expand All @@ -78,45 +90,69 @@ def _dispatch(self, request):
auth_allowed = self.iam.is_basic_auth_allowed(self.system, auth)

if not auth_allowed:
logger.error("resource request({}) auth failed with auth param: {}".format(request_id, auth))
logger.error(
"resource request({}) auth failed with auth param: {}".format(
request_id, auth
)
)
return fail_response(401, "basic auth failed", request_id)

# load json data
try:
data = json.loads(request.body)
except Exception:
logger.error("resource request({}) failed with invalid body: {}".format(request_id, request.body))
logger.error(
"resource request({}) failed with invalid body: {}".format(
request_id, request.body
)
)
return fail_response(400, "reqeust body is not a valid json", request_id)

# check basic params
method = data.get("method")
resource_type = data.get("type")
if not (method and resource_type):
logger.error("resource request({}) failed with invalid data: {}".format(request_id, data))
logger.error(
"resource request({}) failed with invalid data: {}".format(
request_id, data
)
)
return fail_response(400, "method and type is required field", request_id)

# check resource type
if resource_type not in self._provider:
logger.error(
"resource request({}) failed with unsupport resource type: {}".format(request_id, resource_type)
"resource request({}) failed with unsupport resource type: {}".format(
request_id, resource_type
)
)
return fail_response(
404, "unsupport resource type: {}".format(resource_type), request_id
)
return fail_response(404, "unsupport resource type: {}".format(resource_type), request_id)

# check method and process
processor = getattr(self, "_dispatch_{}".format(method), None)
if not processor:
logger.error("resource request({}) failed with unsupport method: {}".format(request_id, method))
logger.error(
"resource request({}) failed with unsupport method: {}".format(
request_id, method
)
)
return fail_response(404, "unsupport method: {}".format(method), request_id)

logger.info(
"resource request({}) with filter: {}, page: {}".format(request_id, data.get("filter"), data.get("page"))
"resource request({}) with filter: {}, page: {}".format(
request_id, data.get("filter"), data.get("page")
)
)
try:
return processor(request, data, request_id)
except InvalidPageException as e:
return fail_response(422, str(e), request_id)
except Exception as e:
logger.exception("resource request({}) failed with exception: {}".format(request_id, e))
logger.exception(
"resource request({}) failed with exception: {}".format(request_id, e)
)
return fail_response(500, str(e), request_id)

def _get_options(self, request):
Expand Down Expand Up @@ -154,7 +190,9 @@ def _dispatch_list_attr_value(self, request, data, request_id):
def _dispatch_list_instance(self, request, data, request_id):
options = self._get_options(request)

filter_obj = get_filter_obj(data.get("filter"), ["parent", "search", "resource_type_chain"])
filter_obj = get_filter_obj(
data.get("filter"), ["parent", "search", "resource_type_chain"]
)
page_obj = get_page_obj(data.get("page"))

provider = self._provider[data["type"]]
Expand Down Expand Up @@ -204,7 +242,9 @@ def _dispatch_search_instance(self, request, data, request_id):
filter_obj = get_filter_obj(data.get("filter"), ["parent", "keyword"])

if filter_obj.keyword is None or len(filter_obj.keyword) < 2:
raise KeywordTooShortException("the length of keyword should be greater than or equals to 2")
raise KeywordTooShortException(
"the length of keyword should be greater than or equals to 2"
)

page_obj = get_page_obj(data.get("page"))

Expand All @@ -216,7 +256,11 @@ def _dispatch_search_instance(self, request, data, request_id):

search_function = getattr(provider, "search_instance", None)
if not (search_function and callable(search_function)):
return fail_response(404, "resource type: {} not support search instance".format(data["type"]), request_id)
return fail_response(
404,
"resource type: {} not support search instance".format(data["type"]),
request_id,
)

result = provider.search_instance(filter_obj, page_obj, **options)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@

class Command(BaseCommand):

help = "Create new migration for specific iam migration json file e.g. python manage.py iam_makemigrations migration.json"
help = (
"Create new migration for specific iam migration json file "
"e.g. python manage.py iam_makemigrations migration.json"
)

def add_arguments(self, parser):
parser.add_argument("migration_json", nargs="?", type=str)
Expand All @@ -40,7 +43,9 @@ def handle(self, *args, **options):
sys.stderr.write("please provide a migration json file name\n")
exit(1)

json_path = getattr(settings, "BK_IAM_MIGRATION_JSON_PATH", "support-files/iam/")
json_path = getattr(
settings, "BK_IAM_MIGRATION_JSON_PATH", "support-files/iam/"
)
file_path = os.path.join(settings.BASE_DIR, json_path, json_file)

if not os.path.exists(file_path):
Expand All @@ -62,7 +67,11 @@ def handle(self, *args, **options):

migration_name = self.migration_name(last_migration_name)
migration_file = "{}.py".format(
os.path.join(settings.BASE_DIR, "iam/contrib/iam_migration/migrations", migration_name,)
os.path.join(
settings.BASE_DIR,
"iam/contrib/iam_migration/migrations",
migration_name,
)
)

with codecs.open(migration_file, mode="w", encoding="utf-8") as fp:
Expand All @@ -83,12 +92,16 @@ def migration_name(self, last_migration_name):
time = datetime.now().strftime("%Y%m%d%H%M")

if not system_id:
self.stderr.write("You must set BK_IAM_SYSTEM_ID in django settings before make migrations")
self.stderr.write(
"You must set BK_IAM_SYSTEM_ID in django settings before make migrations"
)
exit(1)

if not last_migration_name:
return "0001_initial"

code = "%04d" % (int(last_migration_name[:4]) + 1)

return "{code}_{system_id}_{time}".format(code=code, system_id=system_id, time=time)
return "{code}_{system_id}_{time}".format(
code=code, system_id=system_id, time=time
)
Loading
Loading