def wrap(request, *args, **kwargs): skip_access_control = getattr(settings, "SC_SKIP_ACCESS_CONTROL", False) if skip_access_control is False or skip_access_control == 'False': user_auth_tuple = auth_user.authenticate(request) app_name = get_service_name() resource_code = (dict( (k.lower(), v) for k, v in resource.items())).get( request.method.lower()) if resource_code: if not user_auth_tuple: return HttpResponse( json.dumps(DETAIL_401), content_type='application/json; charset=utf-8', status=401) user, auth = user_auth_tuple if not access_verify(user_id=user.id, app_name=app_name, resource_code=resource_code): return HttpResponse( json.dumps(DETAIL_403), content_type='application/json; charset=utf-8', status=403) return function(request, *args, **kwargs) return function(request, *args, **kwargs)
def request(method, service_address, api_path, protocol="http", token=None, *args, **kwargs): ''' :param token: should be a json format dict or json string, it should be {'uid': '1234abc', 'exp': 1722200316, 'iat': 1622193116, 'app_id': 'core'} type encode token by `json.dumps` to request header X-Jwt-Payload ''' service_name = get_service_name() request_url = build_url(protocol=protocol, address=service_address, api_path=api_path) headers = kwargs.pop('headers', {}) if token: if isinstance(token, dict): #token also should contain "uid" key headers.update({'X-Jwt-Payload': json.dumps(token)}) elif isinstance(token, str): headers.update({'X-Jwt-Payload': token}) else: logger.error(f"requests_client token parameter is not suitable type: {token}") tracer = opentracing.global_tracer() if tracer: span = tracer.active_span if span: carrier = {} tracer.inject(span, opentracing.Format.HTTP_HEADERS, carrier) headers.update(carrier) # logger.debug('=================== carrier: {}'.format(carrier)) try: res = requests.request(method=method, url=request_url, headers=headers, *args, **kwargs) return res except Exception as ex: error_message = "requests_client error, service_name:{}, protocol:{}, method:{}, " \ "request_service_address:{}, api_path:{}, message:{}" \ .format(service_name, protocol, method, service_address, api_path, ex.__str__()) logger.error(error_message) raise ex
def wrap(request, *args, **kwargs): skip_access_control = getattr(settings, "SC_SKIP_ACCESS_CONTROL", False) if skip_access_control is False or skip_access_control == 'False': user_id = request.META["REMOTE_USER"] if user_id is None: return HttpResponse(json.dumps(DETAIL_401), content_type='application/json; charset=utf-8', status=401) app_name = get_service_name() if not access_verify(user_id=user_id, app_name=app_name, resource_code=resource): return HttpResponse(json.dumps(DETAIL_403), content_type='application/json; charset=utf-8', status=403) return function(request, *args, **kwargs) return function(request, *args, **kwargs)
def handle(self, *args, **options): sg = SchemaGenerator() schema = sg.get_schema_dict() if not schema: return # 作者 schema["contributors"] = get_git_contributors() or [] # 服务名称 schema["service_name"] = get_service_name() # 注册schema register(schema) if options["print"] is True: data = json.dumps(schema, ensure_ascii=False) print(data)
def send_message(msg_data, code_type, content_type="text", msg_sender=None, *args, **kwargs): """ # ConfigMap: SC_LY_MESSAGE SC_LY_MESSAGE_API """ if msg_sender is None: msg_sender = get_service_name() sc_ly_message = get_cm_value("SC_LY_MESSAGE") sc_ly_message_api = get_cm_value("SC_LY_MESSAGE_API") data = { "shop_id": kwargs.pop("shop_id", None), "msg_sender": msg_sender, "code_type": code_type, "user_id_list": kwargs.pop("user_id_list", []), # msg数据格式是动态变化,由发送者根据服务要求填充发送该类型数据的必要数据 # "msg": { # "content_type": content_type, # "data": msg_data # } } # 把kwargs里面剩余的有关数据放入msg中,发送的数据由服务发送者决定,此处不做校验 msg = {"content_type": content_type, "data": msg_data} if kwargs.get("nickname"): msg.update({"nickname": kwargs.pop("nickname")}) if kwargs.get("title"): msg.update({"title": kwargs.pop("title")}) data.update({"msg": msg}) try: res = rest_client.post(sc_ly_message, sc_ly_message_api, json=data, *args, **kwargs) logging.info( "sparrow_cloud ly_message send_message, data:{}, code_type:{}". format(data, code_type)) return res except HTTPException as ex: logging.error( "sparrow_cloud ly_message send_message error: {}".format(ex)) raise HTTPException(ex)
def send_log(data): """ :param data: dict :return:True, False """ if not isinstance(data, dict): raise TypeError("参数类型错误:except=%s, get=%s" % ("dict", type(data))) data["service_name"] = get_service_name() service_log_svc = get_cm_value("SC_SERVICE_LOG_SVC") service_log_api = get_cm_value("SC_SERVICE_LOG_API") try: response = post(service_log_svc, service_log_api, data=data) logging.info( "sparrow_cloud: service log sent successfully, message:{}".format( response)) return True except HTTPException as ex: logging.error( "sparrow_cloud: Service log sending failed, message:{}".format( ex.__str__())) return False
def request(method, service_address, api_path, timeout, protocol="http", token=None, *args, **kwargs): service_name = get_service_name() request_url = build_url(protocol=protocol, address=service_address, api_path=api_path) headers = kwargs.pop('headers', {}) if token: headers.update({'Authorization': "token " + token}) tracer = opentracing.global_tracer() if tracer: span = tracer.active_span if span: carrier = {} tracer.inject(span, opentracing.Format.HTTP_HEADERS, carrier) headers.update(carrier) logger.debug('=================== carrier: {}'.format(carrier)) try: res = requests.request(method=method, url=request_url, headers=headers, timeout=timeout, *args, **kwargs) return _handle_response(res) except Exception as ex: error_message = "rest_client error, service_name:{}, protocol:{}, method:{}, " \ "request_service_address:{}, api_path:{}, message:{}"\ .format(service_name, protocol, method, service_address, api_path, ex.__str__()) logger.error(error_message) raise HTTPException(error_message)