Skip to content

Commit

Permalink
fix: 修改Callable导入 TencentBlueKing#1464
Browse files Browse the repository at this point in the history
  • Loading branch information
huangpixu committed Jan 7, 2025
1 parent 40366f6 commit 53e1bf4
Showing 1 changed file with 61 additions and 36 deletions.
97 changes: 61 additions & 36 deletions itsm/component/esb/esbclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,18 @@

# 全平台 esb-sdk 封装,依赖于 esb-sdk 包,但不依赖 sdk 的版本。
# sdk 中有封装好 cc.get_app_by_user 方法时,可直接按以前 sdk 的习惯调用
#
#
# from blueapps.utils import client
# client.cc.get_app_by_user()
#
#
# from blueapps.utils import backend_client
# b_client = backend_client(access_token="SfgcGlBHmPWttwlGd7nOLAbOP3TAOG")
# b_client.cc.get_app_by_user()
#
#
# 当前版本 sdk 中未封装好,但 api 已经有 get_app_by_user 的时候。需要指定请求方法
# client.cc.get_app_by_user.get()

import collections
from collections.abc import Callable
import logging

from django.contrib.auth import get_user_model
Expand All @@ -50,11 +50,11 @@
from itsm.component.constants import API_PERMISSION_ERROR_CODE

__all__ = [
'client',
'backend_client',
'get_client_by_user',
'get_client_by_request',
'CustomComponentAPI',
"client",
"backend_client",
"get_client_by_user",
"get_client_by_request",
"CustomComponentAPI",
"client_backend",
]

Expand All @@ -79,7 +79,7 @@ def get_api_prefix():
if not ESB_SDK_NAME:
raise AttributeError
except AttributeError:
ESB_SDK_NAME = 'blueking.component.{platform}'.format(platform=settings.RUN_VER)
ESB_SDK_NAME = "blueking.component.{platform}".format(platform=settings.RUN_VER)


class SDKClient(object):
Expand All @@ -96,15 +96,15 @@ def __backend__(self):
def __new__(cls, **kwargs):
if cls.sdk_package is None:
try:
cls.sdk_package = __import__(ESB_SDK_NAME, fromlist=['shortcuts'])
cls.sdk_package = __import__(ESB_SDK_NAME, fromlist=["shortcuts"])
except ImportError as e:
raise ImportError("%s is not installed: %s" % (ESB_SDK_NAME, e))
return super(SDKClient, cls).__new__(cls)

def __init__(self, **kwargs):
self.mod_name = ""
self.sdk_mod = None
for ignored_field in ['app_code', 'app_secret']:
for ignored_field in ["app_code", "app_secret"]:
if ignored_field in kwargs:
kwargs.pop(ignored_field)
self.common_args = kwargs
Expand All @@ -114,7 +114,7 @@ def __getattr__(self, item):
ret = SDKClient(**self.common_args)
ret.mod_name = item
ret.setup_modules()
if isinstance(ret.sdk_mod, collections.Callable):
if isinstance(ret.sdk_mod, Callable):
return ret.sdk_mod
return ret
else:
Expand All @@ -123,7 +123,7 @@ def __getattr__(self, item):
if ret is None:
ret = ComponentAPICollection(self).add_api(item)

if not isinstance(ret, collections.Callable):
if not isinstance(ret, Callable):
ret = self
return _wrap_data_handler(ret)

Expand All @@ -134,20 +134,26 @@ def setup_modules(self):

