def get_snippet(self, service_name: str, rpc_name: str, sync: bool = True) -> Optional[Snippet]: """Fetch a single snippet from the index. Args: service_name (str): The name of the service. rpc_name (str): The name of the RPC. sync (bool): True for the sync version of the snippet, False for the async version. Returns: Optional[Snippet]: The snippet if it exists, or None. Raises: UnknownService: If the service is not found. RpcMethodNotFound: If the method is not found. """ # Fetch a snippet from the snippet metadata index service = self._index.get(service_name) if service is None: raise types.UnknownService( "API does not have a service named '{}'.".format(service_name)) method = service.get(rpc_name) if method is None: raise types.RpcMethodNotFound( "API does not have method '{}' in service '{}'".format( rpc_name, service_name)) return method["sync" if sync else "async"]
def add_snippet(self, snippet: Snippet) -> None: """Add a single snippet to the snippet index. Args: snippet (Snippet): The code snippet to be added. Raises: UnknownService: If the service indicated by the snippet metadata is not found. RpcMethodNotFound: If the method indicated by the snippet metadata is not found. """ service_name = snippet.metadata.client_method.method.service.short_name rpc_name = snippet.metadata.client_method.method.short_name service = self._index.get(service_name) if service is None: raise types.UnknownService( "API does not have a service named '{}'.".format(service_name)) method = service.get(rpc_name) if method is None: raise types.RpcMethodNotFound( "API does not have method '{}' in service '{}'".format( rpc_name, service_name)) if getattr(snippet.metadata.client_method, "async"): method["async"] = snippet else: method["sync"] = snippet self.metadata_index.snippets.append(snippet.metadata)
def generate_sample(sample, api_schema, sample_template: jinja2.Template) -> Tuple[str, Any]: """Generate a standalone, runnable sample. Writing the rendered output is left for the caller. Args: sample (Any): A definition for a single sample. api_schema (api.API): The schema that defines the API to which the sample belongs. sample_template (jinja2.Template): The template representing a generic sample. Returns: Tuple(str, snippet_metadata_pb2.Snippet): The rendered sample. """ service_name = sample["service"] service = api_schema.services.get(service_name) if not service: raise types.UnknownService("Unknown service: {}", service_name) rpc_name = sample["rpc"] rpc = service.methods.get(rpc_name) if not rpc: raise types.RpcMethodNotFound( "Could not find rpc in service {}: {}".format( service_name, rpc_name) ) calling_form = types.CallingForm.method_default(rpc) v = Validator(rpc, api_schema) # Tweak some small aspects of the sample to set defaults for optional # fields, add fields that are required for the template, and so forth. v.preprocess_sample(sample, api_schema, rpc) sample["request"] = v.validate_and_transform_request( calling_form, sample["request"] ) v.validate_response(sample["response"]) # Snippet Metadata can't be fully filled out in any one function # In this function we add information from # the API schema and sample dictionary. snippet_metadata = snippet_metadata_pb2.Snippet() # type: ignore snippet_metadata.region_tag = sample["region_tag"] setattr(snippet_metadata.client_method, "async", sample["transport"] == api.TRANSPORT_GRPC_ASYNC) snippet_metadata.client_method.method.short_name = sample["rpc"] snippet_metadata.client_method.method.service.short_name = sample["service"].split( ".")[-1] return sample_template.render( sample=sample, imports=[], calling_form=calling_form, calling_form_enum=types.CallingForm, trim_blocks=True, lstrip_blocks=True, ), snippet_metadata
def generate_sample( sample, api_schema, sample_template: jinja2.Template ) -> str: """Generate a standalone, runnable sample. Writing the rendered output is left for the caller. Args: sample (Any): A definition for a single sample generated from parsed yaml. api_schema (api.API): The schema that defines the API to which the sample belongs. sample_template (jinja2.Template): The template representing a generic sample. Returns: str: The rendered sample. """ service_name = sample["service"] service = api_schema.services.get(service_name) if not service: raise types.UnknownService("Unknown service: {}", service_name) rpc_name = sample["rpc"] rpc = service.methods.get(rpc_name) if not rpc: raise types.RpcMethodNotFound( "Could not find rpc in service {}: {}".format( service_name, rpc_name) ) calling_form = types.CallingForm.method_default(rpc) v = Validator(rpc) # Tweak some small aspects of the sample to set sane defaults for optional # fields, add fields that are required for the template, and so forth. v.preprocess_sample(sample, api_schema) sample["request"] = v.validate_and_transform_request(calling_form, sample["request"]) v.validate_response(sample["response"]) return sample_template.render( sample=sample, imports=[ "from google import auth", "from google.auth import credentials", ], calling_form=calling_form, calling_form_enum=types.CallingForm, api=api_schema, service=service, )
def generate_sample(sample, env: jinja2.environment.Environment, api_schema: api.API, template_name: str = DEFAULT_TEMPLATE_NAME) -> str: """Generate a standalone, runnable sample. Rendering and writing the rendered output is left for the caller. Args: sample (Any): A definition for a single sample generated from parsed yaml. env (jinja2.environment.Environment): The jinja environment used to generate the filled template for the sample. api_schema (api.API): The schema that defines the API to which the sample belongs. template_name (str): An optional override for the name of the template used to generate the sample. Returns: str: The rendered sample. """ sample_template = env.get_template(template_name) service_name = sample["service"] service = api_schema.services.get(service_name) if not service: raise types.UnknownService("Unknown service: {}", service_name) rpc_name = sample["rpc"] rpc = service.methods.get(rpc_name) if not rpc: raise types.RpcMethodNotFound( "Could not find rpc in service {}: {}".format( service_name, rpc_name)) calling_form = types.CallingForm.method_default(rpc) v = Validator(rpc) # Tweak some small aspects of the sample to set sane defaults for optional # fields, add fields that are required for the template, and so forth. v.preprocess_sample(sample, api_schema) sample["request"] = v.validate_and_transform_request( calling_form, sample["request"]) v.validate_response(sample["response"]) return sample_template.render( file_header=FILE_HEADER, sample=sample, imports=[], calling_form=calling_form, calling_form_enum=types.CallingForm, )
def generate_sample(sample, api_schema, sample_template: jinja2.Template) -> Tuple[str, Any]: """Generate a standalone, runnable sample. Writing the rendered output is left for the caller. Args: sample (Any): A definition for a single sample. api_schema (api.API): The schema that defines the API to which the sample belongs. sample_template (jinja2.Template): The template representing a generic sample. Returns: Tuple(str, snippet_metadata_pb2.Snippet): The rendered sample. """ service_name = sample["service"] service = api_schema.services.get(service_name) if not service: raise types.UnknownService("Unknown service: {}", service_name) rpc_name = sample["rpc"] rpc = service.methods.get(rpc_name) if not rpc: raise types.RpcMethodNotFound( "Could not find rpc in service {}: {}".format( service_name, rpc_name)) calling_form = types.CallingForm.method_default(rpc) v = Validator(rpc, api_schema) # Tweak some small aspects of the sample to set defaults for optional # fields, add fields that are required for the template, and so forth. v.preprocess_sample(sample, api_schema, rpc) sample["request"] = v.validate_and_transform_request( calling_form, sample["request"]) v.validate_response(sample["response"]) snippet_metadata = _fill_sample_metadata(sample, api_schema) # The sample must be preprocessed before calling _get_sample_imports. imports = _get_sample_imports(sample, rpc) return sample_template.render( sample=sample, imports=imports, calling_form=calling_form, calling_form_enum=types.CallingForm, trim_blocks=True, lstrip_blocks=True, ), snippet_metadata