def get_receiver_with_username(receiver__username=None, # noqa cc__username=None, contact_way='phone'): username_list = [] if receiver__username: username_list.extend(receiver__username) if cc__username: username_list.extend(cc__username) if not username_list: return {} from components.bk.apis.bk_login.get_batch_user import GetBatchUser user_result = GetBatchUser().invoke(kwargs={'username_list': username_list}) if not user_result['result']: raise CommonAPIError(u'Failed to get users contact information based on username, %s' % user_result['message']) result = {} not_exist_user = [] error_contact_user = [] user_data = user_result['data'] if receiver__username: result['receiver'] = [] for username in receiver__username: user = user_data.get(username) if not user: not_exist_user.append(username) continue user_contact, is_valid = get_user_contact(user, contact_way) if is_valid: result['receiver'].append(user_contact) else: error_contact_user.append(username) if cc__username: result['cc'] = [] for username in cc__username: user = user_data.get(username) if not user: not_exist_user.append(username) continue user_contact, is_valid = get_user_contact(user, contact_way) if is_valid: result['cc'].append(user_contact) else: error_contact_user.append(username) _extra_user_error_msg = [] if not_exist_user: _extra_user_error_msg.append(u'The following users are not blueking users: %s' % ','.join(not_exist_user)) if error_contact_user: _extra_user_error_msg.append(u'The following users contact format are incorrect: %s' % ','.join(error_contact_user)) result['_extra_user_error_msg'] = ';'.join(_extra_user_error_msg) if receiver__username and not result.get('receiver'): raise CommonAPIError(u'All users message failed to be sent. %s' % result['_extra_user_error_msg']) return result
def format_response(self, response): try: response = json.loads(response) except Exception: return { 'result': False, 'code': 1306000, 'message': 'Request interface error, response: %s' % response, } try: bk_error_code = response['bk_error_code'] except Exception: logger.exception('response: %s', response) raise CommonAPIError( 'An exception occurred while requesting CC interface, ' 'please contact the component developer to handle it.') if bk_error_code == 0: return { 'result': True, 'code': 0, 'data': response.get('data'), 'message': response.get('bk_error_msg') or '', } else: return { 'result': False, 'code': bk_error_code, 'data': response.get('data'), 'message': response.get('bk_error_msg') or '', }
def post_request(self, host, path, data=None, headers_json=True, **kwargs): headers = {} if not headers_json: headers = {'Content-type': 'application/x-www-form-urlencoded'} data = urllib.urlencode(data) response = self.request('POST', host, path, data=data, headers=headers, **kwargs) try: code = str(response['code']) except Exception: logger.exception('response: %s', response) raise CommonAPIError( 'An error occurred while requesting CC interface, ' 'the response content does not contain code field.') if code != '0': return { 'result': False, 'message': response.get('extmsg') or response.get('msg') or 'An unknown error occurred', 'error': { 'error_data': { 'api_spec': response } } } else: return {'result': True, 'data': response.get('data')}
def _request(self, method, request, system_name, component_name): components_manager = get_components_manager() comp_cls = components_manager.get_comp_by_compname( system_name, component_name) if not comp_cls: raise error_codes.COMPONENT_NOT_FOUND.format_prompt( 'system_name: %s, component_name: %s' % (system_name.upper(), component_name)) # noqa comp = comp_cls() self.patch_request_common(request) comp.set_request(CompRequest(wsgi_request=request)) try: response = comp.invoke() except APIError as e: response = e.code.as_dict() except: logger.exception('Request exception, request_id=%s, path=%s' % (request.g.request_id, request.path)) response = CommonAPIError( 'Component error, please contact the component developer' ).code.as_dict() response['request_id'] = request.g.request_id response = format_resp_dict(response) return JsonResponse(response)
def apply_mappings(self, mapping_id, _input, _output=None): """ 使用设置好的 Mapping 来重新处理输入输出 :param str mapping_id: ESBBuffetMapping 主键 :param dict _input: 请求参数 :param dict _output: 响应结果 :returns: 经过模板转换过的结果 """ mapping_obj = ESBBuffetMapping.objects.filter(id=mapping_id).first() if not mapping_obj: # INFO: 因为目前使用该方法的只有 _input 和 _output,目前优先返回 _output return _output or _input try: result = Template(mapping_obj.source).render( _input=_input, _output=_output, # Custom funcitons json=json.dumps ) result = json.loads(result) except Exception: logger.exception('Error occoured when apply mapping[%s], _input=%s, _output=%s', mapping_id, _input, _output) raise CommonAPIError('An error occurred in mapping of template. Please contact the developer') return result
def get_cleaned_data_or_error(self, status=None): """ 获取当前form的cleaned data,如果验证不通过,直接抛出CommonAPIError """ if self.is_valid(): return self.cleaned_data else: raise CommonAPIError(self.get_error_prompt(), status=status)
def get_wx_config(self): try: send_weixin_channel = ESBChannel.objects.get( path='/cmsi/send_weixin/') except Exception: raise CommonAPIError( 'Channel with path [/cmsi/send_weixin/] does not exist, can not get WeChat configuration' ) return dict(json.loads(send_weixin_channel.comp_conf))
def get_wx_token(self): params = { 'grant_type': 'client_credential', 'appid': self.form_data['appid'], 'secret': self.form_data['secret'], 'simple_get_token': 1, } client = tools.WEIXINClient(self.outgoing.http_client) result = client.get(path='/cgi-bin/token', params=params) if not result['result']: raise CommonAPIError(result['message']) return result['data']
def handle(self): wx_config = self.get_wx_config() wx_type = wx_config.get('wx_type') if wx_type in ['qy', 'qywx']: wx_qy_corpid = wx_config.get('wx_qy_corpid') wx_qy_corpsecret = wx_config.get('wx_qy_corpsecret') if not (wx_qy_corpid and wx_qy_corpsecret): raise CommonAPIError( 'Please improve the component configuration of component [/cmsi/send_weixin/] ' 'in ESB channel management') kwargs = { 'corpid': wx_qy_corpid, 'corpsecret': wx_qy_corpsecret, } self.response.payload = self.invoke_other( 'generic.weixin_qy.get_token', kwargs=kwargs) elif wx_type in ['mp']: wx_app_id = wx_config.get('wx_app_id') wx_secret = wx_config.get('wx_secret') if not (wx_app_id and wx_secret): raise CommonAPIError( 'Please improve the component configuration of component [/cmsi/send_weixin/] ' 'in ESB channel management') kwargs = { 'appid': wx_app_id, 'secret': wx_secret, 'need_new_token': self.form_data['need_new_token'], } self.response.payload = self.invoke_other( 'generic.weixin_mp.get_token', kwargs=kwargs) else: self.response.payload = { 'result': False, 'message': 'In the component configuration for component [/cmsi/send_weixin/], ' 'the value of wx_type is not in the optional range' }
def get_user_contact_with_username(username_list=None, contact_way='phone'): from components.bk.apis.bk_login.get_batch_user import GetBatchUser user_result = GetBatchUser().invoke( kwargs={'username_list': username_list}) if not user_result['result']: raise CommonAPIError(u'根据用户名批量获取用户联系方式失败,%s' % user_result['message']) user_contact_info = {} not_exist_user = [] error_contact_user = [] user_data = user_result['data'] for username in username_list: user = user_data.get(username) if not user: not_exist_user.append(username) continue user_contact, is_valid = get_user_contact(user, contact_way) if is_valid: user_contact_info[username] = user_contact else: error_contact_user.append(username) _extra_user_error_msg = [] if not_exist_user: _extra_user_error_msg.append(u'以下用户不是蓝鲸用户:%s' % ','.join(not_exist_user)) if error_contact_user: _extra_user_error_msg.append(u'以下用户联系方式格式错误:%s' % ','.join(error_contact_user)) _extra_user_error_msg = ';'.join(_extra_user_error_msg) if not user_contact_info: raise CommonAPIError(u'全部用户联系方式获取失败。%s' % _extra_user_error_msg) return { 'user_contact_info': user_contact_info, '_extra_user_error_msg': _extra_user_error_msg }
def validate_receiver(receiver, contact_way='phone'): valid_receiver = [] error_contact_user = [] for user_contact in receiver: if contact_way == 'email': is_valid = valid_email(user_contact) elif contact_way == 'phone': is_valid = valid_phone(user_contact) if is_valid: valid_receiver.append(user_contact) else: error_contact_user.append(user_contact) if error_contact_user: raise CommonAPIError('User message failed to send. The following users contact format are incorrect: %s, please check' % ','.join(error_contact_user)) # noqa return valid_receiver
def get_user_contact_with_username(username_list=None, contact_way='phone'): from components.bk.apis.bk_login.get_batch_user import GetBatchUser user_result = GetBatchUser().invoke(kwargs={'username_list': username_list}) if not user_result['result']: raise CommonAPIError(u'Failed to get users contact information based on username, %s' % user_result['message']) user_contact_info = {} not_exist_user = [] error_contact_user = [] user_data = user_result['data'] for username in username_list: user = user_data.get(username) if not user: not_exist_user.append(username) continue user_contact, is_valid = get_user_contact(user, contact_way) if is_valid: user_contact_info[username] = user_contact else: error_contact_user.append(username) _extra_user_error_msg = [] if not_exist_user: _extra_user_error_msg.append(u'The following users are not blueking users: %s' % ','.join(not_exist_user)) if error_contact_user: _extra_user_error_msg.append(u'The following users contact format are incorrect: %s' % ','.join(error_contact_user)) _extra_user_error_msg = ';'.join(_extra_user_error_msg) if not user_contact_info: raise CommonAPIError(u'All users contact information failed to get, %s' % _extra_user_error_msg) return { 'user_contact_info': user_contact_info, '_extra_user_error_msg': _extra_user_error_msg }
def validate_receiver(receiver, contact_way='phone'): valid_receiver = [] error_contact_user = [] for user_contact in receiver: if contact_way == 'email': is_valid = valid_email(user_contact) elif contact_way == 'phone': is_valid = valid_phone(user_contact) if is_valid: valid_receiver.append(user_contact) else: error_contact_user.append(user_contact) if error_contact_user: raise CommonAPIError(u'用户消息发送失败。以下用户联系方式格式错误:%s,请进行检查' % ','.join(error_contact_user)) return valid_receiver
def format_response(self, response): try: response = json.loads(response) except Exception: return { 'result': False, 'code': 1306000, 'message': 'Request interface error, the response content is not a json string: %s' % response, } bk_error_code = response.get('bk_error_code', response.get('code')) if bk_error_code is None: raise CommonAPIError( 'An error occurred while requesting CC interface, ' 'the response content does not contain bk_error_code field.') elif bk_error_code == 0: return { 'result': True, 'code': 0, 'data': response.get('data'), 'message': response.get('bk_error_msg', response.get('message')) or '', } else: return { 'result': False, 'code': bk_error_code, 'data': response.get('data'), 'message': response.get('bk_error_msg', response.get('message')) or '', }
def get_cleaned_data_or_error(self, status=None): if self.is_valid(): return self.cleaned_data else: raise CommonAPIError(self.get_error_prompt(), status=status)
def get_receiver_with_username( receiver__username=None, # noqa cc__username=None, contact_way='phone'): username_list = [] if receiver__username: username_list.extend(receiver__username) if cc__username: username_list.extend(cc__username) if not username_list: return {} from components.bk.apis.bk_login.get_batch_user import GetBatchUser user_result = GetBatchUser().invoke( kwargs={'username_list': username_list}) if not user_result['result']: raise CommonAPIError(u'根据用户名批量获取用户联系方式失败,%s' % user_result['message']) result = {} not_exist_user = [] error_contact_user = [] user_data = user_result['data'] if receiver__username: result['receiver'] = [] for username in receiver__username: user = user_data.get(username) if not user: not_exist_user.append(username) continue user_contact, is_valid = get_user_contact(user, contact_way) if is_valid: result['receiver'].append(user_contact) else: error_contact_user.append(username) if cc__username: result['cc'] = [] for username in cc__username: user = user_data.get(username) if not user: not_exist_user.append(username) continue user_contact, is_valid = get_user_contact(user, contact_way) if is_valid: result['cc'].append(user_contact) else: error_contact_user.append(username) _extra_user_error_msg = [] if not_exist_user: _extra_user_error_msg.append(u'以下用户不是蓝鲸用户:%s' % ','.join(not_exist_user)) if error_contact_user: _extra_user_error_msg.append(u'以下用户联系方式格式错误:%s' % ','.join(error_contact_user)) result['_extra_user_error_msg'] = ';'.join(_extra_user_error_msg) if receiver__username and not result.get('receiver'): raise CommonAPIError(u'全部用户消息发送失败。%s' % result['_extra_user_error_msg']) return result