@property
def sdk_client(self):
is_backend = self.common_args.pop('__backend__', False)
is_backend = self.common_args.pop("__backend__", False)
username = self.common_args.get("username", settings.SYSTEM_CALL_USER)
if is_backend:
try:
return self.load_sdk_class("shortcuts", "get_client_by_user")(username, **self.common_args)
return self.load_sdk_class("shortcuts", "get_client_by_user")(
username, **self.common_args
)
except Exception as err:
logger.exception("client call get_client_by_user failed, msg is {}".format(err))
logger.exception(
"client call get_client_by_user failed, msg is {}".format(err)
)
if settings.RUN_MODE != "DEVELOP":
if self.common_args:
return self.load_sdk_class("shortcuts", "get_client_by_user")(
settings.SYSTEM_CALL_USER, **self.common_args
)
else:
raise AccessForbidden("sdk can only be called through the Web request")
raise AccessForbidden(
"sdk can only be called through the Web request"
)
else:
# develop mode
# 根据RUN_VER获得get_component_client_common_args函数
Expand All @@ -163,14 +169,22 @@ def sdk_client(self):
request = get_request()
try:
# 调用sdk方法获取sdk client
return self.load_sdk_class("shortcuts", "get_client_by_request")(request)
return self.load_sdk_class("shortcuts", "get_client_by_request")(
request
)
except Exception as err:
logger.exception("client call get_client_by_request failed, msg is {}".format(err))
logger.exception(
"client call get_client_by_request failed, msg is {}".format(err)
)
if settings.RUN_MODE != "DEVELOP":
if self.common_args:
return self.load_sdk_class("shortcuts", "get_client_by_request")(request, **self.common_args)
return self.load_sdk_class(
"shortcuts", "get_client_by_request"
)(request, **self.common_args)
else:
raise AccessForbidden("sdk can only be called through the Web request")
raise AccessForbidden(
"sdk can only be called through the Web request"
)
else:
# develop mode
# 根据RUN_VER获得get_component_client_common_args函数
Expand All @@ -189,7 +203,7 @@ def load_sdk_class(self, mod, attr_or_class):

def patch_sdk_component_api_class(self):
def patch_get_item(self, item):
if item.startswith('__'):
if item.startswith("__"):
# make client can be pickled
raise AttributeError()

Expand All @@ -209,7 +223,9 @@ class ComponentAPICollection(object):

def __new__(cls, sdk_client, *args, **kwargs):
if sdk_client.mod_name not in cls.mod_map:
cls.mod_map[sdk_client.mod_name] = super(ComponentAPICollection, cls).__new__(cls)
cls.mod_map[sdk_client.mod_name] = super(
ComponentAPICollection, cls
).__new__(cls)
return cls.mod_map[sdk_client.mod_name]

def __init__(self, sdk_client):
Expand Down Expand Up @@ -240,14 +256,18 @@ def __getattr__(self, method):
return api_cls(
client=SDKClient(**self.collection.client.common_args),
method=method,
path='{api_prefix}{collection}/{action}/'.format(
api_prefix=ESB_API_PREFIX, collection=self.collection.client.mod_name, action=self.action
path="{api_prefix}{collection}/{action}/".format(
api_prefix=ESB_API_PREFIX,
collection=self.collection.client.mod_name,
action=self.action,
),
description='custom api(%s)' % self.action,
description="custom api(%s)" % self.action,
)

def __call__(self, *args, **kwargs):
raise NotImplementedError('custom api `%s` must specify the request method' % self.action)
raise NotImplementedError(
"custom api `%s` must specify the request method" % self.action
)


client = SDKClient()
Expand All @@ -264,7 +284,9 @@ def get_client_by_user(user_or_username):
username = user_or_username.username
else:
username = user_or_username
get_client_by_user = import_string(".".join([ESB_SDK_NAME, 'shortcuts', 'get_client_by_user']))
get_client_by_user = import_string(
".".join([ESB_SDK_NAME, "shortcuts", "get_client_by_user"])
)
return get_client_by_user(username)


Expand All @@ -282,17 +304,20 @@ def _wrap(*args, **kwargs):
response = sdk_method(*args, **kwargs)
if __raw:
return response

if "get_batch_users" in sdk_method.url:
logger.info("get_batch_users is execute, args={}, kwargs={}, response={}"
.format(args, kwargs, response))

if not response['result'] and not __ignore_err:
if response['code'] == API_PERMISSION_ERROR_CODE:
if "get_batch_users" in sdk_method.url:
logger.info(
"get_batch_users is execute, args={}, kwargs={}, response={}".format(
args, kwargs, response
)
)

if not response["result"] and not __ignore_err:
if response["code"] == API_PERMISSION_ERROR_CODE:
"""接口返回无权限的时候,直接抛出权限不够"""
raise IamPermissionDenied(data=response.get("permission", []))
raise ComponentCallError(response)

return response['data']
return response["data"]

return _wrap

0 comments on commit 53e1bf4

Please sign in to comment.