async def update_partner_account_origin_data(self, auth_token, partner, identifier, origin_data, app_id, request_id=None): """ 修改第三方账号的origin_data :param auth_token: :param partner: :param identifier: :param origin_data: :param app_id: :param request_id: :return: """ if app_id is None: raise Exception("app id empty?") if origin_data is None: origin_data = {} data = Struct() data.update(origin_data) msg = pbaccount_pb2.PartnerAccountUpdateOriginDataRequest( auth_token=auth_token, partner=partner, identifier=identifier, origin_data=data, app_id=app_id) await MServer().call("account-server", "UpdatePartnerAccountOriginData", msg, request_id)
def execute_request(stub, session_id, selector_dict={}, payload_dict={}, option="text"): selector = Selector(channel=selector_dict.get('channel'), library=selector_dict.get('library'), language=selector_dict.get('language')) if option is "text": input = Input(user_text=payload_dict.get('input').get('userText')) data = None print("this is the input:", input) else: payload_dict = payload_dict['data'] struct_data = Struct() struct_data.update(payload_dict.get('value')) data = RequestData(id=payload_dict.get('id'), value=struct_data) print("this is the struct_data: ", struct_data) input = None event = Event() # session_data = SessionData() execute_payload = ExecuteRequestPayload( input=input, event=event, session_data=None, data=data) execute_request = ExecuteRequest(session_id=session_id, selector=selector, payload=execute_payload) #log.debug(f'Execute Request: {execute_payload}') execute_response, call = stub.Execute.with_call(execute_request) response = MessageToDict(execute_response) #log.debug(f'Execute Response: {response}') return response, call
def __init__(self, project: str, platform: int = enums.Intent.Message.Platform.LINE): self.project = project self.platform = platform self.intents_client = dialogflow.IntentsClient() self.contexts_client = dialogflow.ContextsClient() payload = Struct() payload.update({ self.PLATFORMS[self.platform].lower(): self.MORE_QUESTION_PAYLOAD }) self.more_question_message = Intent.Message( payload=payload, platform=self.platform, ) self.more_question_context = Context( name=self.contexts_client.context_path( project=self.project, session='-', context='more_question', ), lifespan_count=1, )
def __init__(self, pb_object: Union[GeneratedProtocolMessageType, FlyteIdlEntity]): """ :param Union[T, FlyteIdlEntity] pb_object: """ struct = Struct() v = pb_object # This section converts an existing proto object (or a subclass of) to the right type expected by this instance # of GenericProto. GenericProto can be used with any protobuf type (not restricted to FlyteType). This makes it # a bit tricky to figure out the right version of the underlying raw proto class to use to populate the final # struct. # If the provided object has to_flyte_idl(), call it to produce a raw proto. if isinstance(pb_object, FlyteIdlEntity): v = pb_object.to_flyte_idl() # A check to ensure the raw proto (v) is of the correct expected type. This also performs one final attempt to # convert it to the correct type by leveraging from_flyte_idl (implemented by all FlyteTypes) in case this class # is initialized with one. expected_type = type(self).pb_type if expected_type != type(v) and expected_type != type(pb_object): if isinstance(type(self).pb_type, FlyteType): v = expected_type.from_flyte_idl(v).to_flyte_idl() else: raise _user_exceptions.FlyteTypeException( received_type=type(pb_object), expected_type=expected_type, received_value=pb_object ) struct.update(_MessageToDict(v)) super().__init__(scalar=_literals.Scalar(generic=struct,))
def retrieve_credentials(credentials_supplier): """This is an internal wrapper around the Virtualization library's credentials retrieval API. Given a supplier provided by Virtualization, retrieves the credentials from that supplier. Args: credentials_supplier (dict): Properties that make up a supplier of credentials. Return: Subclass of Credentials retrieved from supplier. Either a PasswordCredentials or a KeyPairCredentials from dlpx.virtualization.common._common_classes. """ from dlpx.virtualization._engine import libs as internal_libs if not isinstance(credentials_supplier, dict): raise IncorrectArgumentTypeError('credentials_supplier', type(credentials_supplier), dict) credentials_request = libs_pb2.CredentialsRequest() credentials_struct = Struct() credentials_struct.update(credentials_supplier) credentials_request.credentials_supplier.CopyFrom(credentials_struct) response = internal_libs.retrieve_credentials(credentials_request) credentials_result = _handle_response(response) if credentials_result.password != "": return PasswordCredentials(credentials_result.username, credentials_result.password) return KeyPairCredentials( credentials_result.username, credentials_result.key_pair.private_key, credentials_result.key_pair.public_key)
def __init__(self, grpc_addr, uri, **kwargs): params = Struct() params.update(kwargs) self._grpc_addr = grpc_addr self._init = CaptureRequest( init=CaptureInit(uri=uri, parameters=params))
def to_literal( self, ctx: FlyteContext, python_val: DoltTable, python_type: typing.Type[DoltTable], expected: LiteralType, ) -> Literal: if not isinstance(python_val, DoltTable): raise AssertionError(f"Value cannot be converted to a table: {python_val}") conf = python_val.config if python_val.data is not None and python_val.config.tablename is not None: db = dolt.Dolt(conf.db_path) with tempfile.NamedTemporaryFile() as f: python_val.data.to_csv(f.name, index=False) message = f"Generated by Flyte execution id: {ctx.user_space_params.execution_id}" dolt_int.save( db=db, tablename=conf.tablename, filename=f.name, branch_conf=conf.branch_conf, meta_conf=conf.meta_conf, remote_conf=conf.remote_conf, save_args=conf.io_args, commit_message=message, ) s = Struct() s.update(python_val.to_dict()) return Literal(Scalar(generic=s))
async def create_group_message(self, group_message_id, product_id, msg_title, msg_content, from_id, request_id=None): content = Struct() try: content.update(msg_content) message_body = pbmsgbox_pb2.MessageBody(msg_title=msg_title, msg_content=content) msg = pbmsgbox_pb2.GroupMessageCreateRequest( group_message_id=group_message_id, product_id=product_id, message_body=message_body, from_id=from_id) await MServer().call("msgbox-server", "CreateGroupMessage", msg, request_id) except grpc.RpcError as e: msg = "create group message except. code: {}, details:{}".format( e.code(), e.details()) logging.warning(msg) return e.details()
def execute_request(stub, session_id, selector_dict={}, payload_dict={}, data_action=None): selector = Selector(channel=selector_dict.get('channel'), library=selector_dict.get('library'), language=selector_dict.get('language')) execute_input = None execute_data = None if not data_action: execute_input = Input(user_text=payload_dict.get('input').get('userText')) else: v = Struct() v.update(data_action.get('value')) execute_data = RequestData(id=data_action.get('id'), value=v) # session_data = SessionData() execute_event = Event() execute_payload = ExecuteRequestPayload( input=execute_input, event=execute_event, session_data=None, # DEFUNCT data=execute_data) execute_request = ExecuteRequest(session_id=session_id, selector=selector, payload=execute_payload) log.debug(f'>>>> Execute Request: {execute_request}') execute_response, call = stub.Execute.with_call(execute_request) response = MessageToDict(execute_response) log.debug(f'<<<< Execute Response: {json.dumps(response, indent=2)}') return response, call
def get_subscription_info(self, request, context): """Returns a user's subscription information stored in the tower, if the user is registered.""" try: subscription_info, locators = self.watcher.get_subscription_info( request.signature) user_struct = Struct() user_struct.update({ "subscription_expiry": subscription_info.subscription_expiry, "available_slots": subscription_info.available_slots, "appointments": locators, }) return GetUserResponse(user=user_struct) except AuthenticationFailure: msg = "User not found. Have you registered?" status_code = grpc.StatusCode.UNAUTHENTICATED except SubscriptionExpired as e: msg = str(e) status_code = grpc.StatusCode.UNAUTHENTICATED except ConnectionRefusedError: msg = "Service unavailable" status_code = grpc.StatusCode.UNAVAILABLE context.set_details(msg) context.set_code(status_code) return GetUserResponse()
async def bind_partner_account(self, identifier, token, origin_data, partner=pbaccount_pb2.PARTNER_WECHAT, app_id=None, request_id=None): """绑定第三方账号 注意,app_id参数一定要传入,不能使用默认的None :param identifier: :param token: :param origin_data: :param app_id: :param request_id: :param partner: :return: """ # check app_id first, because the app_id params have a default value with None. # Maybe someone will forget to give it a value if app_id is None: raise Exception("app id empty?") info = Struct() info.update(origin_data) msg = pbaccount_pb2.PartnerAccountBindRequest(partner=partner, auth_token=token, identifier=identifier, origin_data=info, app_id=app_id) await MServer().call("account-server", "PartnerAccountBind", msg, request_id)
async def create_account_by_partner(self, partner, identifier, origin_data, app_id=None, request_id=None): """通过第三方账号创建新账号 注意,app_id参数一定要传入,不能使用默认的None Returns: pb_account.Account -- Account信息 """ # check app_id first, because the app_id params have a default value with None. # Maybe someone will forget to give it a value if app_id is None: raise Exception("app id empty?") if origin_data is None: origin_data = {} data = Struct() data.update(origin_data) msg = pbaccount_pb2.CreateAccountByPartnerAccountRequest( partner=partner, identifier=identifier, origin_data=data, app_id=app_id) pb_account = await MServer().call("account-server", "CreateAccountByPartnerAccount", msg, request_id) return pb_account
def write_dict_to_proto(data: Dict[str, Any], path: str) -> str: from google.protobuf.struct_pb2 import Struct s = Struct() s.update(data) with open(f"{path}", "wb") as f: f.write(s.SerializeToString()) return f"{path}"
def document_info_handler(d, message_type): verified = d.pop("verified", False) if not verified: return d s = Struct() s.update(verified) d["verified"] = s return d
def activate(self, experiment_key, user_id, attributes): attrs = Struct() for k, v in attributes.items(): attrs.update({k: v}) user = pb2.User(id=user_id, attributes=attrs) activate_request = pb2.ActivateRequest(experiment_key=experiment_key, user=user) return self.stub.Activate(activate_request).variation
async def execute_action(self, game_id, data_dict): data_struct = Struct() data_struct.update(data_dict) response = await self.stub.ExecuteAction( eda_games_pb2.ExecuteActionRequest( idgame=game_id, data=data_struct, )) return GameState.from_protobuf_game_state_response(response)
def Write(self, write_command): if self.stub is None: raise RuntimeError('Not open channel.') s = Struct() s.update(write_command) request_data = control_yaskawa_robot_w_pb2.WriteRequest( write_command=s) detection = self.stub.Write(request_data) return detection
def test_only_day_parsed(self): parameters = Struct() parameters.update({'date': {"day": "2017-03-20"}}) r = Mock() r.action = 'history' r.parameters = parameters action = Action(r) self.assertEqual(action.date.year, 2017) self.assertEqual(action.date.month, 3) self.assertEqual(action.date.day, 20)
def test_day_with_years_ago_parsed(self): parameters = Struct() parameters.update({'date': {"day": "2017-03-20", "years_ago": 75}}) r = Mock() r.action = 'history' r.parameters = parameters action = Action(r) self.assertEqual(action.year, str(2017 - 75)) self.assertEqual(action.date.month, 3) self.assertEqual(action.date.day, 20)
def test_day_with_exact_year_parsed(self): parameters = Struct() parameters.update({'date': {"day": "2017-03-20", "year_exact": 1945}}) r = Mock() r.action = 'history' r.parameters = parameters action = Action(r) self.assertEqual(action.year, "1945") self.assertEqual(action.date.month, 3) self.assertEqual(action.date.day, 20)
def get_custom(self, settings: SerializationSettings) -> Dict[str, Any]: config = { "Location": self.task_config.Location, "ProjectID": self.task_config.ProjectID, } if self.task_config.QueryJobConfig is not None: config.update( self.task_config.QueryJobConfig.to_api_repr()["query"]) s = Struct() s.update(config) return json_format.MessageToDict(s)
def python_to_val_proto(raw_val, allow_collection=False): """ Converts a Python variable into a `protobuf` `Value` `Message` object. Parameters ---------- raw_val Python variable. allow_collection : bool, default False Whether to allow ``list``s and ``dict``s as `val`. This flag exists because some callers ought to not support logging collections, so this function will perform the typecheck on `val`. Returns ------- google.protobuf.struct_pb2.Value `protobuf` `Value` `Message` representing `val`. """ # TODO: check `allow_collection` before `to_builtin()` to avoid unnecessary processing val = to_builtin(raw_val) if val is None: return Value(null_value=NULL_VALUE) elif isinstance(val, bool): # did you know that `bool` is a subclass of `int`? return Value(bool_value=val) elif isinstance(val, numbers.Real): return Value(number_value=val) elif isinstance(val, six.string_types): return Value(string_value=val) elif isinstance(val, (list, dict)): if allow_collection: if isinstance(val, list): list_value = ListValue() list_value.extend(val) # pylint: disable=no-member return Value(list_value=list_value) else: # isinstance(val, dict) if all( [isinstance(key, six.string_types) for key in val.keys()]): struct_value = Struct() struct_value.update(val) # pylint: disable=no-member return Value(struct_value=struct_value) else: # protobuf's fault raise TypeError( "struct keys must be strings; consider using log_artifact() instead" ) else: raise TypeError( "unsupported type {}; consider using log_attribute() instead". format(type(raw_val))) else: raise TypeError( "unsupported type {}; consider using log_artifact() instead". format(type(raw_val)))
async def run(): async with grpc.aio.insecure_channel('localhost:50001') as channel: stub = rpc.test_pb2_grpc.TestServiceStub(channel) params = Struct() params.update({'hola': 'bb'}) response = await stub.TestCall( rpc.test_pb2.TestRequest( test_string='asd', test_dict=params, )) print(f"Test response: {response}")
def Write(self, request, context): write_command = MessageToDict(request.write_command) robot_data, timestamp = await self.y.write_command(write_command) #robot_data = MessageToDict(request.write_command) #timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] s = Struct() s.update(robot_data) return control_yaskawa_robot_w_pb2.WriteResponse( robot_data=s, timestamp=timestamp)
def test_dolt_table_to_literal_error(): s = Struct() s.update({"dummy": "data"}) lv = Literal(Scalar(generic=s)) with pytest.raises(ValueError): DoltTableNameTransformer.to_python_value( self=None, ctx=None, lv=lv, expected_python_type=DoltTable, )
def test_date_with_only_exact_year_parsed(self): parameters = Struct() parameters.update({'date': { "year_exact": 1910, }}) r = Mock() r.action = 'history' r.parameters = parameters action = Action(r) self.assertEqual(action.year, "1910") self.assertEqual(action.date.month, date.today().month) self.assertEqual(action.date.day, date.today().day)
def get_all_appointments(self, request, context): """Returns all the appointments in the tower.""" watcher_appointments = self.watcher.get_all_watcher_appointments() responder_trackers = self.watcher.get_all_responder_trackers() appointments = Struct() appointments.update({ "watcher_appointments": watcher_appointments, "responder_trackers": responder_trackers }) return GetAllAppointmentsResponse(appointments=appointments)
def encode(cls, dictionary: Dict[str, Any]) -> bytes: """Serialize compatible dictionary to bytes""" if not isinstance(dictionary, dict): raise TypeError( # pragma: nocover "dictionary must be of dict type, got type {}".format(type(dictionary)) ) # TOFIX(LR) problematic as it'll copy every message patched_dict = copy.deepcopy(dictionary) cls._patch_dict(patched_dict) pstruct = Struct() pstruct.update(patched_dict) # pylint: disable=no-member return pstruct.SerializeToString()
def testRunStrategy(strategy_id): channel = grpc.insecure_channel("localhost:50051") stub = strategy_pb2_grpc.StrategyServiceStub(channel) params = Struct() params.update({ "ema26": 26, "ema12": 12, "ema9": 9, }) selection = strategy_pb2.Selection( ID=strategy_id, Instrument="AUD_USD", Granularity="S5", Strategy="MACD", Parameters=params, Capital=1000, ) statistics = stub.InitialiseAlgorithm(selection) print(strategy_id, statistics) tmp = strategy_pb2.Tmp(ID=strategy_id, tmp=1) # stub.Act(tmp) # MUST RUN ACT BEFORE CALLING GET FUNCTIONS start_algo_param = strategy_pb2.StartAlgorithmParam(ID=strategy_id) start_algo_res = stub.StartAlgorithm(start_algo_param) if start_algo_res.Error != "": print(strategy_id, "failed to start", start_algo_res.Error) time.sleep(30) stop_algo_param = strategy_pb2.StopAlgorithmParam(ID=strategy_id) stop_algo_res = stub.Stop(stop_algo_param) if stop_algo_res.Error != "": print(strategy_id, "failed to stop", stop_algo_res.Error) return history_params = strategy_pb2.HistoryParams(ID=strategy_id, Length=10) data = stub.GetData(history_params) indicators = stub.GetIndicators(history_params) performances = stub.GetPerformances(history_params) statistics = stub.GetStatistics(tmp) print(strategy_id, data) print(strategy_id, indicators) print(strategy_id, performances) print(strategy_id, statistics)
def get_matching_summary(self, matching_data): s = Struct() s.update({'templateMatchingByOpenCV': matching_data}) request = template_matcning_summary_pb2.SummaryRequest(matching_data=s) try: ret = self.stub.get_matching_summary(request) except grpc.RpcError as e: lprint(e) return False else: return self._unpack_struct(ret.summary_data)