repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
awslabs/serverless-application-model
samtranslator/intrinsics/resource_refs.py
SupportedResourceReferences.add
def add(self, logical_id, property, value): """ Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" :param logical_id: Logical ID of the resource (Ex: MyLambdaFunction) :param property: Property on the resource that can be referenced (Ex: Alias) :param value: Value that this reference resolves to. :return: nothing """ if not logical_id or not property: raise ValueError("LogicalId and property must be a non-empty string") if not value or not isinstance(value, string_types): raise ValueError("Property value must be a non-empty string") if logical_id not in self._refs: self._refs[logical_id] = {} if property in self._refs[logical_id]: raise ValueError("Cannot add second reference value to {}.{} property".format(logical_id, property)) self._refs[logical_id][property] = value
python
def add(self, logical_id, property, value): """ Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" :param logical_id: Logical ID of the resource (Ex: MyLambdaFunction) :param property: Property on the resource that can be referenced (Ex: Alias) :param value: Value that this reference resolves to. :return: nothing """ if not logical_id or not property: raise ValueError("LogicalId and property must be a non-empty string") if not value or not isinstance(value, string_types): raise ValueError("Property value must be a non-empty string") if logical_id not in self._refs: self._refs[logical_id] = {} if property in self._refs[logical_id]: raise ValueError("Cannot add second reference value to {}.{} property".format(logical_id, property)) self._refs[logical_id][property] = value
[ "def", "add", "(", "self", ",", "logical_id", ",", "property", ",", "value", ")", ":", "if", "not", "logical_id", "or", "not", "property", ":", "raise", "ValueError", "(", "\"LogicalId and property must be a non-empty string\"", ")", "if", "not", "value", "or", "not", "isinstance", "(", "value", ",", "string_types", ")", ":", "raise", "ValueError", "(", "\"Property value must be a non-empty string\"", ")", "if", "logical_id", "not", "in", "self", ".", "_refs", ":", "self", ".", "_refs", "[", "logical_id", "]", "=", "{", "}", "if", "property", "in", "self", ".", "_refs", "[", "logical_id", "]", ":", "raise", "ValueError", "(", "\"Cannot add second reference value to {}.{} property\"", ".", "format", "(", "logical_id", ",", "property", ")", ")", "self", ".", "_refs", "[", "logical_id", "]", "[", "property", "]", "=", "value" ]
Add the information that resource with given `logical_id` supports the given `property`, and that a reference to `logical_id.property` resolves to given `value. Example: "MyApi.Deployment" -> "MyApiDeployment1234567890" :param logical_id: Logical ID of the resource (Ex: MyLambdaFunction) :param property: Property on the resource that can be referenced (Ex: Alias) :param value: Value that this reference resolves to. :return: nothing
[ "Add", "the", "information", "that", "resource", "with", "given", "logical_id", "supports", "the", "given", "property", "and", "that", "a", "reference", "to", "logical_id", ".", "property", "resolves", "to", "given", "value", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resource_refs.py#L17-L44
train
awslabs/serverless-application-model
samtranslator/intrinsics/resource_refs.py
SupportedResourceReferences.get
def get(self, logical_id, property): """ Returns the value of the reference for given logical_id at given property. Ex: MyFunction.Alias :param logical_id: Logical Id of the resource :param property: Property of the resource you want to resolve. None if you want to get value of all properties :return: Value of this property if present. None otherwise """ # By defaulting to empty dictionary, we can handle the case where logical_id is not in map without if statements prop_values = self.get_all(logical_id) if prop_values: return prop_values.get(property, None) else: return None
python
def get(self, logical_id, property): """ Returns the value of the reference for given logical_id at given property. Ex: MyFunction.Alias :param logical_id: Logical Id of the resource :param property: Property of the resource you want to resolve. None if you want to get value of all properties :return: Value of this property if present. None otherwise """ # By defaulting to empty dictionary, we can handle the case where logical_id is not in map without if statements prop_values = self.get_all(logical_id) if prop_values: return prop_values.get(property, None) else: return None
[ "def", "get", "(", "self", ",", "logical_id", ",", "property", ")", ":", "# By defaulting to empty dictionary, we can handle the case where logical_id is not in map without if statements", "prop_values", "=", "self", ".", "get_all", "(", "logical_id", ")", "if", "prop_values", ":", "return", "prop_values", ".", "get", "(", "property", ",", "None", ")", "else", ":", "return", "None" ]
Returns the value of the reference for given logical_id at given property. Ex: MyFunction.Alias :param logical_id: Logical Id of the resource :param property: Property of the resource you want to resolve. None if you want to get value of all properties :return: Value of this property if present. None otherwise
[ "Returns", "the", "value", "of", "the", "reference", "for", "given", "logical_id", "at", "given", "property", ".", "Ex", ":", "MyFunction", ".", "Alias" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/intrinsics/resource_refs.py#L46-L60
train
awslabs/serverless-application-model
examples/2016-10-31/encryption_proxy/src/encryption.py
encrypt
def encrypt(key, message): '''encrypt leverages KMS encrypt and base64-encode encrypted blob More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html ''' try: ret = kms.encrypt(KeyId=key, Plaintext=message) encrypted_data = base64.encodestring(ret.get('CiphertextBlob')) except Exception as e: # returns http 500 back to user and log error details in Cloudwatch Logs raise Exception("Unable to encrypt data: ", e) return encrypted_data.decode()
python
def encrypt(key, message): '''encrypt leverages KMS encrypt and base64-encode encrypted blob More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html ''' try: ret = kms.encrypt(KeyId=key, Plaintext=message) encrypted_data = base64.encodestring(ret.get('CiphertextBlob')) except Exception as e: # returns http 500 back to user and log error details in Cloudwatch Logs raise Exception("Unable to encrypt data: ", e) return encrypted_data.decode()
[ "def", "encrypt", "(", "key", ",", "message", ")", ":", "try", ":", "ret", "=", "kms", ".", "encrypt", "(", "KeyId", "=", "key", ",", "Plaintext", "=", "message", ")", "encrypted_data", "=", "base64", ".", "encodestring", "(", "ret", ".", "get", "(", "'CiphertextBlob'", ")", ")", "except", "Exception", "as", "e", ":", "# returns http 500 back to user and log error details in Cloudwatch Logs", "raise", "Exception", "(", "\"Unable to encrypt data: \"", ",", "e", ")", "return", "encrypted_data", ".", "decode", "(", ")" ]
encrypt leverages KMS encrypt and base64-encode encrypted blob More info on KMS encrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html
[ "encrypt", "leverages", "KMS", "encrypt", "and", "base64", "-", "encode", "encrypted", "blob" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/2016-10-31/encryption_proxy/src/encryption.py#L16-L29
train
awslabs/serverless-application-model
samtranslator/model/tags/resource_tagging.py
get_tag_list
def get_tag_list(resource_tag_dict): """ Transforms the SAM defined Tags into the form CloudFormation is expecting. SAM Example: ``` ... Tags: TagKey: TagValue ``` CloudFormation equivalent: - Key: TagKey Value: TagValue ``` :param resource_tag_dict: Customer defined dictionary (SAM Example from above) :return: List of Tag Dictionaries (CloudFormation Equivalent from above) """ tag_list = [] if resource_tag_dict is None: return tag_list for tag_key, tag_value in resource_tag_dict.items(): tag = {_KEY: tag_key, _VALUE: tag_value if tag_value else ""} tag_list.append(tag) return tag_list
python
def get_tag_list(resource_tag_dict): """ Transforms the SAM defined Tags into the form CloudFormation is expecting. SAM Example: ``` ... Tags: TagKey: TagValue ``` CloudFormation equivalent: - Key: TagKey Value: TagValue ``` :param resource_tag_dict: Customer defined dictionary (SAM Example from above) :return: List of Tag Dictionaries (CloudFormation Equivalent from above) """ tag_list = [] if resource_tag_dict is None: return tag_list for tag_key, tag_value in resource_tag_dict.items(): tag = {_KEY: tag_key, _VALUE: tag_value if tag_value else ""} tag_list.append(tag) return tag_list
[ "def", "get_tag_list", "(", "resource_tag_dict", ")", ":", "tag_list", "=", "[", "]", "if", "resource_tag_dict", "is", "None", ":", "return", "tag_list", "for", "tag_key", ",", "tag_value", "in", "resource_tag_dict", ".", "items", "(", ")", ":", "tag", "=", "{", "_KEY", ":", "tag_key", ",", "_VALUE", ":", "tag_value", "if", "tag_value", "else", "\"\"", "}", "tag_list", ".", "append", "(", "tag", ")", "return", "tag_list" ]
Transforms the SAM defined Tags into the form CloudFormation is expecting. SAM Example: ``` ... Tags: TagKey: TagValue ``` CloudFormation equivalent: - Key: TagKey Value: TagValue ``` :param resource_tag_dict: Customer defined dictionary (SAM Example from above) :return: List of Tag Dictionaries (CloudFormation Equivalent from above)
[ "Transforms", "the", "SAM", "defined", "Tags", "into", "the", "form", "CloudFormation", "is", "expecting", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/tags/resource_tagging.py#L7-L36
train
awslabs/serverless-application-model
samtranslator/translator/arn_generator.py
ArnGenerator.get_partition_name
def get_partition_name(cls, region=None): """ Gets the name of the partition given the region name. If region name is not provided, this method will use Boto3 to get name of the region where this code is running. This implementation is borrowed from AWS CLI https://github.com/aws/aws-cli/blob/1.11.139/awscli/customizations/emr/createdefaultroles.py#L59 :param region: Optional name of the region :return: Partition name """ if region is None: # Use Boto3 to get the region where code is running. This uses Boto's regular region resolution # mechanism, starting from AWS_DEFAULT_REGION environment variable. region = boto3.session.Session().region_name region_string = region.lower() if region_string.startswith("cn-"): return "aws-cn" elif region_string.startswith("us-gov"): return "aws-us-gov" else: return "aws"
python
def get_partition_name(cls, region=None): """ Gets the name of the partition given the region name. If region name is not provided, this method will use Boto3 to get name of the region where this code is running. This implementation is borrowed from AWS CLI https://github.com/aws/aws-cli/blob/1.11.139/awscli/customizations/emr/createdefaultroles.py#L59 :param region: Optional name of the region :return: Partition name """ if region is None: # Use Boto3 to get the region where code is running. This uses Boto's regular region resolution # mechanism, starting from AWS_DEFAULT_REGION environment variable. region = boto3.session.Session().region_name region_string = region.lower() if region_string.startswith("cn-"): return "aws-cn" elif region_string.startswith("us-gov"): return "aws-us-gov" else: return "aws"
[ "def", "get_partition_name", "(", "cls", ",", "region", "=", "None", ")", ":", "if", "region", "is", "None", ":", "# Use Boto3 to get the region where code is running. This uses Boto's regular region resolution", "# mechanism, starting from AWS_DEFAULT_REGION environment variable.", "region", "=", "boto3", ".", "session", ".", "Session", "(", ")", ".", "region_name", "region_string", "=", "region", ".", "lower", "(", ")", "if", "region_string", ".", "startswith", "(", "\"cn-\"", ")", ":", "return", "\"aws-cn\"", "elif", "region_string", ".", "startswith", "(", "\"us-gov\"", ")", ":", "return", "\"aws-us-gov\"", "else", ":", "return", "\"aws\"" ]
Gets the name of the partition given the region name. If region name is not provided, this method will use Boto3 to get name of the region where this code is running. This implementation is borrowed from AWS CLI https://github.com/aws/aws-cli/blob/1.11.139/awscli/customizations/emr/createdefaultroles.py#L59 :param region: Optional name of the region :return: Partition name
[ "Gets", "the", "name", "of", "the", "partition", "given", "the", "region", "name", ".", "If", "region", "name", "is", "not", "provided", "this", "method", "will", "use", "Boto3", "to", "get", "name", "of", "the", "region", "where", "this", "code", "is", "running", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/arn_generator.py#L33-L56
train
awslabs/serverless-application-model
samtranslator/plugins/api/default_definition_body_plugin.py
DefaultDefinitionBodyPlugin.on_before_transform_template
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing """ template = SamTemplate(template_dict) for logicalId, api in template.iterate(SamResourceType.Api.value): if api.properties.get('DefinitionBody') or api.properties.get('DefinitionUri'): continue api.properties['DefinitionBody'] = SwaggerEditor.gen_skeleton() api.properties['__MANAGE_SWAGGER'] = True
python
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing """ template = SamTemplate(template_dict) for logicalId, api in template.iterate(SamResourceType.Api.value): if api.properties.get('DefinitionBody') or api.properties.get('DefinitionUri'): continue api.properties['DefinitionBody'] = SwaggerEditor.gen_skeleton() api.properties['__MANAGE_SWAGGER'] = True
[ "def", "on_before_transform_template", "(", "self", ",", "template_dict", ")", ":", "template", "=", "SamTemplate", "(", "template_dict", ")", "for", "logicalId", ",", "api", "in", "template", ".", "iterate", "(", "SamResourceType", ".", "Api", ".", "value", ")", ":", "if", "api", ".", "properties", ".", "get", "(", "'DefinitionBody'", ")", "or", "api", ".", "properties", ".", "get", "(", "'DefinitionUri'", ")", ":", "continue", "api", ".", "properties", "[", "'DefinitionBody'", "]", "=", "SwaggerEditor", ".", "gen_skeleton", "(", ")", "api", ".", "properties", "[", "'__MANAGE_SWAGGER'", "]", "=", "True" ]
Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing
[ "Hook", "method", "that", "gets", "called", "before", "the", "SAM", "template", "is", "processed", ".", "The", "template", "has", "passed", "the", "validation", "and", "is", "guaranteed", "to", "contain", "a", "non", "-", "empty", "Resources", "section", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/default_definition_body_plugin.py#L22-L37
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.has_path
def has_path(self, path, method=None): """ Returns True if this Swagger has the given path and optional method :param string path: Path name :param string method: HTTP method :return: True, if this path/method is present in the document """ method = self._normalize_method_name(method) path_dict = self.get_path(path) path_dict_exists = path_dict is not None if method: return path_dict_exists and method in path_dict return path_dict_exists
python
def has_path(self, path, method=None): """ Returns True if this Swagger has the given path and optional method :param string path: Path name :param string method: HTTP method :return: True, if this path/method is present in the document """ method = self._normalize_method_name(method) path_dict = self.get_path(path) path_dict_exists = path_dict is not None if method: return path_dict_exists and method in path_dict return path_dict_exists
[ "def", "has_path", "(", "self", ",", "path", ",", "method", "=", "None", ")", ":", "method", "=", "self", ".", "_normalize_method_name", "(", "method", ")", "path_dict", "=", "self", ".", "get_path", "(", "path", ")", "path_dict_exists", "=", "path_dict", "is", "not", "None", "if", "method", ":", "return", "path_dict_exists", "and", "method", "in", "path_dict", "return", "path_dict_exists" ]
Returns True if this Swagger has the given path and optional method :param string path: Path name :param string method: HTTP method :return: True, if this path/method is present in the document
[ "Returns", "True", "if", "this", "Swagger", "has", "the", "given", "path", "and", "optional", "method" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L46-L60
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.method_has_integration
def method_has_integration(self, method): """ Returns true if the given method contains a valid method definition. This uses the get_method_contents function to handle conditionals. :param dict method: method dictionary :return: true if method has one or multiple integrations """ for method_definition in self.get_method_contents(method): if self.method_definition_has_integration(method_definition): return True return False
python
def method_has_integration(self, method): """ Returns true if the given method contains a valid method definition. This uses the get_method_contents function to handle conditionals. :param dict method: method dictionary :return: true if method has one or multiple integrations """ for method_definition in self.get_method_contents(method): if self.method_definition_has_integration(method_definition): return True return False
[ "def", "method_has_integration", "(", "self", ",", "method", ")", ":", "for", "method_definition", "in", "self", ".", "get_method_contents", "(", "method", ")", ":", "if", "self", ".", "method_definition_has_integration", "(", "method_definition", ")", ":", "return", "True", "return", "False" ]
Returns true if the given method contains a valid method definition. This uses the get_method_contents function to handle conditionals. :param dict method: method dictionary :return: true if method has one or multiple integrations
[ "Returns", "true", "if", "the", "given", "method", "contains", "a", "valid", "method", "definition", ".", "This", "uses", "the", "get_method_contents", "function", "to", "handle", "conditionals", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L62-L73
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.get_method_contents
def get_method_contents(self, method): """ Returns the swagger contents of the given method. This checks to see if a conditional block has been used inside of the method, and, if so, returns the method contents that are inside of the conditional. :param dict method: method dictionary :return: list of swagger component dictionaries for the method """ if self._CONDITIONAL_IF in method: return method[self._CONDITIONAL_IF][1:] return [method]
python
def get_method_contents(self, method): """ Returns the swagger contents of the given method. This checks to see if a conditional block has been used inside of the method, and, if so, returns the method contents that are inside of the conditional. :param dict method: method dictionary :return: list of swagger component dictionaries for the method """ if self._CONDITIONAL_IF in method: return method[self._CONDITIONAL_IF][1:] return [method]
[ "def", "get_method_contents", "(", "self", ",", "method", ")", ":", "if", "self", ".", "_CONDITIONAL_IF", "in", "method", ":", "return", "method", "[", "self", ".", "_CONDITIONAL_IF", "]", "[", "1", ":", "]", "return", "[", "method", "]" ]
Returns the swagger contents of the given method. This checks to see if a conditional block has been used inside of the method, and, if so, returns the method contents that are inside of the conditional. :param dict method: method dictionary :return: list of swagger component dictionaries for the method
[ "Returns", "the", "swagger", "contents", "of", "the", "given", "method", ".", "This", "checks", "to", "see", "if", "a", "conditional", "block", "has", "been", "used", "inside", "of", "the", "method", "and", "if", "so", "returns", "the", "method", "contents", "that", "are", "inside", "of", "the", "conditional", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L86-L97
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.has_integration
def has_integration(self, path, method): """ Checks if an API Gateway integration is already present at the given path/method :param string path: Path name :param string method: HTTP method :return: True, if an API Gateway integration is already present """ method = self._normalize_method_name(method) path_dict = self.get_path(path) return self.has_path(path, method) and \ isinstance(path_dict[method], dict) and \ self.method_has_integration(path_dict[method])
python
def has_integration(self, path, method): """ Checks if an API Gateway integration is already present at the given path/method :param string path: Path name :param string method: HTTP method :return: True, if an API Gateway integration is already present """ method = self._normalize_method_name(method) path_dict = self.get_path(path) return self.has_path(path, method) and \ isinstance(path_dict[method], dict) and \ self.method_has_integration(path_dict[method])
[ "def", "has_integration", "(", "self", ",", "path", ",", "method", ")", ":", "method", "=", "self", ".", "_normalize_method_name", "(", "method", ")", "path_dict", "=", "self", ".", "get_path", "(", "path", ")", "return", "self", ".", "has_path", "(", "path", ",", "method", ")", "and", "isinstance", "(", "path_dict", "[", "method", "]", ",", "dict", ")", "and", "self", ".", "method_has_integration", "(", "path_dict", "[", "method", "]", ")" ]
Checks if an API Gateway integration is already present at the given path/method :param string path: Path name :param string method: HTTP method :return: True, if an API Gateway integration is already present
[ "Checks", "if", "an", "API", "Gateway", "integration", "is", "already", "present", "at", "the", "given", "path", "/", "method" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L99-L112
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.add_path
def add_path(self, path, method=None): """ Adds the path/method combination to the Swagger, if not already present :param string path: Path name :param string method: HTTP method :raises ValueError: If the value of `path` in Swagger is not a dictionary """ method = self._normalize_method_name(method) path_dict = self.paths.setdefault(path, {}) if not isinstance(path_dict, dict): # Either customers has provided us an invalid Swagger, or this class has messed it somehow raise InvalidDocumentException( [InvalidTemplateException("Value of '{}' path must be a dictionary according to Swagger spec." .format(path))]) if self._CONDITIONAL_IF in path_dict: path_dict = path_dict[self._CONDITIONAL_IF][1] path_dict.setdefault(method, {})
python
def add_path(self, path, method=None): """ Adds the path/method combination to the Swagger, if not already present :param string path: Path name :param string method: HTTP method :raises ValueError: If the value of `path` in Swagger is not a dictionary """ method = self._normalize_method_name(method) path_dict = self.paths.setdefault(path, {}) if not isinstance(path_dict, dict): # Either customers has provided us an invalid Swagger, or this class has messed it somehow raise InvalidDocumentException( [InvalidTemplateException("Value of '{}' path must be a dictionary according to Swagger spec." .format(path))]) if self._CONDITIONAL_IF in path_dict: path_dict = path_dict[self._CONDITIONAL_IF][1] path_dict.setdefault(method, {})
[ "def", "add_path", "(", "self", ",", "path", ",", "method", "=", "None", ")", ":", "method", "=", "self", ".", "_normalize_method_name", "(", "method", ")", "path_dict", "=", "self", ".", "paths", ".", "setdefault", "(", "path", ",", "{", "}", ")", "if", "not", "isinstance", "(", "path_dict", ",", "dict", ")", ":", "# Either customers has provided us an invalid Swagger, or this class has messed it somehow", "raise", "InvalidDocumentException", "(", "[", "InvalidTemplateException", "(", "\"Value of '{}' path must be a dictionary according to Swagger spec.\"", ".", "format", "(", "path", ")", ")", "]", ")", "if", "self", ".", "_CONDITIONAL_IF", "in", "path_dict", ":", "path_dict", "=", "path_dict", "[", "self", ".", "_CONDITIONAL_IF", "]", "[", "1", "]", "path_dict", ".", "setdefault", "(", "method", ",", "{", "}", ")" ]
Adds the path/method combination to the Swagger, if not already present :param string path: Path name :param string method: HTTP method :raises ValueError: If the value of `path` in Swagger is not a dictionary
[ "Adds", "the", "path", "/", "method", "combination", "to", "the", "Swagger", "if", "not", "already", "present" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L114-L135
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.add_lambda_integration
def add_lambda_integration(self, path, method, integration_uri, method_auth_config=None, api_auth_config=None, condition=None): """ Adds aws_proxy APIGW integration to the given path+method. :param string path: Path name :param string method: HTTP Method :param string integration_uri: URI for the integration. """ method = self._normalize_method_name(method) if self.has_integration(path, method): raise ValueError("Lambda integration already exists on Path={}, Method={}".format(path, method)) self.add_path(path, method) # Wrap the integration_uri in a Condition if one exists on that function # This is necessary so CFN doesn't try to resolve the integration reference. if condition: integration_uri = make_conditional(condition, integration_uri) path_dict = self.get_path(path) path_dict[method][self._X_APIGW_INTEGRATION] = { 'type': 'aws_proxy', 'httpMethod': 'POST', 'uri': integration_uri } method_auth_config = method_auth_config or {} api_auth_config = api_auth_config or {} if method_auth_config.get('Authorizer') == 'AWS_IAM' \ or api_auth_config.get('DefaultAuthorizer') == 'AWS_IAM' and not method_auth_config: self.paths[path][method][self._X_APIGW_INTEGRATION]['credentials'] = self._generate_integration_credentials( method_invoke_role=method_auth_config.get('InvokeRole'), api_invoke_role=api_auth_config.get('InvokeRole') ) # If 'responses' key is *not* present, add it with an empty dict as value path_dict[method].setdefault('responses', {}) # If a condition is present, wrap all method contents up into the condition if condition: path_dict[method] = make_conditional(condition, path_dict[method])
python
def add_lambda_integration(self, path, method, integration_uri, method_auth_config=None, api_auth_config=None, condition=None): """ Adds aws_proxy APIGW integration to the given path+method. :param string path: Path name :param string method: HTTP Method :param string integration_uri: URI for the integration. """ method = self._normalize_method_name(method) if self.has_integration(path, method): raise ValueError("Lambda integration already exists on Path={}, Method={}".format(path, method)) self.add_path(path, method) # Wrap the integration_uri in a Condition if one exists on that function # This is necessary so CFN doesn't try to resolve the integration reference. if condition: integration_uri = make_conditional(condition, integration_uri) path_dict = self.get_path(path) path_dict[method][self._X_APIGW_INTEGRATION] = { 'type': 'aws_proxy', 'httpMethod': 'POST', 'uri': integration_uri } method_auth_config = method_auth_config or {} api_auth_config = api_auth_config or {} if method_auth_config.get('Authorizer') == 'AWS_IAM' \ or api_auth_config.get('DefaultAuthorizer') == 'AWS_IAM' and not method_auth_config: self.paths[path][method][self._X_APIGW_INTEGRATION]['credentials'] = self._generate_integration_credentials( method_invoke_role=method_auth_config.get('InvokeRole'), api_invoke_role=api_auth_config.get('InvokeRole') ) # If 'responses' key is *not* present, add it with an empty dict as value path_dict[method].setdefault('responses', {}) # If a condition is present, wrap all method contents up into the condition if condition: path_dict[method] = make_conditional(condition, path_dict[method])
[ "def", "add_lambda_integration", "(", "self", ",", "path", ",", "method", ",", "integration_uri", ",", "method_auth_config", "=", "None", ",", "api_auth_config", "=", "None", ",", "condition", "=", "None", ")", ":", "method", "=", "self", ".", "_normalize_method_name", "(", "method", ")", "if", "self", ".", "has_integration", "(", "path", ",", "method", ")", ":", "raise", "ValueError", "(", "\"Lambda integration already exists on Path={}, Method={}\"", ".", "format", "(", "path", ",", "method", ")", ")", "self", ".", "add_path", "(", "path", ",", "method", ")", "# Wrap the integration_uri in a Condition if one exists on that function", "# This is necessary so CFN doesn't try to resolve the integration reference.", "if", "condition", ":", "integration_uri", "=", "make_conditional", "(", "condition", ",", "integration_uri", ")", "path_dict", "=", "self", ".", "get_path", "(", "path", ")", "path_dict", "[", "method", "]", "[", "self", ".", "_X_APIGW_INTEGRATION", "]", "=", "{", "'type'", ":", "'aws_proxy'", ",", "'httpMethod'", ":", "'POST'", ",", "'uri'", ":", "integration_uri", "}", "method_auth_config", "=", "method_auth_config", "or", "{", "}", "api_auth_config", "=", "api_auth_config", "or", "{", "}", "if", "method_auth_config", ".", "get", "(", "'Authorizer'", ")", "==", "'AWS_IAM'", "or", "api_auth_config", ".", "get", "(", "'DefaultAuthorizer'", ")", "==", "'AWS_IAM'", "and", "not", "method_auth_config", ":", "self", ".", "paths", "[", "path", "]", "[", "method", "]", "[", "self", ".", "_X_APIGW_INTEGRATION", "]", "[", "'credentials'", "]", "=", "self", ".", "_generate_integration_credentials", "(", "method_invoke_role", "=", "method_auth_config", ".", "get", "(", "'InvokeRole'", ")", ",", "api_invoke_role", "=", "api_auth_config", ".", "get", "(", "'InvokeRole'", ")", ")", "# If 'responses' key is *not* present, add it with an empty dict as value", "path_dict", "[", "method", "]", ".", "setdefault", "(", "'responses'", ",", "{", "}", ")", "# If a condition is present, wrap all method contents up into the condition", "if", "condition", ":", "path_dict", "[", "method", "]", "=", "make_conditional", "(", "condition", ",", "path_dict", "[", "method", "]", ")" ]
Adds aws_proxy APIGW integration to the given path+method. :param string path: Path name :param string method: HTTP Method :param string integration_uri: URI for the integration.
[ "Adds", "aws_proxy", "APIGW", "integration", "to", "the", "given", "path", "+", "method", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L137-L179
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.make_path_conditional
def make_path_conditional(self, path, condition): """ Wrap entire API path definition in a CloudFormation if condition. """ self.paths[path] = make_conditional(condition, self.paths[path])
python
def make_path_conditional(self, path, condition): """ Wrap entire API path definition in a CloudFormation if condition. """ self.paths[path] = make_conditional(condition, self.paths[path])
[ "def", "make_path_conditional", "(", "self", ",", "path", ",", "condition", ")", ":", "self", ".", "paths", "[", "path", "]", "=", "make_conditional", "(", "condition", ",", "self", ".", "paths", "[", "path", "]", ")" ]
Wrap entire API path definition in a CloudFormation if condition.
[ "Wrap", "entire", "API", "path", "definition", "in", "a", "CloudFormation", "if", "condition", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L181-L185
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.add_cors
def add_cors(self, path, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): """ Add CORS configuration to this path. Specifically, we will add a OPTIONS response config to the Swagger that will return headers required for CORS. Since SAM uses aws_proxy integration, we cannot inject the headers into the actual response returned from Lambda function. This is something customers have to implement themselves. If OPTIONS method is already present for the Path, we will skip adding CORS configuration Following this guide: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool :param string path: Path to add the CORS configuration to. :param string/dict allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool/None allow_credentials: Flags whether request is allowed to contain credentials. :raises ValueError: When values for one of the allowed_* variables is empty """ # Skip if Options is already present if self.has_path(path, self._OPTIONS_METHOD): return if not allowed_origins: raise ValueError("Invalid input. Value for AllowedOrigins is required") if not allowed_methods: # AllowMethods is not given. Let's try to generate the list from the given Swagger. allowed_methods = self._make_cors_allowed_methods_for_path(path) # APIGW expects the value to be a "string expression". Hence wrap in another quote. Ex: "'GET,POST,DELETE'" allowed_methods = "'{}'".format(allowed_methods) if allow_credentials is not True: allow_credentials = False # Add the Options method and the CORS response self.add_path(path, self._OPTIONS_METHOD) self.get_path(path)[self._OPTIONS_METHOD] = self._options_method_response_for_cors(allowed_origins, allowed_headers, allowed_methods, max_age, allow_credentials)
python
def add_cors(self, path, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): """ Add CORS configuration to this path. Specifically, we will add a OPTIONS response config to the Swagger that will return headers required for CORS. Since SAM uses aws_proxy integration, we cannot inject the headers into the actual response returned from Lambda function. This is something customers have to implement themselves. If OPTIONS method is already present for the Path, we will skip adding CORS configuration Following this guide: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool :param string path: Path to add the CORS configuration to. :param string/dict allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool/None allow_credentials: Flags whether request is allowed to contain credentials. :raises ValueError: When values for one of the allowed_* variables is empty """ # Skip if Options is already present if self.has_path(path, self._OPTIONS_METHOD): return if not allowed_origins: raise ValueError("Invalid input. Value for AllowedOrigins is required") if not allowed_methods: # AllowMethods is not given. Let's try to generate the list from the given Swagger. allowed_methods = self._make_cors_allowed_methods_for_path(path) # APIGW expects the value to be a "string expression". Hence wrap in another quote. Ex: "'GET,POST,DELETE'" allowed_methods = "'{}'".format(allowed_methods) if allow_credentials is not True: allow_credentials = False # Add the Options method and the CORS response self.add_path(path, self._OPTIONS_METHOD) self.get_path(path)[self._OPTIONS_METHOD] = self._options_method_response_for_cors(allowed_origins, allowed_headers, allowed_methods, max_age, allow_credentials)
[ "def", "add_cors", "(", "self", ",", "path", ",", "allowed_origins", ",", "allowed_headers", "=", "None", ",", "allowed_methods", "=", "None", ",", "max_age", "=", "None", ",", "allow_credentials", "=", "None", ")", ":", "# Skip if Options is already present", "if", "self", ".", "has_path", "(", "path", ",", "self", ".", "_OPTIONS_METHOD", ")", ":", "return", "if", "not", "allowed_origins", ":", "raise", "ValueError", "(", "\"Invalid input. Value for AllowedOrigins is required\"", ")", "if", "not", "allowed_methods", ":", "# AllowMethods is not given. Let's try to generate the list from the given Swagger.", "allowed_methods", "=", "self", ".", "_make_cors_allowed_methods_for_path", "(", "path", ")", "# APIGW expects the value to be a \"string expression\". Hence wrap in another quote. Ex: \"'GET,POST,DELETE'\"", "allowed_methods", "=", "\"'{}'\"", ".", "format", "(", "allowed_methods", ")", "if", "allow_credentials", "is", "not", "True", ":", "allow_credentials", "=", "False", "# Add the Options method and the CORS response", "self", ".", "add_path", "(", "path", ",", "self", ".", "_OPTIONS_METHOD", ")", "self", ".", "get_path", "(", "path", ")", "[", "self", ".", "_OPTIONS_METHOD", "]", "=", "self", ".", "_options_method_response_for_cors", "(", "allowed_origins", ",", "allowed_headers", ",", "allowed_methods", ",", "max_age", ",", "allow_credentials", ")" ]
Add CORS configuration to this path. Specifically, we will add a OPTIONS response config to the Swagger that will return headers required for CORS. Since SAM uses aws_proxy integration, we cannot inject the headers into the actual response returned from Lambda function. This is something customers have to implement themselves. If OPTIONS method is already present for the Path, we will skip adding CORS configuration Following this guide: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool :param string path: Path to add the CORS configuration to. :param string/dict allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool/None allow_credentials: Flags whether request is allowed to contain credentials. :raises ValueError: When values for one of the allowed_* variables is empty
[ "Add", "CORS", "configuration", "to", "this", "path", ".", "Specifically", "we", "will", "add", "a", "OPTIONS", "response", "config", "to", "the", "Swagger", "that", "will", "return", "headers", "required", "for", "CORS", ".", "Since", "SAM", "uses", "aws_proxy", "integration", "we", "cannot", "inject", "the", "headers", "into", "the", "actual", "response", "returned", "from", "Lambda", "function", ".", "This", "is", "something", "customers", "have", "to", "implement", "themselves", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L205-L254
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor._options_method_response_for_cors
def _options_method_response_for_cors(self, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): """ Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS. This snippet is taken from public documentation: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool :param string/dict allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool allow_credentials: Flags whether request is allowed to contain credentials. :return dict: Dictionary containing Options method configuration for CORS """ ALLOW_ORIGIN = "Access-Control-Allow-Origin" ALLOW_HEADERS = "Access-Control-Allow-Headers" ALLOW_METHODS = "Access-Control-Allow-Methods" MAX_AGE = "Access-Control-Max-Age" ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials" HEADER_RESPONSE = (lambda x: "method.response.header." + x) response_parameters = { # AllowedOrigin is always required HEADER_RESPONSE(ALLOW_ORIGIN): allowed_origins } response_headers = { # Allow Origin is always required ALLOW_ORIGIN: { "type": "string" } } # Optional values. Skip the header if value is empty # # The values must not be empty string or null. Also, value of '*' is a very recent addition (2017) and # not supported in all the browsers. So it is important to skip the header if value is not given # https://fetch.spec.whatwg.org/#http-new-header-syntax # if allowed_headers: response_parameters[HEADER_RESPONSE(ALLOW_HEADERS)] = allowed_headers response_headers[ALLOW_HEADERS] = {"type": "string"} if allowed_methods: response_parameters[HEADER_RESPONSE(ALLOW_METHODS)] = allowed_methods response_headers[ALLOW_METHODS] = {"type": "string"} if max_age is not None: # MaxAge can be set to 0, which is a valid value. So explicitly check against None response_parameters[HEADER_RESPONSE(MAX_AGE)] = max_age response_headers[MAX_AGE] = {"type": "integer"} if allow_credentials is True: # Allow-Credentials only has a valid value of true, it should be omitted otherwise. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials response_parameters[HEADER_RESPONSE(ALLOW_CREDENTIALS)] = "'true'" response_headers[ALLOW_CREDENTIALS] = {"type": "string"} return { "summary": "CORS support", "consumes": ["application/json"], "produces": ["application/json"], self._X_APIGW_INTEGRATION: { "type": "mock", "requestTemplates": { "application/json": "{\n \"statusCode\" : 200\n}\n" }, "responses": { "default": { "statusCode": "200", "responseParameters": response_parameters, "responseTemplates": { "application/json": "{}\n" } } } }, "responses": { "200": { "description": "Default response for CORS method", "headers": response_headers } } }
python
def _options_method_response_for_cors(self, allowed_origins, allowed_headers=None, allowed_methods=None, max_age=None, allow_credentials=None): """ Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS. This snippet is taken from public documentation: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool :param string/dict allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool allow_credentials: Flags whether request is allowed to contain credentials. :return dict: Dictionary containing Options method configuration for CORS """ ALLOW_ORIGIN = "Access-Control-Allow-Origin" ALLOW_HEADERS = "Access-Control-Allow-Headers" ALLOW_METHODS = "Access-Control-Allow-Methods" MAX_AGE = "Access-Control-Max-Age" ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials" HEADER_RESPONSE = (lambda x: "method.response.header." + x) response_parameters = { # AllowedOrigin is always required HEADER_RESPONSE(ALLOW_ORIGIN): allowed_origins } response_headers = { # Allow Origin is always required ALLOW_ORIGIN: { "type": "string" } } # Optional values. Skip the header if value is empty # # The values must not be empty string or null. Also, value of '*' is a very recent addition (2017) and # not supported in all the browsers. So it is important to skip the header if value is not given # https://fetch.spec.whatwg.org/#http-new-header-syntax # if allowed_headers: response_parameters[HEADER_RESPONSE(ALLOW_HEADERS)] = allowed_headers response_headers[ALLOW_HEADERS] = {"type": "string"} if allowed_methods: response_parameters[HEADER_RESPONSE(ALLOW_METHODS)] = allowed_methods response_headers[ALLOW_METHODS] = {"type": "string"} if max_age is not None: # MaxAge can be set to 0, which is a valid value. So explicitly check against None response_parameters[HEADER_RESPONSE(MAX_AGE)] = max_age response_headers[MAX_AGE] = {"type": "integer"} if allow_credentials is True: # Allow-Credentials only has a valid value of true, it should be omitted otherwise. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials response_parameters[HEADER_RESPONSE(ALLOW_CREDENTIALS)] = "'true'" response_headers[ALLOW_CREDENTIALS] = {"type": "string"} return { "summary": "CORS support", "consumes": ["application/json"], "produces": ["application/json"], self._X_APIGW_INTEGRATION: { "type": "mock", "requestTemplates": { "application/json": "{\n \"statusCode\" : 200\n}\n" }, "responses": { "default": { "statusCode": "200", "responseParameters": response_parameters, "responseTemplates": { "application/json": "{}\n" } } } }, "responses": { "200": { "description": "Default response for CORS method", "headers": response_headers } } }
[ "def", "_options_method_response_for_cors", "(", "self", ",", "allowed_origins", ",", "allowed_headers", "=", "None", ",", "allowed_methods", "=", "None", ",", "max_age", "=", "None", ",", "allow_credentials", "=", "None", ")", ":", "ALLOW_ORIGIN", "=", "\"Access-Control-Allow-Origin\"", "ALLOW_HEADERS", "=", "\"Access-Control-Allow-Headers\"", "ALLOW_METHODS", "=", "\"Access-Control-Allow-Methods\"", "MAX_AGE", "=", "\"Access-Control-Max-Age\"", "ALLOW_CREDENTIALS", "=", "\"Access-Control-Allow-Credentials\"", "HEADER_RESPONSE", "=", "(", "lambda", "x", ":", "\"method.response.header.\"", "+", "x", ")", "response_parameters", "=", "{", "# AllowedOrigin is always required", "HEADER_RESPONSE", "(", "ALLOW_ORIGIN", ")", ":", "allowed_origins", "}", "response_headers", "=", "{", "# Allow Origin is always required", "ALLOW_ORIGIN", ":", "{", "\"type\"", ":", "\"string\"", "}", "}", "# Optional values. Skip the header if value is empty", "#", "# The values must not be empty string or null. Also, value of '*' is a very recent addition (2017) and", "# not supported in all the browsers. So it is important to skip the header if value is not given", "# https://fetch.spec.whatwg.org/#http-new-header-syntax", "#", "if", "allowed_headers", ":", "response_parameters", "[", "HEADER_RESPONSE", "(", "ALLOW_HEADERS", ")", "]", "=", "allowed_headers", "response_headers", "[", "ALLOW_HEADERS", "]", "=", "{", "\"type\"", ":", "\"string\"", "}", "if", "allowed_methods", ":", "response_parameters", "[", "HEADER_RESPONSE", "(", "ALLOW_METHODS", ")", "]", "=", "allowed_methods", "response_headers", "[", "ALLOW_METHODS", "]", "=", "{", "\"type\"", ":", "\"string\"", "}", "if", "max_age", "is", "not", "None", ":", "# MaxAge can be set to 0, which is a valid value. So explicitly check against None", "response_parameters", "[", "HEADER_RESPONSE", "(", "MAX_AGE", ")", "]", "=", "max_age", "response_headers", "[", "MAX_AGE", "]", "=", "{", "\"type\"", ":", "\"integer\"", "}", "if", "allow_credentials", "is", "True", ":", "# Allow-Credentials only has a valid value of true, it should be omitted otherwise.", "# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials", "response_parameters", "[", "HEADER_RESPONSE", "(", "ALLOW_CREDENTIALS", ")", "]", "=", "\"'true'\"", "response_headers", "[", "ALLOW_CREDENTIALS", "]", "=", "{", "\"type\"", ":", "\"string\"", "}", "return", "{", "\"summary\"", ":", "\"CORS support\"", ",", "\"consumes\"", ":", "[", "\"application/json\"", "]", ",", "\"produces\"", ":", "[", "\"application/json\"", "]", ",", "self", ".", "_X_APIGW_INTEGRATION", ":", "{", "\"type\"", ":", "\"mock\"", ",", "\"requestTemplates\"", ":", "{", "\"application/json\"", ":", "\"{\\n \\\"statusCode\\\" : 200\\n}\\n\"", "}", ",", "\"responses\"", ":", "{", "\"default\"", ":", "{", "\"statusCode\"", ":", "\"200\"", ",", "\"responseParameters\"", ":", "response_parameters", ",", "\"responseTemplates\"", ":", "{", "\"application/json\"", ":", "\"{}\\n\"", "}", "}", "}", "}", ",", "\"responses\"", ":", "{", "\"200\"", ":", "{", "\"description\"", ":", "\"Default response for CORS method\"", ",", "\"headers\"", ":", "response_headers", "}", "}", "}" ]
Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS. This snippet is taken from public documentation: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html#enable-cors-for-resource-using-swagger-importer-tool :param string/dict allowed_origins: Comma separate list of allowed origins. Value can also be an intrinsic function dict. :param string/dict allowed_headers: Comma separated list of allowed headers. Value can also be an intrinsic function dict. :param string/dict allowed_methods: Comma separated list of allowed methods. Value can also be an intrinsic function dict. :param integer/dict max_age: Maximum duration to cache the CORS Preflight request. Value is set on Access-Control-Max-Age header. Value can also be an intrinsic function dict. :param bool allow_credentials: Flags whether request is allowed to contain credentials. :return dict: Dictionary containing Options method configuration for CORS
[ "Returns", "a", "Swagger", "snippet", "containing", "configuration", "for", "OPTIONS", "HTTP", "Method", "to", "configure", "CORS", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L256-L343
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor._make_cors_allowed_methods_for_path
def _make_cors_allowed_methods_for_path(self, path): """ Creates the value for Access-Control-Allow-Methods header for given path. All HTTP methods defined for this path will be included in the result. If the path contains "ANY" method, then *all available* HTTP methods will be returned as result. :param string path: Path to generate AllowMethods value for :return string: String containing the value of AllowMethods, if the path contains any methods. Empty string, otherwise """ # https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html all_http_methods = ["OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"] if not self.has_path(path): return "" # At this point, value of Swagger path should be a dictionary with method names being the keys methods = list(self.get_path(path).keys()) if self._X_ANY_METHOD in methods: # API Gateway's ANY method is not a real HTTP method but a wildcard representing all HTTP methods allow_methods = all_http_methods else: allow_methods = methods allow_methods.append("options") # Always add Options to the CORS methods response # Clean up the result: # # - HTTP Methods **must** be upper case and they are case sensitive. # (https://tools.ietf.org/html/rfc7231#section-4.1) # - Convert to set to remove any duplicates # - Sort to keep this list stable because it could be constructed from dictionary keys which are *not* ordered. # Therefore we might get back a different list each time the code runs. To prevent any unnecessary # regression, we sort the list so the returned value is stable. allow_methods = list({m.upper() for m in allow_methods}) allow_methods.sort() # Allow-Methods is comma separated string return ','.join(allow_methods)
python
def _make_cors_allowed_methods_for_path(self, path): """ Creates the value for Access-Control-Allow-Methods header for given path. All HTTP methods defined for this path will be included in the result. If the path contains "ANY" method, then *all available* HTTP methods will be returned as result. :param string path: Path to generate AllowMethods value for :return string: String containing the value of AllowMethods, if the path contains any methods. Empty string, otherwise """ # https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html all_http_methods = ["OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"] if not self.has_path(path): return "" # At this point, value of Swagger path should be a dictionary with method names being the keys methods = list(self.get_path(path).keys()) if self._X_ANY_METHOD in methods: # API Gateway's ANY method is not a real HTTP method but a wildcard representing all HTTP methods allow_methods = all_http_methods else: allow_methods = methods allow_methods.append("options") # Always add Options to the CORS methods response # Clean up the result: # # - HTTP Methods **must** be upper case and they are case sensitive. # (https://tools.ietf.org/html/rfc7231#section-4.1) # - Convert to set to remove any duplicates # - Sort to keep this list stable because it could be constructed from dictionary keys which are *not* ordered. # Therefore we might get back a different list each time the code runs. To prevent any unnecessary # regression, we sort the list so the returned value is stable. allow_methods = list({m.upper() for m in allow_methods}) allow_methods.sort() # Allow-Methods is comma separated string return ','.join(allow_methods)
[ "def", "_make_cors_allowed_methods_for_path", "(", "self", ",", "path", ")", ":", "# https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html", "all_http_methods", "=", "[", "\"OPTIONS\"", ",", "\"GET\"", ",", "\"HEAD\"", ",", "\"POST\"", ",", "\"PUT\"", ",", "\"DELETE\"", ",", "\"PATCH\"", "]", "if", "not", "self", ".", "has_path", "(", "path", ")", ":", "return", "\"\"", "# At this point, value of Swagger path should be a dictionary with method names being the keys", "methods", "=", "list", "(", "self", ".", "get_path", "(", "path", ")", ".", "keys", "(", ")", ")", "if", "self", ".", "_X_ANY_METHOD", "in", "methods", ":", "# API Gateway's ANY method is not a real HTTP method but a wildcard representing all HTTP methods", "allow_methods", "=", "all_http_methods", "else", ":", "allow_methods", "=", "methods", "allow_methods", ".", "append", "(", "\"options\"", ")", "# Always add Options to the CORS methods response", "# Clean up the result:", "#", "# - HTTP Methods **must** be upper case and they are case sensitive.", "# (https://tools.ietf.org/html/rfc7231#section-4.1)", "# - Convert to set to remove any duplicates", "# - Sort to keep this list stable because it could be constructed from dictionary keys which are *not* ordered.", "# Therefore we might get back a different list each time the code runs. To prevent any unnecessary", "# regression, we sort the list so the returned value is stable.", "allow_methods", "=", "list", "(", "{", "m", ".", "upper", "(", ")", "for", "m", "in", "allow_methods", "}", ")", "allow_methods", ".", "sort", "(", ")", "# Allow-Methods is comma separated string", "return", "','", ".", "join", "(", "allow_methods", ")" ]
Creates the value for Access-Control-Allow-Methods header for given path. All HTTP methods defined for this path will be included in the result. If the path contains "ANY" method, then *all available* HTTP methods will be returned as result. :param string path: Path to generate AllowMethods value for :return string: String containing the value of AllowMethods, if the path contains any methods. Empty string, otherwise
[ "Creates", "the", "value", "for", "Access", "-", "Control", "-", "Allow", "-", "Methods", "header", "for", "given", "path", ".", "All", "HTTP", "methods", "defined", "for", "this", "path", "will", "be", "included", "in", "the", "result", ".", "If", "the", "path", "contains", "ANY", "method", "then", "*", "all", "available", "*", "HTTP", "methods", "will", "be", "returned", "as", "result", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L345-L384
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.add_authorizers
def add_authorizers(self, authorizers): """ Add Authorizer definitions to the securityDefinitions part of Swagger. :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions. """ self.security_definitions = self.security_definitions or {} for authorizer_name, authorizer in authorizers.items(): self.security_definitions[authorizer_name] = authorizer.generate_swagger()
python
def add_authorizers(self, authorizers): """ Add Authorizer definitions to the securityDefinitions part of Swagger. :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions. """ self.security_definitions = self.security_definitions or {} for authorizer_name, authorizer in authorizers.items(): self.security_definitions[authorizer_name] = authorizer.generate_swagger()
[ "def", "add_authorizers", "(", "self", ",", "authorizers", ")", ":", "self", ".", "security_definitions", "=", "self", ".", "security_definitions", "or", "{", "}", "for", "authorizer_name", ",", "authorizer", "in", "authorizers", ".", "items", "(", ")", ":", "self", ".", "security_definitions", "[", "authorizer_name", "]", "=", "authorizer", ".", "generate_swagger", "(", ")" ]
Add Authorizer definitions to the securityDefinitions part of Swagger. :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions.
[ "Add", "Authorizer", "definitions", "to", "the", "securityDefinitions", "part", "of", "Swagger", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L386-L395
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.set_path_default_authorizer
def set_path_default_authorizer(self, path, default_authorizer, authorizers): """ Sets the DefaultAuthorizer for each method on this path. The DefaultAuthorizer won't be set if an Authorizer was defined at the Function/Path/Method level :param string path: Path name :param string default_authorizer: Name of the authorizer to use as the default. Must be a key in the authorizers param. :param list authorizers: List of Authorizer configurations defined on the related Api. """ for method_name, method in self.get_path(path).items(): self.set_method_authorizer(path, method_name, default_authorizer, authorizers, default_authorizer=default_authorizer, is_default=True)
python
def set_path_default_authorizer(self, path, default_authorizer, authorizers): """ Sets the DefaultAuthorizer for each method on this path. The DefaultAuthorizer won't be set if an Authorizer was defined at the Function/Path/Method level :param string path: Path name :param string default_authorizer: Name of the authorizer to use as the default. Must be a key in the authorizers param. :param list authorizers: List of Authorizer configurations defined on the related Api. """ for method_name, method in self.get_path(path).items(): self.set_method_authorizer(path, method_name, default_authorizer, authorizers, default_authorizer=default_authorizer, is_default=True)
[ "def", "set_path_default_authorizer", "(", "self", ",", "path", ",", "default_authorizer", ",", "authorizers", ")", ":", "for", "method_name", ",", "method", "in", "self", ".", "get_path", "(", "path", ")", ".", "items", "(", ")", ":", "self", ".", "set_method_authorizer", "(", "path", ",", "method_name", ",", "default_authorizer", ",", "authorizers", ",", "default_authorizer", "=", "default_authorizer", ",", "is_default", "=", "True", ")" ]
Sets the DefaultAuthorizer for each method on this path. The DefaultAuthorizer won't be set if an Authorizer was defined at the Function/Path/Method level :param string path: Path name :param string default_authorizer: Name of the authorizer to use as the default. Must be a key in the authorizers param. :param list authorizers: List of Authorizer configurations defined on the related Api.
[ "Sets", "the", "DefaultAuthorizer", "for", "each", "method", "on", "this", "path", ".", "The", "DefaultAuthorizer", "won", "t", "be", "set", "if", "an", "Authorizer", "was", "defined", "at", "the", "Function", "/", "Path", "/", "Method", "level" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L397-L409
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.add_auth_to_method
def add_auth_to_method(self, path, method_name, auth, api): """ Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers but this method will eventually include setting other auth settings such as API Key, Resource Policy, etc. :param string path: Path name :param string method_name: Method name :param dict auth: Auth configuration such as Authorizers, ApiKey, ResourcePolicy (only Authorizers supported currently) :param dict api: Reference to the related Api's properties as defined in the template. """ method_authorizer = auth and auth.get('Authorizer') if method_authorizer: api_auth = api.get('Auth') api_authorizers = api_auth and api_auth.get('Authorizers') default_authorizer = api_auth and api_auth.get('DefaultAuthorizer') self.set_method_authorizer(path, method_name, method_authorizer, api_authorizers, default_authorizer)
python
def add_auth_to_method(self, path, method_name, auth, api): """ Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers but this method will eventually include setting other auth settings such as API Key, Resource Policy, etc. :param string path: Path name :param string method_name: Method name :param dict auth: Auth configuration such as Authorizers, ApiKey, ResourcePolicy (only Authorizers supported currently) :param dict api: Reference to the related Api's properties as defined in the template. """ method_authorizer = auth and auth.get('Authorizer') if method_authorizer: api_auth = api.get('Auth') api_authorizers = api_auth and api_auth.get('Authorizers') default_authorizer = api_auth and api_auth.get('DefaultAuthorizer') self.set_method_authorizer(path, method_name, method_authorizer, api_authorizers, default_authorizer)
[ "def", "add_auth_to_method", "(", "self", ",", "path", ",", "method_name", ",", "auth", ",", "api", ")", ":", "method_authorizer", "=", "auth", "and", "auth", ".", "get", "(", "'Authorizer'", ")", "if", "method_authorizer", ":", "api_auth", "=", "api", ".", "get", "(", "'Auth'", ")", "api_authorizers", "=", "api_auth", "and", "api_auth", ".", "get", "(", "'Authorizers'", ")", "default_authorizer", "=", "api_auth", "and", "api_auth", ".", "get", "(", "'DefaultAuthorizer'", ")", "self", ".", "set_method_authorizer", "(", "path", ",", "method_name", ",", "method_authorizer", ",", "api_authorizers", ",", "default_authorizer", ")" ]
Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers but this method will eventually include setting other auth settings such as API Key, Resource Policy, etc. :param string path: Path name :param string method_name: Method name :param dict auth: Auth configuration such as Authorizers, ApiKey, ResourcePolicy (only Authorizers supported currently) :param dict api: Reference to the related Api's properties as defined in the template.
[ "Adds", "auth", "settings", "for", "this", "path", "/", "method", ".", "Auth", "settings", "currently", "consist", "solely", "of", "Authorizers", "but", "this", "method", "will", "eventually", "include", "setting", "other", "auth", "settings", "such", "as", "API", "Key", "Resource", "Policy", "etc", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L411-L429
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.add_gateway_responses
def add_gateway_responses(self, gateway_responses): """ Add Gateway Response definitions to Swagger. :param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated. """ self.gateway_responses = self.gateway_responses or {} for response_type, response in gateway_responses.items(): self.gateway_responses[response_type] = response.generate_swagger()
python
def add_gateway_responses(self, gateway_responses): """ Add Gateway Response definitions to Swagger. :param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated. """ self.gateway_responses = self.gateway_responses or {} for response_type, response in gateway_responses.items(): self.gateway_responses[response_type] = response.generate_swagger()
[ "def", "add_gateway_responses", "(", "self", ",", "gateway_responses", ")", ":", "self", ".", "gateway_responses", "=", "self", ".", "gateway_responses", "or", "{", "}", "for", "response_type", ",", "response", "in", "gateway_responses", ".", "items", "(", ")", ":", "self", ".", "gateway_responses", "[", "response_type", "]", "=", "response", ".", "generate_swagger", "(", ")" ]
Add Gateway Response definitions to Swagger. :param dict gateway_responses: Dictionary of GatewayResponse configuration which gets translated.
[ "Add", "Gateway", "Response", "definitions", "to", "Swagger", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L516-L525
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.swagger
def swagger(self): """ Returns a **copy** of the Swagger document as a dictionary. :return dict: Dictionary containing the Swagger document """ # Make sure any changes to the paths are reflected back in output self._doc["paths"] = self.paths if self.security_definitions: self._doc["securityDefinitions"] = self.security_definitions if self.gateway_responses: self._doc[self._X_APIGW_GATEWAY_RESPONSES] = self.gateway_responses return copy.deepcopy(self._doc)
python
def swagger(self): """ Returns a **copy** of the Swagger document as a dictionary. :return dict: Dictionary containing the Swagger document """ # Make sure any changes to the paths are reflected back in output self._doc["paths"] = self.paths if self.security_definitions: self._doc["securityDefinitions"] = self.security_definitions if self.gateway_responses: self._doc[self._X_APIGW_GATEWAY_RESPONSES] = self.gateway_responses return copy.deepcopy(self._doc)
[ "def", "swagger", "(", "self", ")", ":", "# Make sure any changes to the paths are reflected back in output", "self", ".", "_doc", "[", "\"paths\"", "]", "=", "self", ".", "paths", "if", "self", ".", "security_definitions", ":", "self", ".", "_doc", "[", "\"securityDefinitions\"", "]", "=", "self", ".", "security_definitions", "if", "self", ".", "gateway_responses", ":", "self", ".", "_doc", "[", "self", ".", "_X_APIGW_GATEWAY_RESPONSES", "]", "=", "self", ".", "gateway_responses", "return", "copy", ".", "deepcopy", "(", "self", ".", "_doc", ")" ]
Returns a **copy** of the Swagger document as a dictionary. :return dict: Dictionary containing the Swagger document
[ "Returns", "a", "**", "copy", "**", "of", "the", "Swagger", "document", "as", "a", "dictionary", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L528-L543
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor.is_valid
def is_valid(data): """ Checks if the input data is a Swagger document :param dict data: Data to be validated :return: True, if data is a Swagger """ return bool(data) and \ isinstance(data, dict) and \ bool(data.get("swagger")) and \ isinstance(data.get('paths'), dict)
python
def is_valid(data): """ Checks if the input data is a Swagger document :param dict data: Data to be validated :return: True, if data is a Swagger """ return bool(data) and \ isinstance(data, dict) and \ bool(data.get("swagger")) and \ isinstance(data.get('paths'), dict)
[ "def", "is_valid", "(", "data", ")", ":", "return", "bool", "(", "data", ")", "and", "isinstance", "(", "data", ",", "dict", ")", "and", "bool", "(", "data", ".", "get", "(", "\"swagger\"", ")", ")", "and", "isinstance", "(", "data", ".", "get", "(", "'paths'", ")", ",", "dict", ")" ]
Checks if the input data is a Swagger document :param dict data: Data to be validated :return: True, if data is a Swagger
[ "Checks", "if", "the", "input", "data", "is", "a", "Swagger", "document" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L546-L556
train
awslabs/serverless-application-model
samtranslator/swagger/swagger.py
SwaggerEditor._normalize_method_name
def _normalize_method_name(method): """ Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods like "ANY" NOTE: Always normalize before using the `method` value passed in as input :param string method: Name of the HTTP Method :return string: Normalized method name """ if not method or not isinstance(method, string_types): return method method = method.lower() if method == 'any': return SwaggerEditor._X_ANY_METHOD else: return method
python
def _normalize_method_name(method): """ Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods like "ANY" NOTE: Always normalize before using the `method` value passed in as input :param string method: Name of the HTTP Method :return string: Normalized method name """ if not method or not isinstance(method, string_types): return method method = method.lower() if method == 'any': return SwaggerEditor._X_ANY_METHOD else: return method
[ "def", "_normalize_method_name", "(", "method", ")", ":", "if", "not", "method", "or", "not", "isinstance", "(", "method", ",", "string_types", ")", ":", "return", "method", "method", "=", "method", ".", "lower", "(", ")", "if", "method", "==", "'any'", ":", "return", "SwaggerEditor", ".", "_X_ANY_METHOD", "else", ":", "return", "method" ]
Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods like "ANY" NOTE: Always normalize before using the `method` value passed in as input :param string method: Name of the HTTP Method :return string: Normalized method name
[ "Returns", "a", "lower", "case", "normalized", "version", "of", "HTTP", "Method", ".", "It", "also", "know", "how", "to", "handle", "API", "Gateway", "specific", "methods", "like", "ANY" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/swagger/swagger.py#L576-L593
train
awslabs/serverless-application-model
samtranslator/plugins/globals/globals_plugin.py
GlobalsPlugin.on_before_transform_template
def on_before_transform_template(self, template_dict): """ Hook method that runs before a template gets transformed. In this method, we parse and process Globals section from the template (if present). :param dict template_dict: SAM template as a dictionary """ try: global_section = Globals(template_dict) except InvalidGlobalsSectionException as ex: raise InvalidDocumentException([ex]) # For each resource in template, try and merge with Globals if necessary template = SamTemplate(template_dict) for logicalId, resource in template.iterate(): resource.properties = global_section.merge(resource.type, resource.properties) template.set(logicalId, resource) # Remove the Globals section from template if necessary Globals.del_section(template_dict)
python
def on_before_transform_template(self, template_dict): """ Hook method that runs before a template gets transformed. In this method, we parse and process Globals section from the template (if present). :param dict template_dict: SAM template as a dictionary """ try: global_section = Globals(template_dict) except InvalidGlobalsSectionException as ex: raise InvalidDocumentException([ex]) # For each resource in template, try and merge with Globals if necessary template = SamTemplate(template_dict) for logicalId, resource in template.iterate(): resource.properties = global_section.merge(resource.type, resource.properties) template.set(logicalId, resource) # Remove the Globals section from template if necessary Globals.del_section(template_dict)
[ "def", "on_before_transform_template", "(", "self", ",", "template_dict", ")", ":", "try", ":", "global_section", "=", "Globals", "(", "template_dict", ")", "except", "InvalidGlobalsSectionException", "as", "ex", ":", "raise", "InvalidDocumentException", "(", "[", "ex", "]", ")", "# For each resource in template, try and merge with Globals if necessary", "template", "=", "SamTemplate", "(", "template_dict", ")", "for", "logicalId", ",", "resource", "in", "template", ".", "iterate", "(", ")", ":", "resource", ".", "properties", "=", "global_section", ".", "merge", "(", "resource", ".", "type", ",", "resource", ".", "properties", ")", "template", ".", "set", "(", "logicalId", ",", "resource", ")", "# Remove the Globals section from template if necessary", "Globals", ".", "del_section", "(", "template_dict", ")" ]
Hook method that runs before a template gets transformed. In this method, we parse and process Globals section from the template (if present). :param dict template_dict: SAM template as a dictionary
[ "Hook", "method", "that", "runs", "before", "a", "template", "gets", "transformed", ".", "In", "this", "method", "we", "parse", "and", "process", "Globals", "section", "from", "the", "template", "(", "if", "present", ")", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/globals/globals_plugin.py#L20-L40
train
awslabs/serverless-application-model
samtranslator/model/types.py
is_type
def is_type(valid_type): """Returns a validator function that succeeds only for inputs of the provided valid_type. :param type valid_type: the type that should be considered valid for the validator :returns: a function which returns True its input is an instance of valid_type, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): if not isinstance(value, valid_type): if should_raise: raise TypeError("Expected value of type {expected}, actual value was of type {actual}.".format( expected=valid_type, actual=type(value))) return False return True return validate
python
def is_type(valid_type): """Returns a validator function that succeeds only for inputs of the provided valid_type. :param type valid_type: the type that should be considered valid for the validator :returns: a function which returns True its input is an instance of valid_type, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): if not isinstance(value, valid_type): if should_raise: raise TypeError("Expected value of type {expected}, actual value was of type {actual}.".format( expected=valid_type, actual=type(value))) return False return True return validate
[ "def", "is_type", "(", "valid_type", ")", ":", "def", "validate", "(", "value", ",", "should_raise", "=", "True", ")", ":", "if", "not", "isinstance", "(", "value", ",", "valid_type", ")", ":", "if", "should_raise", ":", "raise", "TypeError", "(", "\"Expected value of type {expected}, actual value was of type {actual}.\"", ".", "format", "(", "expected", "=", "valid_type", ",", "actual", "=", "type", "(", "value", ")", ")", ")", "return", "False", "return", "True", "return", "validate" ]
Returns a validator function that succeeds only for inputs of the provided valid_type. :param type valid_type: the type that should be considered valid for the validator :returns: a function which returns True its input is an instance of valid_type, and raises TypeError otherwise :rtype: callable
[ "Returns", "a", "validator", "function", "that", "succeeds", "only", "for", "inputs", "of", "the", "provided", "valid_type", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/types.py#L15-L29
train
awslabs/serverless-application-model
samtranslator/model/types.py
list_of
def list_of(validate_item): """Returns a validator function that succeeds only if the input is a list, and each item in the list passes as input to the provided validator validate_item. :param callable validate_item: the validator function for items in the list :returns: a function which returns True its input is an list of valid items, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): validate_type = is_type(list) if not validate_type(value, should_raise=should_raise): return False for item in value: try: validate_item(item) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "list contained an invalid item") raise return False return True return validate
python
def list_of(validate_item): """Returns a validator function that succeeds only if the input is a list, and each item in the list passes as input to the provided validator validate_item. :param callable validate_item: the validator function for items in the list :returns: a function which returns True its input is an list of valid items, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): validate_type = is_type(list) if not validate_type(value, should_raise=should_raise): return False for item in value: try: validate_item(item) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "list contained an invalid item") raise return False return True return validate
[ "def", "list_of", "(", "validate_item", ")", ":", "def", "validate", "(", "value", ",", "should_raise", "=", "True", ")", ":", "validate_type", "=", "is_type", "(", "list", ")", "if", "not", "validate_type", "(", "value", ",", "should_raise", "=", "should_raise", ")", ":", "return", "False", "for", "item", "in", "value", ":", "try", ":", "validate_item", "(", "item", ")", "except", "TypeError", "as", "e", ":", "if", "should_raise", ":", "samtranslator", ".", "model", ".", "exceptions", ".", "prepend", "(", "e", ",", "\"list contained an invalid item\"", ")", "raise", "return", "False", "return", "True", "return", "validate" ]
Returns a validator function that succeeds only if the input is a list, and each item in the list passes as input to the provided validator validate_item. :param callable validate_item: the validator function for items in the list :returns: a function which returns True its input is an list of valid items, and raises TypeError otherwise :rtype: callable
[ "Returns", "a", "validator", "function", "that", "succeeds", "only", "if", "the", "input", "is", "a", "list", "and", "each", "item", "in", "the", "list", "passes", "as", "input", "to", "the", "provided", "validator", "validate_item", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/types.py#L32-L54
train
awslabs/serverless-application-model
samtranslator/model/types.py
dict_of
def dict_of(validate_key, validate_item): """Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes as input to the provided validators validate_key and validate_item, respectively. :param callable validate_key: the validator function for keys in the dict :param callable validate_item: the validator function for values in the list :returns: a function which returns True its input is an dict of valid items, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): validate_type = is_type(dict) if not validate_type(value, should_raise=should_raise): return False for key, item in value.items(): try: validate_key(key) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "dict contained an invalid key") raise return False try: validate_item(item) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "dict contained an invalid value") raise return False return True return validate
python
def dict_of(validate_key, validate_item): """Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes as input to the provided validators validate_key and validate_item, respectively. :param callable validate_key: the validator function for keys in the dict :param callable validate_item: the validator function for values in the list :returns: a function which returns True its input is an dict of valid items, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): validate_type = is_type(dict) if not validate_type(value, should_raise=should_raise): return False for key, item in value.items(): try: validate_key(key) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "dict contained an invalid key") raise return False try: validate_item(item) except TypeError as e: if should_raise: samtranslator.model.exceptions.prepend(e, "dict contained an invalid value") raise return False return True return validate
[ "def", "dict_of", "(", "validate_key", ",", "validate_item", ")", ":", "def", "validate", "(", "value", ",", "should_raise", "=", "True", ")", ":", "validate_type", "=", "is_type", "(", "dict", ")", "if", "not", "validate_type", "(", "value", ",", "should_raise", "=", "should_raise", ")", ":", "return", "False", "for", "key", ",", "item", "in", "value", ".", "items", "(", ")", ":", "try", ":", "validate_key", "(", "key", ")", "except", "TypeError", "as", "e", ":", "if", "should_raise", ":", "samtranslator", ".", "model", ".", "exceptions", ".", "prepend", "(", "e", ",", "\"dict contained an invalid key\"", ")", "raise", "return", "False", "try", ":", "validate_item", "(", "item", ")", "except", "TypeError", "as", "e", ":", "if", "should_raise", ":", "samtranslator", ".", "model", ".", "exceptions", ".", "prepend", "(", "e", ",", "\"dict contained an invalid value\"", ")", "raise", "return", "False", "return", "True", "return", "validate" ]
Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes as input to the provided validators validate_key and validate_item, respectively. :param callable validate_key: the validator function for keys in the dict :param callable validate_item: the validator function for values in the list :returns: a function which returns True its input is an dict of valid items, and raises TypeError otherwise :rtype: callable
[ "Returns", "a", "validator", "function", "that", "succeeds", "only", "if", "the", "input", "is", "a", "dict", "and", "each", "key", "and", "value", "in", "the", "dict", "passes", "as", "input", "to", "the", "provided", "validators", "validate_key", "and", "validate_item", "respectively", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/types.py#L57-L88
train
awslabs/serverless-application-model
samtranslator/model/types.py
one_of
def one_of(*validators): """Returns a validator function that succeeds only if the input passes at least one of the provided validators. :param callable validators: the validator functions :returns: a function which returns True its input passes at least one of the validators, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): if any(validate(value, should_raise=False) for validate in validators): return True if should_raise: raise TypeError("value did not match any allowable type") return False return validate
python
def one_of(*validators): """Returns a validator function that succeeds only if the input passes at least one of the provided validators. :param callable validators: the validator functions :returns: a function which returns True its input passes at least one of the validators, and raises TypeError otherwise :rtype: callable """ def validate(value, should_raise=True): if any(validate(value, should_raise=False) for validate in validators): return True if should_raise: raise TypeError("value did not match any allowable type") return False return validate
[ "def", "one_of", "(", "*", "validators", ")", ":", "def", "validate", "(", "value", ",", "should_raise", "=", "True", ")", ":", "if", "any", "(", "validate", "(", "value", ",", "should_raise", "=", "False", ")", "for", "validate", "in", "validators", ")", ":", "return", "True", "if", "should_raise", ":", "raise", "TypeError", "(", "\"value did not match any allowable type\"", ")", "return", "False", "return", "validate" ]
Returns a validator function that succeeds only if the input passes at least one of the provided validators. :param callable validators: the validator functions :returns: a function which returns True its input passes at least one of the validators, and raises TypeError otherwise :rtype: callable
[ "Returns", "a", "validator", "function", "that", "succeeds", "only", "if", "the", "input", "passes", "at", "least", "one", "of", "the", "provided", "validators", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/types.py#L91-L106
train
awslabs/serverless-application-model
samtranslator/policy_template_processor/template.py
Template.to_statement
def to_statement(self, parameter_values): """ With the given values for each parameter, this method will return a policy statement that can be used directly with IAM. :param dict parameter_values: Dict containing values for each parameter defined in the template :return dict: Dictionary containing policy statement :raises InvalidParameterValues: If parameter values is not a valid dictionary or does not contain values for all parameters :raises InsufficientParameterValues: If the parameter values don't have values for all required parameters """ missing = self.missing_parameter_values(parameter_values) if len(missing) > 0: # str() of elements of list to prevent any `u` prefix from being displayed in user-facing error message raise InsufficientParameterValues("Following required parameters of template '{}' don't have values: {}" .format(self.name, [str(m) for m in missing])) # Select only necessary parameter_values. this is to prevent malicious or accidental # injection of values for parameters not intended in the template. This is important because "Ref" resolution # will substitute any references for which a value is provided. necessary_parameter_values = {name: value for name, value in parameter_values.items() if name in self.parameters} # Only "Ref" is supported supported_intrinsics = { RefAction.intrinsic_name: RefAction() } resolver = IntrinsicsResolver(necessary_parameter_values, supported_intrinsics) definition_copy = copy.deepcopy(self.definition) return resolver.resolve_parameter_refs(definition_copy)
python
def to_statement(self, parameter_values): """ With the given values for each parameter, this method will return a policy statement that can be used directly with IAM. :param dict parameter_values: Dict containing values for each parameter defined in the template :return dict: Dictionary containing policy statement :raises InvalidParameterValues: If parameter values is not a valid dictionary or does not contain values for all parameters :raises InsufficientParameterValues: If the parameter values don't have values for all required parameters """ missing = self.missing_parameter_values(parameter_values) if len(missing) > 0: # str() of elements of list to prevent any `u` prefix from being displayed in user-facing error message raise InsufficientParameterValues("Following required parameters of template '{}' don't have values: {}" .format(self.name, [str(m) for m in missing])) # Select only necessary parameter_values. this is to prevent malicious or accidental # injection of values for parameters not intended in the template. This is important because "Ref" resolution # will substitute any references for which a value is provided. necessary_parameter_values = {name: value for name, value in parameter_values.items() if name in self.parameters} # Only "Ref" is supported supported_intrinsics = { RefAction.intrinsic_name: RefAction() } resolver = IntrinsicsResolver(necessary_parameter_values, supported_intrinsics) definition_copy = copy.deepcopy(self.definition) return resolver.resolve_parameter_refs(definition_copy)
[ "def", "to_statement", "(", "self", ",", "parameter_values", ")", ":", "missing", "=", "self", ".", "missing_parameter_values", "(", "parameter_values", ")", "if", "len", "(", "missing", ")", ">", "0", ":", "# str() of elements of list to prevent any `u` prefix from being displayed in user-facing error message", "raise", "InsufficientParameterValues", "(", "\"Following required parameters of template '{}' don't have values: {}\"", ".", "format", "(", "self", ".", "name", ",", "[", "str", "(", "m", ")", "for", "m", "in", "missing", "]", ")", ")", "# Select only necessary parameter_values. this is to prevent malicious or accidental", "# injection of values for parameters not intended in the template. This is important because \"Ref\" resolution", "# will substitute any references for which a value is provided.", "necessary_parameter_values", "=", "{", "name", ":", "value", "for", "name", ",", "value", "in", "parameter_values", ".", "items", "(", ")", "if", "name", "in", "self", ".", "parameters", "}", "# Only \"Ref\" is supported", "supported_intrinsics", "=", "{", "RefAction", ".", "intrinsic_name", ":", "RefAction", "(", ")", "}", "resolver", "=", "IntrinsicsResolver", "(", "necessary_parameter_values", ",", "supported_intrinsics", ")", "definition_copy", "=", "copy", ".", "deepcopy", "(", "self", ".", "definition", ")", "return", "resolver", ".", "resolve_parameter_refs", "(", "definition_copy", ")" ]
With the given values for each parameter, this method will return a policy statement that can be used directly with IAM. :param dict parameter_values: Dict containing values for each parameter defined in the template :return dict: Dictionary containing policy statement :raises InvalidParameterValues: If parameter values is not a valid dictionary or does not contain values for all parameters :raises InsufficientParameterValues: If the parameter values don't have values for all required parameters
[ "With", "the", "given", "values", "for", "each", "parameter", "this", "method", "will", "return", "a", "policy", "statement", "that", "can", "be", "used", "directly", "with", "IAM", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/policy_template_processor/template.py#L30-L62
train
awslabs/serverless-application-model
samtranslator/policy_template_processor/template.py
Template.missing_parameter_values
def missing_parameter_values(self, parameter_values): """ Checks if the given input contains values for all parameters used by this template :param dict parameter_values: Dictionary of values for each parameter used in the template :return list: List of names of parameters that are missing. :raises InvalidParameterValues: When parameter values is not a valid dictionary """ if not self._is_valid_parameter_values(parameter_values): raise InvalidParameterValues("Parameter values are required to process a policy template") return list(set(self.parameters.keys()) - set(parameter_values.keys()))
python
def missing_parameter_values(self, parameter_values): """ Checks if the given input contains values for all parameters used by this template :param dict parameter_values: Dictionary of values for each parameter used in the template :return list: List of names of parameters that are missing. :raises InvalidParameterValues: When parameter values is not a valid dictionary """ if not self._is_valid_parameter_values(parameter_values): raise InvalidParameterValues("Parameter values are required to process a policy template") return list(set(self.parameters.keys()) - set(parameter_values.keys()))
[ "def", "missing_parameter_values", "(", "self", ",", "parameter_values", ")", ":", "if", "not", "self", ".", "_is_valid_parameter_values", "(", "parameter_values", ")", ":", "raise", "InvalidParameterValues", "(", "\"Parameter values are required to process a policy template\"", ")", "return", "list", "(", "set", "(", "self", ".", "parameters", ".", "keys", "(", ")", ")", "-", "set", "(", "parameter_values", ".", "keys", "(", ")", ")", ")" ]
Checks if the given input contains values for all parameters used by this template :param dict parameter_values: Dictionary of values for each parameter used in the template :return list: List of names of parameters that are missing. :raises InvalidParameterValues: When parameter values is not a valid dictionary
[ "Checks", "if", "the", "given", "input", "contains", "values", "for", "all", "parameters", "used", "by", "this", "template" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/policy_template_processor/template.py#L64-L76
train
awslabs/serverless-application-model
samtranslator/policy_template_processor/template.py
Template.from_dict
def from_dict(template_name, template_values_dict): """ Parses the input and returns an instance of this class. :param string template_name: Name of the template :param dict template_values_dict: Dictionary containing the value of the template. This dict must have passed the JSON Schema validation. :return Template: Instance of this class containing the values provided in this dictionary """ parameters = template_values_dict.get("Parameters", {}) definition = template_values_dict.get("Definition", {}) return Template(template_name, parameters, definition)
python
def from_dict(template_name, template_values_dict): """ Parses the input and returns an instance of this class. :param string template_name: Name of the template :param dict template_values_dict: Dictionary containing the value of the template. This dict must have passed the JSON Schema validation. :return Template: Instance of this class containing the values provided in this dictionary """ parameters = template_values_dict.get("Parameters", {}) definition = template_values_dict.get("Definition", {}) return Template(template_name, parameters, definition)
[ "def", "from_dict", "(", "template_name", ",", "template_values_dict", ")", ":", "parameters", "=", "template_values_dict", ".", "get", "(", "\"Parameters\"", ",", "{", "}", ")", "definition", "=", "template_values_dict", ".", "get", "(", "\"Definition\"", ",", "{", "}", ")", "return", "Template", "(", "template_name", ",", "parameters", ",", "definition", ")" ]
Parses the input and returns an instance of this class. :param string template_name: Name of the template :param dict template_values_dict: Dictionary containing the value of the template. This dict must have passed the JSON Schema validation. :return Template: Instance of this class containing the values provided in this dictionary
[ "Parses", "the", "input", "and", "returns", "an", "instance", "of", "this", "class", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/policy_template_processor/template.py#L102-L115
train
awslabs/serverless-application-model
samtranslator/plugins/__init__.py
SamPlugins.register
def register(self, plugin): """ Register a plugin. New plugins are added to the end of the plugins list. :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks :raises ValueError: If plugin is not an instance of samtranslator.plugins.BasePlugin or if it is already registered :return: None """ if not plugin or not isinstance(plugin, BasePlugin): raise ValueError("Plugin must be implemented as a subclass of BasePlugin class") if self.is_registered(plugin.name): raise ValueError("Plugin with name {} is already registered".format(plugin.name)) self._plugins.append(plugin)
python
def register(self, plugin): """ Register a plugin. New plugins are added to the end of the plugins list. :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks :raises ValueError: If plugin is not an instance of samtranslator.plugins.BasePlugin or if it is already registered :return: None """ if not plugin or not isinstance(plugin, BasePlugin): raise ValueError("Plugin must be implemented as a subclass of BasePlugin class") if self.is_registered(plugin.name): raise ValueError("Plugin with name {} is already registered".format(plugin.name)) self._plugins.append(plugin)
[ "def", "register", "(", "self", ",", "plugin", ")", ":", "if", "not", "plugin", "or", "not", "isinstance", "(", "plugin", ",", "BasePlugin", ")", ":", "raise", "ValueError", "(", "\"Plugin must be implemented as a subclass of BasePlugin class\"", ")", "if", "self", ".", "is_registered", "(", "plugin", ".", "name", ")", ":", "raise", "ValueError", "(", "\"Plugin with name {} is already registered\"", ".", "format", "(", "plugin", ".", "name", ")", ")", "self", ".", "_plugins", ".", "append", "(", "plugin", ")" ]
Register a plugin. New plugins are added to the end of the plugins list. :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks :raises ValueError: If plugin is not an instance of samtranslator.plugins.BasePlugin or if it is already registered :return: None
[ "Register", "a", "plugin", ".", "New", "plugins", "are", "added", "to", "the", "end", "of", "the", "plugins", "list", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/__init__.py#L64-L80
train
awslabs/serverless-application-model
samtranslator/plugins/__init__.py
SamPlugins._get
def _get(self, plugin_name): """ Retrieves the plugin with given name :param plugin_name: Name of the plugin to retrieve :return samtranslator.plugins.BasePlugin: Returns the plugin object if found. None, otherwise """ for p in self._plugins: if p.name == plugin_name: return p return None
python
def _get(self, plugin_name): """ Retrieves the plugin with given name :param plugin_name: Name of the plugin to retrieve :return samtranslator.plugins.BasePlugin: Returns the plugin object if found. None, otherwise """ for p in self._plugins: if p.name == plugin_name: return p return None
[ "def", "_get", "(", "self", ",", "plugin_name", ")", ":", "for", "p", "in", "self", ".", "_plugins", ":", "if", "p", ".", "name", "==", "plugin_name", ":", "return", "p", "return", "None" ]
Retrieves the plugin with given name :param plugin_name: Name of the plugin to retrieve :return samtranslator.plugins.BasePlugin: Returns the plugin object if found. None, otherwise
[ "Retrieves", "the", "plugin", "with", "given", "name" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/__init__.py#L92-L104
train
awslabs/serverless-application-model
samtranslator/plugins/__init__.py
SamPlugins.act
def act(self, event, *args, **kwargs): """ Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins. *args and **kwargs will be passed directly to the plugin's hook functions :param samtranslator.plugins.LifeCycleEvents event: Event to act upon :return: Nothing :raises ValueError: If event is not a valid life cycle event :raises NameError: If a plugin does not have the hook method defined :raises Exception: Any exception that a plugin raises """ if not isinstance(event, LifeCycleEvents): raise ValueError("'event' must be an instance of LifeCycleEvents class") method_name = "on_" + event.name for plugin in self._plugins: if not hasattr(plugin, method_name): raise NameError("'{}' method is not found in the plugin with name '{}'" .format(method_name, plugin.name)) try: getattr(plugin, method_name)(*args, **kwargs) except InvalidResourceException as ex: # Don't need to log these because they don't result in crashes raise ex except Exception as ex: logging.exception("Plugin '%s' raised an exception: %s", plugin.name, ex) raise ex
python
def act(self, event, *args, **kwargs): """ Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins. *args and **kwargs will be passed directly to the plugin's hook functions :param samtranslator.plugins.LifeCycleEvents event: Event to act upon :return: Nothing :raises ValueError: If event is not a valid life cycle event :raises NameError: If a plugin does not have the hook method defined :raises Exception: Any exception that a plugin raises """ if not isinstance(event, LifeCycleEvents): raise ValueError("'event' must be an instance of LifeCycleEvents class") method_name = "on_" + event.name for plugin in self._plugins: if not hasattr(plugin, method_name): raise NameError("'{}' method is not found in the plugin with name '{}'" .format(method_name, plugin.name)) try: getattr(plugin, method_name)(*args, **kwargs) except InvalidResourceException as ex: # Don't need to log these because they don't result in crashes raise ex except Exception as ex: logging.exception("Plugin '%s' raised an exception: %s", plugin.name, ex) raise ex
[ "def", "act", "(", "self", ",", "event", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "event", ",", "LifeCycleEvents", ")", ":", "raise", "ValueError", "(", "\"'event' must be an instance of LifeCycleEvents class\"", ")", "method_name", "=", "\"on_\"", "+", "event", ".", "name", "for", "plugin", "in", "self", ".", "_plugins", ":", "if", "not", "hasattr", "(", "plugin", ",", "method_name", ")", ":", "raise", "NameError", "(", "\"'{}' method is not found in the plugin with name '{}'\"", ".", "format", "(", "method_name", ",", "plugin", ".", "name", ")", ")", "try", ":", "getattr", "(", "plugin", ",", "method_name", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "InvalidResourceException", "as", "ex", ":", "# Don't need to log these because they don't result in crashes", "raise", "ex", "except", "Exception", "as", "ex", ":", "logging", ".", "exception", "(", "\"Plugin '%s' raised an exception: %s\"", ",", "plugin", ".", "name", ",", "ex", ")", "raise", "ex" ]
Act on the specific life cycle event. The action here is to invoke the hook function on all registered plugins. *args and **kwargs will be passed directly to the plugin's hook functions :param samtranslator.plugins.LifeCycleEvents event: Event to act upon :return: Nothing :raises ValueError: If event is not a valid life cycle event :raises NameError: If a plugin does not have the hook method defined :raises Exception: Any exception that a plugin raises
[ "Act", "on", "the", "specific", "life", "cycle", "event", ".", "The", "action", "here", "is", "to", "invoke", "the", "hook", "function", "on", "all", "registered", "plugins", ".", "*", "args", "and", "**", "kwargs", "will", "be", "passed", "directly", "to", "the", "plugin", "s", "hook", "functions" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/__init__.py#L106-L136
train
awslabs/serverless-application-model
samtranslator/model/preferences/deployment_preference.py
DeploymentPreference.from_dict
def from_dict(cls, logical_id, deployment_preference_dict): """ :param logical_id: the logical_id of the resource that owns this deployment preference :param deployment_preference_dict: the dict object taken from the SAM template :return: """ enabled = deployment_preference_dict.get('Enabled', True) if not enabled: return DeploymentPreference(None, None, None, None, False, None) if 'Type' not in deployment_preference_dict: raise InvalidResourceException(logical_id, "'DeploymentPreference' is missing required Property 'Type'") deployment_type = deployment_preference_dict['Type'] hooks = deployment_preference_dict.get('Hooks', dict()) if not isinstance(hooks, dict): raise InvalidResourceException(logical_id, "'Hooks' property of 'DeploymentPreference' must be a dictionary") pre_traffic_hook = hooks.get('PreTraffic', None) post_traffic_hook = hooks.get('PostTraffic', None) alarms = deployment_preference_dict.get('Alarms', None) role = deployment_preference_dict.get('Role', None) return DeploymentPreference(deployment_type, pre_traffic_hook, post_traffic_hook, alarms, enabled, role)
python
def from_dict(cls, logical_id, deployment_preference_dict): """ :param logical_id: the logical_id of the resource that owns this deployment preference :param deployment_preference_dict: the dict object taken from the SAM template :return: """ enabled = deployment_preference_dict.get('Enabled', True) if not enabled: return DeploymentPreference(None, None, None, None, False, None) if 'Type' not in deployment_preference_dict: raise InvalidResourceException(logical_id, "'DeploymentPreference' is missing required Property 'Type'") deployment_type = deployment_preference_dict['Type'] hooks = deployment_preference_dict.get('Hooks', dict()) if not isinstance(hooks, dict): raise InvalidResourceException(logical_id, "'Hooks' property of 'DeploymentPreference' must be a dictionary") pre_traffic_hook = hooks.get('PreTraffic', None) post_traffic_hook = hooks.get('PostTraffic', None) alarms = deployment_preference_dict.get('Alarms', None) role = deployment_preference_dict.get('Role', None) return DeploymentPreference(deployment_type, pre_traffic_hook, post_traffic_hook, alarms, enabled, role)
[ "def", "from_dict", "(", "cls", ",", "logical_id", ",", "deployment_preference_dict", ")", ":", "enabled", "=", "deployment_preference_dict", ".", "get", "(", "'Enabled'", ",", "True", ")", "if", "not", "enabled", ":", "return", "DeploymentPreference", "(", "None", ",", "None", ",", "None", ",", "None", ",", "False", ",", "None", ")", "if", "'Type'", "not", "in", "deployment_preference_dict", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"'DeploymentPreference' is missing required Property 'Type'\"", ")", "deployment_type", "=", "deployment_preference_dict", "[", "'Type'", "]", "hooks", "=", "deployment_preference_dict", ".", "get", "(", "'Hooks'", ",", "dict", "(", ")", ")", "if", "not", "isinstance", "(", "hooks", ",", "dict", ")", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"'Hooks' property of 'DeploymentPreference' must be a dictionary\"", ")", "pre_traffic_hook", "=", "hooks", ".", "get", "(", "'PreTraffic'", ",", "None", ")", "post_traffic_hook", "=", "hooks", ".", "get", "(", "'PostTraffic'", ",", "None", ")", "alarms", "=", "deployment_preference_dict", ".", "get", "(", "'Alarms'", ",", "None", ")", "role", "=", "deployment_preference_dict", ".", "get", "(", "'Role'", ",", "None", ")", "return", "DeploymentPreference", "(", "deployment_type", ",", "pre_traffic_hook", ",", "post_traffic_hook", ",", "alarms", ",", "enabled", ",", "role", ")" ]
:param logical_id: the logical_id of the resource that owns this deployment preference :param deployment_preference_dict: the dict object taken from the SAM template :return:
[ ":", "param", "logical_id", ":", "the", "logical_id", "of", "the", "resource", "that", "owns", "this", "deployment", "preference", ":", "param", "deployment_preference_dict", ":", "the", "dict", "object", "taken", "from", "the", "SAM", "template", ":", "return", ":" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/preferences/deployment_preference.py#L37-L60
train
awslabs/serverless-application-model
examples/2016-10-31/encryption_proxy/src/decryption.py
decrypt
def decrypt(message): '''decrypt leverages KMS decrypt and base64-encode decrypted blob More info on KMS decrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_decrypt.html ''' try: ret = kms.decrypt( CiphertextBlob=base64.decodestring(message)) decrypted_data = ret.get('Plaintext') except Exception as e: # returns http 500 back to user and log error details in Cloudwatch Logs raise Exception("Unable to decrypt data: ", e) return decrypted_data
python
def decrypt(message): '''decrypt leverages KMS decrypt and base64-encode decrypted blob More info on KMS decrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_decrypt.html ''' try: ret = kms.decrypt( CiphertextBlob=base64.decodestring(message)) decrypted_data = ret.get('Plaintext') except Exception as e: # returns http 500 back to user and log error details in Cloudwatch Logs raise Exception("Unable to decrypt data: ", e) return decrypted_data
[ "def", "decrypt", "(", "message", ")", ":", "try", ":", "ret", "=", "kms", ".", "decrypt", "(", "CiphertextBlob", "=", "base64", ".", "decodestring", "(", "message", ")", ")", "decrypted_data", "=", "ret", ".", "get", "(", "'Plaintext'", ")", "except", "Exception", "as", "e", ":", "# returns http 500 back to user and log error details in Cloudwatch Logs", "raise", "Exception", "(", "\"Unable to decrypt data: \"", ",", "e", ")", "return", "decrypted_data" ]
decrypt leverages KMS decrypt and base64-encode decrypted blob More info on KMS decrypt API: https://docs.aws.amazon.com/kms/latest/APIReference/API_decrypt.html
[ "decrypt", "leverages", "KMS", "decrypt", "and", "base64", "-", "encode", "decrypted", "blob" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/2016-10-31/encryption_proxy/src/decryption.py#L15-L29
train
awslabs/serverless-application-model
examples/apps/rekognition-python/lambda_function.py
lambda_handler
def lambda_handler(event, context): '''Demonstrates S3 trigger that uses Rekognition APIs to detect faces, labels and index faces in S3 Object. ''' #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) try: # Calls rekognition DetectFaces API to detect faces in S3 object response = detect_faces(bucket, key) # Calls rekognition DetectLabels API to detect labels in S3 object #response = detect_labels(bucket, key) # Calls rekognition IndexFaces API to detect faces in S3 object and index faces into specified collection #response = index_faces(bucket, key) # Print response to console. print(response) return response except Exception as e: print(e) print("Error processing object {} from bucket {}. ".format(key, bucket) + "Make sure your object and bucket exist and your bucket is in the same region as this function.") raise e
python
def lambda_handler(event, context): '''Demonstrates S3 trigger that uses Rekognition APIs to detect faces, labels and index faces in S3 Object. ''' #print("Received event: " + json.dumps(event, indent=2)) # Get the object from the event bucket = event['Records'][0]['s3']['bucket']['name'] key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) try: # Calls rekognition DetectFaces API to detect faces in S3 object response = detect_faces(bucket, key) # Calls rekognition DetectLabels API to detect labels in S3 object #response = detect_labels(bucket, key) # Calls rekognition IndexFaces API to detect faces in S3 object and index faces into specified collection #response = index_faces(bucket, key) # Print response to console. print(response) return response except Exception as e: print(e) print("Error processing object {} from bucket {}. ".format(key, bucket) + "Make sure your object and bucket exist and your bucket is in the same region as this function.") raise e
[ "def", "lambda_handler", "(", "event", ",", "context", ")", ":", "#print(\"Received event: \" + json.dumps(event, indent=2))", "# Get the object from the event", "bucket", "=", "event", "[", "'Records'", "]", "[", "0", "]", "[", "'s3'", "]", "[", "'bucket'", "]", "[", "'name'", "]", "key", "=", "urllib", ".", "unquote_plus", "(", "event", "[", "'Records'", "]", "[", "0", "]", "[", "'s3'", "]", "[", "'object'", "]", "[", "'key'", "]", ".", "encode", "(", "'utf8'", ")", ")", "try", ":", "# Calls rekognition DetectFaces API to detect faces in S3 object", "response", "=", "detect_faces", "(", "bucket", ",", "key", ")", "# Calls rekognition DetectLabels API to detect labels in S3 object", "#response = detect_labels(bucket, key)", "# Calls rekognition IndexFaces API to detect faces in S3 object and index faces into specified collection", "#response = index_faces(bucket, key)", "# Print response to console.", "print", "(", "response", ")", "return", "response", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "print", "(", "\"Error processing object {} from bucket {}. \"", ".", "format", "(", "key", ",", "bucket", ")", "+", "\"Make sure your object and bucket exist and your bucket is in the same region as this function.\"", ")", "raise", "e" ]
Demonstrates S3 trigger that uses Rekognition APIs to detect faces, labels and index faces in S3 Object.
[ "Demonstrates", "S3", "trigger", "that", "uses", "Rekognition", "APIs", "to", "detect", "faces", "labels", "and", "index", "faces", "in", "S3", "Object", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/rekognition-python/lambda_function.py#L42-L69
train
awslabs/serverless-application-model
samtranslator/model/exceptions.py
prepend
def prepend(exception, message, end=': '): """Prepends the first argument (i.e., the exception message) of the a BaseException with the provided message. Useful for reraising exceptions with additional information. :param BaseException exception: the exception to prepend :param str message: the message to prepend :param str end: the separator to add to the end of the provided message :returns: the exception """ exception.args = exception.args or ('',) exception.args = (message + end + exception.args[0], ) + exception.args[1:] return exception
python
def prepend(exception, message, end=': '): """Prepends the first argument (i.e., the exception message) of the a BaseException with the provided message. Useful for reraising exceptions with additional information. :param BaseException exception: the exception to prepend :param str message: the message to prepend :param str end: the separator to add to the end of the provided message :returns: the exception """ exception.args = exception.args or ('',) exception.args = (message + end + exception.args[0], ) + exception.args[1:] return exception
[ "def", "prepend", "(", "exception", ",", "message", ",", "end", "=", "': '", ")", ":", "exception", ".", "args", "=", "exception", ".", "args", "or", "(", "''", ",", ")", "exception", ".", "args", "=", "(", "message", "+", "end", "+", "exception", ".", "args", "[", "0", "]", ",", ")", "+", "exception", ".", "args", "[", "1", ":", "]", "return", "exception" ]
Prepends the first argument (i.e., the exception message) of the a BaseException with the provided message. Useful for reraising exceptions with additional information. :param BaseException exception: the exception to prepend :param str message: the message to prepend :param str end: the separator to add to the end of the provided message :returns: the exception
[ "Prepends", "the", "first", "argument", "(", "i", ".", "e", ".", "the", "exception", "message", ")", "of", "the", "a", "BaseException", "with", "the", "provided", "message", ".", "Useful", "for", "reraising", "exceptions", "with", "additional", "information", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/exceptions.py#L87-L98
train
awslabs/serverless-application-model
examples/apps/api-gateway-authorizer-python/lambda_function.py
lambda_handler
def lambda_handler(event, context): # incoming token value token = event['authorizationToken'] print("Method ARN: " + event['methodArn']) ''' Validate the incoming token and produce the principal user identifier associated with the token. This can be accomplished in a number of ways: 1. Call out to the OAuth provider 2. Decode a JWT token inline 3. Lookup in a self-managed DB ''' principalId = 'user|a1b2c3d4' ''' You can send a 401 Unauthorized response to the client by failing like so: raise Exception('Unauthorized') If the token is valid, a policy must be generated which will allow or deny access to the client. If access is denied, the client will receive a 403 Access Denied response. If access is allowed, API Gateway will proceed with the backend integration configured on the method that was called. This function must generate a policy that is associated with the recognized principal user identifier. Depending on your use case, you might store policies in a DB, or generate them on the fly. Keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer) and will apply to subsequent calls to any method/resource in the RestApi made with the same token. The example policy below denies access to all resources in the RestApi. ''' tmp = event['methodArn'].split(':') apiGatewayArnTmp = tmp[5].split('/') awsAccountId = tmp[4] policy = AuthPolicy(principalId, awsAccountId) policy.restApiId = apiGatewayArnTmp[0] policy.region = tmp[3] policy.stage = apiGatewayArnTmp[1] policy.denyAllMethods() #policy.allowMethod(HttpVerb.GET, '/pets/*') # Finally, build the policy authResponse = policy.build() # new! -- add additional key-value pairs associated with the authenticated principal # these are made available by APIGW like so: $context.authorizer.<key> # additional context is cached context = { 'key': 'value', # $context.authorizer.key -> value 'number': 1, 'bool': True } # context['arr'] = ['foo'] <- this is invalid, APIGW will not accept it # context['obj'] = {'foo':'bar'} <- also invalid authResponse['context'] = context return authResponse
python
def lambda_handler(event, context): # incoming token value token = event['authorizationToken'] print("Method ARN: " + event['methodArn']) ''' Validate the incoming token and produce the principal user identifier associated with the token. This can be accomplished in a number of ways: 1. Call out to the OAuth provider 2. Decode a JWT token inline 3. Lookup in a self-managed DB ''' principalId = 'user|a1b2c3d4' ''' You can send a 401 Unauthorized response to the client by failing like so: raise Exception('Unauthorized') If the token is valid, a policy must be generated which will allow or deny access to the client. If access is denied, the client will receive a 403 Access Denied response. If access is allowed, API Gateway will proceed with the backend integration configured on the method that was called. This function must generate a policy that is associated with the recognized principal user identifier. Depending on your use case, you might store policies in a DB, or generate them on the fly. Keep in mind, the policy is cached for 5 minutes by default (TTL is configurable in the authorizer) and will apply to subsequent calls to any method/resource in the RestApi made with the same token. The example policy below denies access to all resources in the RestApi. ''' tmp = event['methodArn'].split(':') apiGatewayArnTmp = tmp[5].split('/') awsAccountId = tmp[4] policy = AuthPolicy(principalId, awsAccountId) policy.restApiId = apiGatewayArnTmp[0] policy.region = tmp[3] policy.stage = apiGatewayArnTmp[1] policy.denyAllMethods() #policy.allowMethod(HttpVerb.GET, '/pets/*') # Finally, build the policy authResponse = policy.build() # new! -- add additional key-value pairs associated with the authenticated principal # these are made available by APIGW like so: $context.authorizer.<key> # additional context is cached context = { 'key': 'value', # $context.authorizer.key -> value 'number': 1, 'bool': True } # context['arr'] = ['foo'] <- this is invalid, APIGW will not accept it # context['obj'] = {'foo':'bar'} <- also invalid authResponse['context'] = context return authResponse
[ "def", "lambda_handler", "(", "event", ",", "context", ")", ":", "# incoming token value", "token", "=", "event", "[", "'authorizationToken'", "]", "print", "(", "\"Method ARN: \"", "+", "event", "[", "'methodArn'", "]", ")", "principalId", "=", "'user|a1b2c3d4'", "'''\n You can send a 401 Unauthorized response to the client by failing like so:\n\n raise Exception('Unauthorized')\n\n If the token is valid, a policy must be generated which will allow or deny\n access to the client. If access is denied, the client will receive a 403\n Access Denied response. If access is allowed, API Gateway will proceed with\n the backend integration configured on the method that was called.\n\n This function must generate a policy that is associated with the recognized\n principal user identifier. Depending on your use case, you might store\n policies in a DB, or generate them on the fly.\n\n Keep in mind, the policy is cached for 5 minutes by default (TTL is\n configurable in the authorizer) and will apply to subsequent calls to any\n method/resource in the RestApi made with the same token.\n\n The example policy below denies access to all resources in the RestApi.\n '''", "tmp", "=", "event", "[", "'methodArn'", "]", ".", "split", "(", "':'", ")", "apiGatewayArnTmp", "=", "tmp", "[", "5", "]", ".", "split", "(", "'/'", ")", "awsAccountId", "=", "tmp", "[", "4", "]", "policy", "=", "AuthPolicy", "(", "principalId", ",", "awsAccountId", ")", "policy", ".", "restApiId", "=", "apiGatewayArnTmp", "[", "0", "]", "policy", ".", "region", "=", "tmp", "[", "3", "]", "policy", ".", "stage", "=", "apiGatewayArnTmp", "[", "1", "]", "policy", ".", "denyAllMethods", "(", ")", "#policy.allowMethod(HttpVerb.GET, '/pets/*')", "# Finally, build the policy", "authResponse", "=", "policy", ".", "build", "(", ")", "# new! -- add additional key-value pairs associated with the authenticated principal", "# these are made available by APIGW like so: $context.authorizer.<key>", "# additional context is cached", "context", "=", "{", "'key'", ":", "'value'", ",", "# $context.authorizer.key -> value", "'number'", ":", "1", ",", "'bool'", ":", "True", "}", "# context['arr'] = ['foo'] <- this is invalid, APIGW will not accept it", "# context['obj'] = {'foo':'bar'} <- also invalid", "authResponse", "[", "'context'", "]", "=", "context", "return", "authResponse" ]
Validate the incoming token and produce the principal user identifier associated with the token. This can be accomplished in a number of ways: 1. Call out to the OAuth provider 2. Decode a JWT token inline 3. Lookup in a self-managed DB
[ "Validate", "the", "incoming", "token", "and", "produce", "the", "principal", "user", "identifier", "associated", "with", "the", "token", ".", "This", "can", "be", "accomplished", "in", "a", "number", "of", "ways", ":" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/api-gateway-authorizer-python/lambda_function.py#L6-L68
train
awslabs/serverless-application-model
examples/apps/api-gateway-authorizer-python/lambda_function.py
AuthPolicy._getStatementForEffect
def _getStatementForEffect(self, effect, methods): '''This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy.''' statements = [] if len(methods) > 0: statement = self._getEmptyStatement(effect) for curMethod in methods: if curMethod['conditions'] is None or len(curMethod['conditions']) == 0: statement['Resource'].append(curMethod['resourceArn']) else: conditionalStatement = self._getEmptyStatement(effect) conditionalStatement['Resource'].append(curMethod['resourceArn']) conditionalStatement['Condition'] = curMethod['conditions'] statements.append(conditionalStatement) if statement['Resource']: statements.append(statement) return statements
python
def _getStatementForEffect(self, effect, methods): '''This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy.''' statements = [] if len(methods) > 0: statement = self._getEmptyStatement(effect) for curMethod in methods: if curMethod['conditions'] is None or len(curMethod['conditions']) == 0: statement['Resource'].append(curMethod['resourceArn']) else: conditionalStatement = self._getEmptyStatement(effect) conditionalStatement['Resource'].append(curMethod['resourceArn']) conditionalStatement['Condition'] = curMethod['conditions'] statements.append(conditionalStatement) if statement['Resource']: statements.append(statement) return statements
[ "def", "_getStatementForEffect", "(", "self", ",", "effect", ",", "methods", ")", ":", "statements", "=", "[", "]", "if", "len", "(", "methods", ")", ">", "0", ":", "statement", "=", "self", ".", "_getEmptyStatement", "(", "effect", ")", "for", "curMethod", "in", "methods", ":", "if", "curMethod", "[", "'conditions'", "]", "is", "None", "or", "len", "(", "curMethod", "[", "'conditions'", "]", ")", "==", "0", ":", "statement", "[", "'Resource'", "]", ".", "append", "(", "curMethod", "[", "'resourceArn'", "]", ")", "else", ":", "conditionalStatement", "=", "self", ".", "_getEmptyStatement", "(", "effect", ")", "conditionalStatement", "[", "'Resource'", "]", ".", "append", "(", "curMethod", "[", "'resourceArn'", "]", ")", "conditionalStatement", "[", "'Condition'", "]", "=", "curMethod", "[", "'conditions'", "]", "statements", ".", "append", "(", "conditionalStatement", ")", "if", "statement", "[", "'Resource'", "]", ":", "statements", ".", "append", "(", "statement", ")", "return", "statements" ]
This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy.
[ "This", "function", "loops", "over", "an", "array", "of", "objects", "containing", "a", "resourceArn", "and", "conditions", "statement", "and", "generates", "the", "array", "of", "statements", "for", "the", "policy", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/api-gateway-authorizer-python/lambda_function.py#L151-L171
train
awslabs/serverless-application-model
samtranslator/plugins/policies/policy_templates_plugin.py
PolicyTemplatesForFunctionPlugin.on_before_transform_resource
def on_before_transform_resource(self, logical_id, resource_type, resource_properties): """ Hook method that gets called before "each" SAM resource gets processed :param string logical_id: Logical ID of the resource being processed :param string resource_type: Type of the resource being processed :param dict resource_properties: Properties of the resource :return: Nothing """ if not self._is_supported(resource_type): return function_policies = FunctionPolicies(resource_properties, self._policy_template_processor) if len(function_policies) == 0: # No policies to process return result = [] for policy_entry in function_policies.get(): if policy_entry.type is not PolicyTypes.POLICY_TEMPLATE: # If we don't know the type, skip processing and pass to result as is. result.append(policy_entry.data) continue # We are processing policy templates. We know they have a particular structure: # {"templateName": { parameter_values_dict }} template_data = policy_entry.data template_name = list(template_data.keys())[0] template_parameters = list(template_data.values())[0] try: # 'convert' will return a list of policy statements result.append(self._policy_template_processor.convert(template_name, template_parameters)) except InsufficientParameterValues as ex: # Exception's message will give lot of specific details raise InvalidResourceException(logical_id, str(ex)) except InvalidParameterValues: raise InvalidResourceException(logical_id, "Must specify valid parameter values for policy template '{}'" .format(template_name)) # Save the modified policies list to the input resource_properties[FunctionPolicies.POLICIES_PROPERTY_NAME] = result
python
def on_before_transform_resource(self, logical_id, resource_type, resource_properties): """ Hook method that gets called before "each" SAM resource gets processed :param string logical_id: Logical ID of the resource being processed :param string resource_type: Type of the resource being processed :param dict resource_properties: Properties of the resource :return: Nothing """ if not self._is_supported(resource_type): return function_policies = FunctionPolicies(resource_properties, self._policy_template_processor) if len(function_policies) == 0: # No policies to process return result = [] for policy_entry in function_policies.get(): if policy_entry.type is not PolicyTypes.POLICY_TEMPLATE: # If we don't know the type, skip processing and pass to result as is. result.append(policy_entry.data) continue # We are processing policy templates. We know they have a particular structure: # {"templateName": { parameter_values_dict }} template_data = policy_entry.data template_name = list(template_data.keys())[0] template_parameters = list(template_data.values())[0] try: # 'convert' will return a list of policy statements result.append(self._policy_template_processor.convert(template_name, template_parameters)) except InsufficientParameterValues as ex: # Exception's message will give lot of specific details raise InvalidResourceException(logical_id, str(ex)) except InvalidParameterValues: raise InvalidResourceException(logical_id, "Must specify valid parameter values for policy template '{}'" .format(template_name)) # Save the modified policies list to the input resource_properties[FunctionPolicies.POLICIES_PROPERTY_NAME] = result
[ "def", "on_before_transform_resource", "(", "self", ",", "logical_id", ",", "resource_type", ",", "resource_properties", ")", ":", "if", "not", "self", ".", "_is_supported", "(", "resource_type", ")", ":", "return", "function_policies", "=", "FunctionPolicies", "(", "resource_properties", ",", "self", ".", "_policy_template_processor", ")", "if", "len", "(", "function_policies", ")", "==", "0", ":", "# No policies to process", "return", "result", "=", "[", "]", "for", "policy_entry", "in", "function_policies", ".", "get", "(", ")", ":", "if", "policy_entry", ".", "type", "is", "not", "PolicyTypes", ".", "POLICY_TEMPLATE", ":", "# If we don't know the type, skip processing and pass to result as is.", "result", ".", "append", "(", "policy_entry", ".", "data", ")", "continue", "# We are processing policy templates. We know they have a particular structure:", "# {\"templateName\": { parameter_values_dict }}", "template_data", "=", "policy_entry", ".", "data", "template_name", "=", "list", "(", "template_data", ".", "keys", "(", ")", ")", "[", "0", "]", "template_parameters", "=", "list", "(", "template_data", ".", "values", "(", ")", ")", "[", "0", "]", "try", ":", "# 'convert' will return a list of policy statements", "result", ".", "append", "(", "self", ".", "_policy_template_processor", ".", "convert", "(", "template_name", ",", "template_parameters", ")", ")", "except", "InsufficientParameterValues", "as", "ex", ":", "# Exception's message will give lot of specific details", "raise", "InvalidResourceException", "(", "logical_id", ",", "str", "(", "ex", ")", ")", "except", "InvalidParameterValues", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Must specify valid parameter values for policy template '{}'\"", ".", "format", "(", "template_name", ")", ")", "# Save the modified policies list to the input", "resource_properties", "[", "FunctionPolicies", ".", "POLICIES_PROPERTY_NAME", "]", "=", "result" ]
Hook method that gets called before "each" SAM resource gets processed :param string logical_id: Logical ID of the resource being processed :param string resource_type: Type of the resource being processed :param dict resource_properties: Properties of the resource :return: Nothing
[ "Hook", "method", "that", "gets", "called", "before", "each", "SAM", "resource", "gets", "processed" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/policies/policy_templates_plugin.py#L31-L78
train
awslabs/serverless-application-model
examples/apps/kinesis-analytics-process-kpl-record/lambda_function.py
lambda_handler
def lambda_handler(event, context): '''A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.''' raw_kpl_records = event['records'] output = [process_kpl_record(kpl_record) for kpl_record in raw_kpl_records] # Print number of successful and failed records. success_count = sum(1 for record in output if record['result'] == 'Ok') failure_count = sum(1 for record in output if record['result'] == 'ProcessingFailed') print('Processing completed. Successful records: {0}, Failed records: {1}.'.format(success_count, failure_count)) return {'records': output}
python
def lambda_handler(event, context): '''A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.''' raw_kpl_records = event['records'] output = [process_kpl_record(kpl_record) for kpl_record in raw_kpl_records] # Print number of successful and failed records. success_count = sum(1 for record in output if record['result'] == 'Ok') failure_count = sum(1 for record in output if record['result'] == 'ProcessingFailed') print('Processing completed. Successful records: {0}, Failed records: {1}.'.format(success_count, failure_count)) return {'records': output}
[ "def", "lambda_handler", "(", "event", ",", "context", ")", ":", "raw_kpl_records", "=", "event", "[", "'records'", "]", "output", "=", "[", "process_kpl_record", "(", "kpl_record", ")", "for", "kpl_record", "in", "raw_kpl_records", "]", "# Print number of successful and failed records.", "success_count", "=", "sum", "(", "1", "for", "record", "in", "output", "if", "record", "[", "'result'", "]", "==", "'Ok'", ")", "failure_count", "=", "sum", "(", "1", "for", "record", "in", "output", "if", "record", "[", "'result'", "]", "==", "'ProcessingFailed'", ")", "print", "(", "'Processing completed. Successful records: {0}, Failed records: {1}.'", ".", "format", "(", "success_count", ",", "failure_count", ")", ")", "return", "{", "'records'", ":", "output", "}" ]
A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.
[ "A", "Python", "AWS", "Lambda", "function", "to", "process", "aggregated", "records", "sent", "to", "KinesisAnalytics", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/kinesis-analytics-process-kpl-record/lambda_function.py#L25-L35
train
awslabs/serverless-application-model
samtranslator/translator/transform.py
transform
def transform(input_fragment, parameter_values, managed_policy_loader): """Translates the SAM manifest provided in the and returns the translation to CloudFormation. :param dict input_fragment: the SAM template to transform :param dict parameter_values: Parameter values provided by the user :returns: the transformed CloudFormation template :rtype: dict """ sam_parser = Parser() translator = Translator(managed_policy_loader.load(), sam_parser) return translator.translate(input_fragment, parameter_values=parameter_values)
python
def transform(input_fragment, parameter_values, managed_policy_loader): """Translates the SAM manifest provided in the and returns the translation to CloudFormation. :param dict input_fragment: the SAM template to transform :param dict parameter_values: Parameter values provided by the user :returns: the transformed CloudFormation template :rtype: dict """ sam_parser = Parser() translator = Translator(managed_policy_loader.load(), sam_parser) return translator.translate(input_fragment, parameter_values=parameter_values)
[ "def", "transform", "(", "input_fragment", ",", "parameter_values", ",", "managed_policy_loader", ")", ":", "sam_parser", "=", "Parser", "(", ")", "translator", "=", "Translator", "(", "managed_policy_loader", ".", "load", "(", ")", ",", "sam_parser", ")", "return", "translator", ".", "translate", "(", "input_fragment", ",", "parameter_values", "=", "parameter_values", ")" ]
Translates the SAM manifest provided in the and returns the translation to CloudFormation. :param dict input_fragment: the SAM template to transform :param dict parameter_values: Parameter values provided by the user :returns: the transformed CloudFormation template :rtype: dict
[ "Translates", "the", "SAM", "manifest", "provided", "in", "the", "and", "returns", "the", "translation", "to", "CloudFormation", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/transform.py#L5-L16
train
awslabs/serverless-application-model
samtranslator/model/update_policy.py
UpdatePolicy.to_dict
def to_dict(self): """ :return: a dict that can be used as part of a cloudformation template """ dict_with_nones = self._asdict() codedeploy_lambda_alias_update_dict = dict((k, v) for k, v in dict_with_nones.items() if v != ref(None) and v is not None) return {'CodeDeployLambdaAliasUpdate': codedeploy_lambda_alias_update_dict}
python
def to_dict(self): """ :return: a dict that can be used as part of a cloudformation template """ dict_with_nones = self._asdict() codedeploy_lambda_alias_update_dict = dict((k, v) for k, v in dict_with_nones.items() if v != ref(None) and v is not None) return {'CodeDeployLambdaAliasUpdate': codedeploy_lambda_alias_update_dict}
[ "def", "to_dict", "(", "self", ")", ":", "dict_with_nones", "=", "self", ".", "_asdict", "(", ")", "codedeploy_lambda_alias_update_dict", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "dict_with_nones", ".", "items", "(", ")", "if", "v", "!=", "ref", "(", "None", ")", "and", "v", "is", "not", "None", ")", "return", "{", "'CodeDeployLambdaAliasUpdate'", ":", "codedeploy_lambda_alias_update_dict", "}" ]
:return: a dict that can be used as part of a cloudformation template
[ ":", "return", ":", "a", "dict", "that", "can", "be", "used", "as", "part", "of", "a", "cloudformation", "template" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/update_policy.py#L23-L30
train
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin.on_before_transform_template
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has pass the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing """ template = SamTemplate(template_dict) # Temporarily add Serverless::Api resource corresponding to Implicit API to the template. # This will allow the processing code to work the same way for both Implicit & Explicit APIs # If there are no implicit APIs, we will remove from the template later. # If the customer has explicitly defined a resource with the id of "ServerlessRestApi", # capture it. If the template ends up not defining any implicit api's, instead of just # removing the "ServerlessRestApi" resource, we just restore what the author defined. self.existing_implicit_api_resource = copy.deepcopy(template.get(self.implicit_api_logical_id)) template.set(self.implicit_api_logical_id, ImplicitApiResource().to_dict()) errors = [] for logicalId, function in template.iterate(SamResourceType.Function.value): api_events = self._get_api_events(function) condition = function.condition if len(api_events) == 0: continue try: self._process_api_events(function, api_events, template, condition) except InvalidEventException as ex: errors.append(InvalidResourceException(logicalId, ex.message)) self._maybe_add_condition_to_implicit_api(template_dict) self._maybe_add_conditions_to_implicit_api_paths(template) self._maybe_remove_implicit_api(template) if len(errors) > 0: raise InvalidDocumentException(errors)
python
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has pass the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing """ template = SamTemplate(template_dict) # Temporarily add Serverless::Api resource corresponding to Implicit API to the template. # This will allow the processing code to work the same way for both Implicit & Explicit APIs # If there are no implicit APIs, we will remove from the template later. # If the customer has explicitly defined a resource with the id of "ServerlessRestApi", # capture it. If the template ends up not defining any implicit api's, instead of just # removing the "ServerlessRestApi" resource, we just restore what the author defined. self.existing_implicit_api_resource = copy.deepcopy(template.get(self.implicit_api_logical_id)) template.set(self.implicit_api_logical_id, ImplicitApiResource().to_dict()) errors = [] for logicalId, function in template.iterate(SamResourceType.Function.value): api_events = self._get_api_events(function) condition = function.condition if len(api_events) == 0: continue try: self._process_api_events(function, api_events, template, condition) except InvalidEventException as ex: errors.append(InvalidResourceException(logicalId, ex.message)) self._maybe_add_condition_to_implicit_api(template_dict) self._maybe_add_conditions_to_implicit_api_paths(template) self._maybe_remove_implicit_api(template) if len(errors) > 0: raise InvalidDocumentException(errors)
[ "def", "on_before_transform_template", "(", "self", ",", "template_dict", ")", ":", "template", "=", "SamTemplate", "(", "template_dict", ")", "# Temporarily add Serverless::Api resource corresponding to Implicit API to the template.", "# This will allow the processing code to work the same way for both Implicit & Explicit APIs", "# If there are no implicit APIs, we will remove from the template later.", "# If the customer has explicitly defined a resource with the id of \"ServerlessRestApi\",", "# capture it. If the template ends up not defining any implicit api's, instead of just", "# removing the \"ServerlessRestApi\" resource, we just restore what the author defined.", "self", ".", "existing_implicit_api_resource", "=", "copy", ".", "deepcopy", "(", "template", ".", "get", "(", "self", ".", "implicit_api_logical_id", ")", ")", "template", ".", "set", "(", "self", ".", "implicit_api_logical_id", ",", "ImplicitApiResource", "(", ")", ".", "to_dict", "(", ")", ")", "errors", "=", "[", "]", "for", "logicalId", ",", "function", "in", "template", ".", "iterate", "(", "SamResourceType", ".", "Function", ".", "value", ")", ":", "api_events", "=", "self", ".", "_get_api_events", "(", "function", ")", "condition", "=", "function", ".", "condition", "if", "len", "(", "api_events", ")", "==", "0", ":", "continue", "try", ":", "self", ".", "_process_api_events", "(", "function", ",", "api_events", ",", "template", ",", "condition", ")", "except", "InvalidEventException", "as", "ex", ":", "errors", ".", "append", "(", "InvalidResourceException", "(", "logicalId", ",", "ex", ".", "message", ")", ")", "self", ".", "_maybe_add_condition_to_implicit_api", "(", "template_dict", ")", "self", ".", "_maybe_add_conditions_to_implicit_api_paths", "(", "template", ")", "self", ".", "_maybe_remove_implicit_api", "(", "template", ")", "if", "len", "(", "errors", ")", ">", "0", ":", "raise", "InvalidDocumentException", "(", "errors", ")" ]
Hook method that gets called before the SAM template is processed. The template has pass the validation and is guaranteed to contain a non-empty "Resources" section. :param dict template_dict: Dictionary of the SAM template :return: Nothing
[ "Hook", "method", "that", "gets", "called", "before", "the", "SAM", "template", "is", "processed", ".", "The", "template", "has", "pass", "the", "validation", "and", "is", "guaranteed", "to", "contain", "a", "non", "-", "empty", "Resources", "section", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L48-L89
train
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._get_api_events
def _get_api_events(self, function): """ Method to return a dictionary of API Events on the function :param SamResource function: Function Resource object :return dict: Dictionary of API events along with any other configuration passed to it. Example: { FooEvent: {Path: "/foo", Method: "post", RestApiId: blah, MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}, BarEvent: {Path: "/bar", Method: "any", MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}" } """ if not (function.valid() and isinstance(function.properties, dict) and isinstance(function.properties.get("Events"), dict) ): # Function resource structure is invalid. return {} api_events = {} for event_id, event in function.properties["Events"].items(): if event and isinstance(event, dict) and event.get("Type") == "Api": api_events[event_id] = event return api_events
python
def _get_api_events(self, function): """ Method to return a dictionary of API Events on the function :param SamResource function: Function Resource object :return dict: Dictionary of API events along with any other configuration passed to it. Example: { FooEvent: {Path: "/foo", Method: "post", RestApiId: blah, MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}, BarEvent: {Path: "/bar", Method: "any", MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}" } """ if not (function.valid() and isinstance(function.properties, dict) and isinstance(function.properties.get("Events"), dict) ): # Function resource structure is invalid. return {} api_events = {} for event_id, event in function.properties["Events"].items(): if event and isinstance(event, dict) and event.get("Type") == "Api": api_events[event_id] = event return api_events
[ "def", "_get_api_events", "(", "self", ",", "function", ")", ":", "if", "not", "(", "function", ".", "valid", "(", ")", "and", "isinstance", "(", "function", ".", "properties", ",", "dict", ")", "and", "isinstance", "(", "function", ".", "properties", ".", "get", "(", "\"Events\"", ")", ",", "dict", ")", ")", ":", "# Function resource structure is invalid.", "return", "{", "}", "api_events", "=", "{", "}", "for", "event_id", ",", "event", "in", "function", ".", "properties", "[", "\"Events\"", "]", ".", "items", "(", ")", ":", "if", "event", "and", "isinstance", "(", "event", ",", "dict", ")", "and", "event", ".", "get", "(", "\"Type\"", ")", "==", "\"Api\"", ":", "api_events", "[", "event_id", "]", "=", "event", "return", "api_events" ]
Method to return a dictionary of API Events on the function :param SamResource function: Function Resource object :return dict: Dictionary of API events along with any other configuration passed to it. Example: { FooEvent: {Path: "/foo", Method: "post", RestApiId: blah, MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}, BarEvent: {Path: "/bar", Method: "any", MethodSettings: {<something>}, Cors: {<something>}, Auth: {<something>}}" }
[ "Method", "to", "return", "a", "dictionary", "of", "API", "Events", "on", "the", "function" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L91-L118
train
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._process_api_events
def _process_api_events(self, function, api_events, template, condition=None): """ Actually process given API events. Iteratively adds the APIs to Swagger JSON in the respective Serverless::Api resource from the template :param SamResource function: SAM Function containing the API events to be processed :param dict api_events: API Events extracted from the function. These events will be processed :param SamTemplate template: SAM Template where Serverless::Api resources can be found :param str condition: optional; this is the condition that is on the function with the API event """ for logicalId, event in api_events.items(): event_properties = event.get("Properties", {}) if not event_properties: continue self._add_implicit_api_id_if_necessary(event_properties) api_id = self._get_api_id(event_properties) try: path = event_properties["Path"] method = event_properties["Method"] except KeyError as e: raise InvalidEventException(logicalId, "Event is missing key {}.".format(e)) if (not isinstance(path, six.string_types)): raise InvalidEventException(logicalId, "Api Event must have a String specified for 'Path'.") if (not isinstance(method, six.string_types)): raise InvalidEventException(logicalId, "Api Event must have a String specified for 'Method'.") api_dict = self.api_conditions.setdefault(api_id, {}) method_conditions = api_dict.setdefault(path, {}) method_conditions[method] = condition self._add_api_to_swagger(logicalId, event_properties, template) api_events[logicalId] = event # We could have made changes to the Events structure. Write it back to function function.properties["Events"].update(api_events)
python
def _process_api_events(self, function, api_events, template, condition=None): """ Actually process given API events. Iteratively adds the APIs to Swagger JSON in the respective Serverless::Api resource from the template :param SamResource function: SAM Function containing the API events to be processed :param dict api_events: API Events extracted from the function. These events will be processed :param SamTemplate template: SAM Template where Serverless::Api resources can be found :param str condition: optional; this is the condition that is on the function with the API event """ for logicalId, event in api_events.items(): event_properties = event.get("Properties", {}) if not event_properties: continue self._add_implicit_api_id_if_necessary(event_properties) api_id = self._get_api_id(event_properties) try: path = event_properties["Path"] method = event_properties["Method"] except KeyError as e: raise InvalidEventException(logicalId, "Event is missing key {}.".format(e)) if (not isinstance(path, six.string_types)): raise InvalidEventException(logicalId, "Api Event must have a String specified for 'Path'.") if (not isinstance(method, six.string_types)): raise InvalidEventException(logicalId, "Api Event must have a String specified for 'Method'.") api_dict = self.api_conditions.setdefault(api_id, {}) method_conditions = api_dict.setdefault(path, {}) method_conditions[method] = condition self._add_api_to_swagger(logicalId, event_properties, template) api_events[logicalId] = event # We could have made changes to the Events structure. Write it back to function function.properties["Events"].update(api_events)
[ "def", "_process_api_events", "(", "self", ",", "function", ",", "api_events", ",", "template", ",", "condition", "=", "None", ")", ":", "for", "logicalId", ",", "event", "in", "api_events", ".", "items", "(", ")", ":", "event_properties", "=", "event", ".", "get", "(", "\"Properties\"", ",", "{", "}", ")", "if", "not", "event_properties", ":", "continue", "self", ".", "_add_implicit_api_id_if_necessary", "(", "event_properties", ")", "api_id", "=", "self", ".", "_get_api_id", "(", "event_properties", ")", "try", ":", "path", "=", "event_properties", "[", "\"Path\"", "]", "method", "=", "event_properties", "[", "\"Method\"", "]", "except", "KeyError", "as", "e", ":", "raise", "InvalidEventException", "(", "logicalId", ",", "\"Event is missing key {}.\"", ".", "format", "(", "e", ")", ")", "if", "(", "not", "isinstance", "(", "path", ",", "six", ".", "string_types", ")", ")", ":", "raise", "InvalidEventException", "(", "logicalId", ",", "\"Api Event must have a String specified for 'Path'.\"", ")", "if", "(", "not", "isinstance", "(", "method", ",", "six", ".", "string_types", ")", ")", ":", "raise", "InvalidEventException", "(", "logicalId", ",", "\"Api Event must have a String specified for 'Method'.\"", ")", "api_dict", "=", "self", ".", "api_conditions", ".", "setdefault", "(", "api_id", ",", "{", "}", ")", "method_conditions", "=", "api_dict", ".", "setdefault", "(", "path", ",", "{", "}", ")", "method_conditions", "[", "method", "]", "=", "condition", "self", ".", "_add_api_to_swagger", "(", "logicalId", ",", "event_properties", ",", "template", ")", "api_events", "[", "logicalId", "]", "=", "event", "# We could have made changes to the Events structure. Write it back to function", "function", ".", "properties", "[", "\"Events\"", "]", ".", "update", "(", "api_events", ")" ]
Actually process given API events. Iteratively adds the APIs to Swagger JSON in the respective Serverless::Api resource from the template :param SamResource function: SAM Function containing the API events to be processed :param dict api_events: API Events extracted from the function. These events will be processed :param SamTemplate template: SAM Template where Serverless::Api resources can be found :param str condition: optional; this is the condition that is on the function with the API event
[ "Actually", "process", "given", "API", "events", ".", "Iteratively", "adds", "the", "APIs", "to", "Swagger", "JSON", "in", "the", "respective", "Serverless", "::", "Api", "resource", "from", "the", "template" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L120-L162
train
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._add_api_to_swagger
def _add_api_to_swagger(self, event_id, event_properties, template): """ Adds the API path/method from the given event to the Swagger JSON of Serverless::Api resource this event refers to. :param string event_id: LogicalId of the event :param dict event_properties: Properties of the event :param SamTemplate template: SAM Template to search for Serverless::Api resources """ # Need to grab the AWS::Serverless::Api resource for this API event and update its Swagger definition api_id = self._get_api_id(event_properties) # RestApiId is not pointing to a valid API resource if isinstance(api_id, dict) or not template.get(api_id): raise InvalidEventException(event_id, "RestApiId must be a valid reference to an 'AWS::Serverless::Api' resource " "in same template") # Make sure Swagger is valid resource = template.get(api_id) if not (resource and isinstance(resource.properties, dict) and SwaggerEditor.is_valid(resource.properties.get("DefinitionBody"))): # This does not have an inline Swagger. Nothing can be done about it. return if not resource.properties.get("__MANAGE_SWAGGER"): # Do not add the api to Swagger, if the resource is not actively managed by SAM. # ie. Implicit API resources are created & managed by SAM on behalf of customers. # But for explicit API resources, customers write their own Swagger and manage it. # If a path is present in Events section but *not* present in the Explicit API Swagger, then it is # customer's responsibility to add to Swagger. We will not modify the Swagger here. # # In the future, we will might expose a flag that will allow SAM to manage explicit API Swagger as well. # Until then, we will not modify explicit explicit APIs. return swagger = resource.properties.get("DefinitionBody") path = event_properties["Path"] method = event_properties["Method"] editor = SwaggerEditor(swagger) editor.add_path(path, method) resource.properties["DefinitionBody"] = editor.swagger template.set(api_id, resource)
python
def _add_api_to_swagger(self, event_id, event_properties, template): """ Adds the API path/method from the given event to the Swagger JSON of Serverless::Api resource this event refers to. :param string event_id: LogicalId of the event :param dict event_properties: Properties of the event :param SamTemplate template: SAM Template to search for Serverless::Api resources """ # Need to grab the AWS::Serverless::Api resource for this API event and update its Swagger definition api_id = self._get_api_id(event_properties) # RestApiId is not pointing to a valid API resource if isinstance(api_id, dict) or not template.get(api_id): raise InvalidEventException(event_id, "RestApiId must be a valid reference to an 'AWS::Serverless::Api' resource " "in same template") # Make sure Swagger is valid resource = template.get(api_id) if not (resource and isinstance(resource.properties, dict) and SwaggerEditor.is_valid(resource.properties.get("DefinitionBody"))): # This does not have an inline Swagger. Nothing can be done about it. return if not resource.properties.get("__MANAGE_SWAGGER"): # Do not add the api to Swagger, if the resource is not actively managed by SAM. # ie. Implicit API resources are created & managed by SAM on behalf of customers. # But for explicit API resources, customers write their own Swagger and manage it. # If a path is present in Events section but *not* present in the Explicit API Swagger, then it is # customer's responsibility to add to Swagger. We will not modify the Swagger here. # # In the future, we will might expose a flag that will allow SAM to manage explicit API Swagger as well. # Until then, we will not modify explicit explicit APIs. return swagger = resource.properties.get("DefinitionBody") path = event_properties["Path"] method = event_properties["Method"] editor = SwaggerEditor(swagger) editor.add_path(path, method) resource.properties["DefinitionBody"] = editor.swagger template.set(api_id, resource)
[ "def", "_add_api_to_swagger", "(", "self", ",", "event_id", ",", "event_properties", ",", "template", ")", ":", "# Need to grab the AWS::Serverless::Api resource for this API event and update its Swagger definition", "api_id", "=", "self", ".", "_get_api_id", "(", "event_properties", ")", "# RestApiId is not pointing to a valid API resource", "if", "isinstance", "(", "api_id", ",", "dict", ")", "or", "not", "template", ".", "get", "(", "api_id", ")", ":", "raise", "InvalidEventException", "(", "event_id", ",", "\"RestApiId must be a valid reference to an 'AWS::Serverless::Api' resource \"", "\"in same template\"", ")", "# Make sure Swagger is valid", "resource", "=", "template", ".", "get", "(", "api_id", ")", "if", "not", "(", "resource", "and", "isinstance", "(", "resource", ".", "properties", ",", "dict", ")", "and", "SwaggerEditor", ".", "is_valid", "(", "resource", ".", "properties", ".", "get", "(", "\"DefinitionBody\"", ")", ")", ")", ":", "# This does not have an inline Swagger. Nothing can be done about it.", "return", "if", "not", "resource", ".", "properties", ".", "get", "(", "\"__MANAGE_SWAGGER\"", ")", ":", "# Do not add the api to Swagger, if the resource is not actively managed by SAM.", "# ie. Implicit API resources are created & managed by SAM on behalf of customers.", "# But for explicit API resources, customers write their own Swagger and manage it.", "# If a path is present in Events section but *not* present in the Explicit API Swagger, then it is", "# customer's responsibility to add to Swagger. We will not modify the Swagger here.", "#", "# In the future, we will might expose a flag that will allow SAM to manage explicit API Swagger as well.", "# Until then, we will not modify explicit explicit APIs.", "return", "swagger", "=", "resource", ".", "properties", ".", "get", "(", "\"DefinitionBody\"", ")", "path", "=", "event_properties", "[", "\"Path\"", "]", "method", "=", "event_properties", "[", "\"Method\"", "]", "editor", "=", "SwaggerEditor", "(", "swagger", ")", "editor", ".", "add_path", "(", "path", ",", "method", ")", "resource", ".", "properties", "[", "\"DefinitionBody\"", "]", "=", "editor", ".", "swagger", "template", ".", "set", "(", "api_id", ",", "resource", ")" ]
Adds the API path/method from the given event to the Swagger JSON of Serverless::Api resource this event refers to. :param string event_id: LogicalId of the event :param dict event_properties: Properties of the event :param SamTemplate template: SAM Template to search for Serverless::Api resources
[ "Adds", "the", "API", "path", "/", "method", "from", "the", "given", "event", "to", "the", "Swagger", "JSON", "of", "Serverless", "::", "Api", "resource", "this", "event", "refers", "to", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L175-L221
train
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._get_api_id
def _get_api_id(self, event_properties): """ Get API logical id from API event properties. Handles case where API id is not specified or is a reference to a logical id. """ api_id = event_properties.get("RestApiId") if isinstance(api_id, dict) and "Ref" in api_id: api_id = api_id["Ref"] return api_id
python
def _get_api_id(self, event_properties): """ Get API logical id from API event properties. Handles case where API id is not specified or is a reference to a logical id. """ api_id = event_properties.get("RestApiId") if isinstance(api_id, dict) and "Ref" in api_id: api_id = api_id["Ref"] return api_id
[ "def", "_get_api_id", "(", "self", ",", "event_properties", ")", ":", "api_id", "=", "event_properties", ".", "get", "(", "\"RestApiId\"", ")", "if", "isinstance", "(", "api_id", ",", "dict", ")", "and", "\"Ref\"", "in", "api_id", ":", "api_id", "=", "api_id", "[", "\"Ref\"", "]", "return", "api_id" ]
Get API logical id from API event properties. Handles case where API id is not specified or is a reference to a logical id.
[ "Get", "API", "logical", "id", "from", "API", "event", "properties", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L223-L232
train
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._maybe_add_condition_to_implicit_api
def _maybe_add_condition_to_implicit_api(self, template_dict): """ Decides whether to add a condition to the implicit api resource. :param dict template_dict: SAM template dictionary """ # Short-circuit if template doesn't have any functions with implicit API events if not self.api_conditions.get(self.implicit_api_logical_id, {}): return # Add a condition to the API resource IFF all of its resource+methods are associated with serverless functions # containing conditions. implicit_api_conditions = self.api_conditions[self.implicit_api_logical_id] all_resource_method_conditions = set([condition for path, method_conditions in implicit_api_conditions.items() for method, condition in method_conditions.items()]) at_least_one_resource_method = len(all_resource_method_conditions) > 0 all_resource_methods_contain_conditions = None not in all_resource_method_conditions if at_least_one_resource_method and all_resource_methods_contain_conditions: implicit_api_resource = template_dict.get('Resources').get(self.implicit_api_logical_id) if len(all_resource_method_conditions) == 1: condition = all_resource_method_conditions.pop() implicit_api_resource['Condition'] = condition else: # If multiple functions with multiple different conditions reference the Implicit Api, we need to # aggregate those conditions in order to conditionally create the Implicit Api. See RFC: # https://github.com/awslabs/serverless-application-model/issues/758 implicit_api_resource['Condition'] = self.implicit_api_condition self._add_combined_condition_to_template( template_dict, self.implicit_api_condition, all_resource_method_conditions)
python
def _maybe_add_condition_to_implicit_api(self, template_dict): """ Decides whether to add a condition to the implicit api resource. :param dict template_dict: SAM template dictionary """ # Short-circuit if template doesn't have any functions with implicit API events if not self.api_conditions.get(self.implicit_api_logical_id, {}): return # Add a condition to the API resource IFF all of its resource+methods are associated with serverless functions # containing conditions. implicit_api_conditions = self.api_conditions[self.implicit_api_logical_id] all_resource_method_conditions = set([condition for path, method_conditions in implicit_api_conditions.items() for method, condition in method_conditions.items()]) at_least_one_resource_method = len(all_resource_method_conditions) > 0 all_resource_methods_contain_conditions = None not in all_resource_method_conditions if at_least_one_resource_method and all_resource_methods_contain_conditions: implicit_api_resource = template_dict.get('Resources').get(self.implicit_api_logical_id) if len(all_resource_method_conditions) == 1: condition = all_resource_method_conditions.pop() implicit_api_resource['Condition'] = condition else: # If multiple functions with multiple different conditions reference the Implicit Api, we need to # aggregate those conditions in order to conditionally create the Implicit Api. See RFC: # https://github.com/awslabs/serverless-application-model/issues/758 implicit_api_resource['Condition'] = self.implicit_api_condition self._add_combined_condition_to_template( template_dict, self.implicit_api_condition, all_resource_method_conditions)
[ "def", "_maybe_add_condition_to_implicit_api", "(", "self", ",", "template_dict", ")", ":", "# Short-circuit if template doesn't have any functions with implicit API events", "if", "not", "self", ".", "api_conditions", ".", "get", "(", "self", ".", "implicit_api_logical_id", ",", "{", "}", ")", ":", "return", "# Add a condition to the API resource IFF all of its resource+methods are associated with serverless functions", "# containing conditions.", "implicit_api_conditions", "=", "self", ".", "api_conditions", "[", "self", ".", "implicit_api_logical_id", "]", "all_resource_method_conditions", "=", "set", "(", "[", "condition", "for", "path", ",", "method_conditions", "in", "implicit_api_conditions", ".", "items", "(", ")", "for", "method", ",", "condition", "in", "method_conditions", ".", "items", "(", ")", "]", ")", "at_least_one_resource_method", "=", "len", "(", "all_resource_method_conditions", ")", ">", "0", "all_resource_methods_contain_conditions", "=", "None", "not", "in", "all_resource_method_conditions", "if", "at_least_one_resource_method", "and", "all_resource_methods_contain_conditions", ":", "implicit_api_resource", "=", "template_dict", ".", "get", "(", "'Resources'", ")", ".", "get", "(", "self", ".", "implicit_api_logical_id", ")", "if", "len", "(", "all_resource_method_conditions", ")", "==", "1", ":", "condition", "=", "all_resource_method_conditions", ".", "pop", "(", ")", "implicit_api_resource", "[", "'Condition'", "]", "=", "condition", "else", ":", "# If multiple functions with multiple different conditions reference the Implicit Api, we need to", "# aggregate those conditions in order to conditionally create the Implicit Api. See RFC:", "# https://github.com/awslabs/serverless-application-model/issues/758", "implicit_api_resource", "[", "'Condition'", "]", "=", "self", ".", "implicit_api_condition", "self", ".", "_add_combined_condition_to_template", "(", "template_dict", ",", "self", ".", "implicit_api_condition", ",", "all_resource_method_conditions", ")" ]
Decides whether to add a condition to the implicit api resource. :param dict template_dict: SAM template dictionary
[ "Decides", "whether", "to", "add", "a", "condition", "to", "the", "implicit", "api", "resource", ".", ":", "param", "dict", "template_dict", ":", "SAM", "template", "dictionary" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L234-L262
train
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._add_combined_condition_to_template
def _add_combined_condition_to_template(self, template_dict, condition_name, conditions_to_combine): """ Add top-level template condition that combines the given list of conditions. :param dict template_dict: SAM template dictionary :param string condition_name: Name of top-level template condition :param list conditions_to_combine: List of conditions that should be combined (via OR operator) to form top-level condition. """ # defensive precondition check if not conditions_to_combine or len(conditions_to_combine) < 2: raise ValueError('conditions_to_combine must have at least 2 conditions') template_conditions = template_dict.setdefault('Conditions', {}) new_template_conditions = make_combined_condition(sorted(list(conditions_to_combine)), condition_name) for name, definition in new_template_conditions.items(): template_conditions[name] = definition
python
def _add_combined_condition_to_template(self, template_dict, condition_name, conditions_to_combine): """ Add top-level template condition that combines the given list of conditions. :param dict template_dict: SAM template dictionary :param string condition_name: Name of top-level template condition :param list conditions_to_combine: List of conditions that should be combined (via OR operator) to form top-level condition. """ # defensive precondition check if not conditions_to_combine or len(conditions_to_combine) < 2: raise ValueError('conditions_to_combine must have at least 2 conditions') template_conditions = template_dict.setdefault('Conditions', {}) new_template_conditions = make_combined_condition(sorted(list(conditions_to_combine)), condition_name) for name, definition in new_template_conditions.items(): template_conditions[name] = definition
[ "def", "_add_combined_condition_to_template", "(", "self", ",", "template_dict", ",", "condition_name", ",", "conditions_to_combine", ")", ":", "# defensive precondition check", "if", "not", "conditions_to_combine", "or", "len", "(", "conditions_to_combine", ")", "<", "2", ":", "raise", "ValueError", "(", "'conditions_to_combine must have at least 2 conditions'", ")", "template_conditions", "=", "template_dict", ".", "setdefault", "(", "'Conditions'", ",", "{", "}", ")", "new_template_conditions", "=", "make_combined_condition", "(", "sorted", "(", "list", "(", "conditions_to_combine", ")", ")", ",", "condition_name", ")", "for", "name", ",", "definition", "in", "new_template_conditions", ".", "items", "(", ")", ":", "template_conditions", "[", "name", "]", "=", "definition" ]
Add top-level template condition that combines the given list of conditions. :param dict template_dict: SAM template dictionary :param string condition_name: Name of top-level template condition :param list conditions_to_combine: List of conditions that should be combined (via OR operator) to form top-level condition.
[ "Add", "top", "-", "level", "template", "condition", "that", "combines", "the", "given", "list", "of", "conditions", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L264-L280
train
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._maybe_add_conditions_to_implicit_api_paths
def _maybe_add_conditions_to_implicit_api_paths(self, template): """ Add conditions to implicit API paths if necessary. Implicit API resource methods are constructed from API events on individual serverless functions within the SAM template. Since serverless functions can have conditions on them, it's possible to have a case where all methods under a resource path have conditions on them. If all of these conditions evaluate to false, the entire resource path should not be defined either. This method checks all resource paths' methods and if all methods under a given path contain a condition, a composite condition is added to the overall template Conditions section and that composite condition is added to the resource path. """ for api_id, api in template.iterate(SamResourceType.Api.value): if not api.properties.get('__MANAGE_SWAGGER'): continue swagger = api.properties.get("DefinitionBody") editor = SwaggerEditor(swagger) for path in editor.iter_on_path(): all_method_conditions = set( [condition for method, condition in self.api_conditions[api_id][path].items()] ) at_least_one_method = len(all_method_conditions) > 0 all_methods_contain_conditions = None not in all_method_conditions if at_least_one_method and all_methods_contain_conditions: if len(all_method_conditions) == 1: editor.make_path_conditional(path, all_method_conditions.pop()) else: path_condition_name = self._path_condition_name(api_id, path) self._add_combined_condition_to_template( template.template_dict, path_condition_name, all_method_conditions) editor.make_path_conditional(path, path_condition_name) api.properties["DefinitionBody"] = editor.swagger template.set(api_id, api)
python
def _maybe_add_conditions_to_implicit_api_paths(self, template): """ Add conditions to implicit API paths if necessary. Implicit API resource methods are constructed from API events on individual serverless functions within the SAM template. Since serverless functions can have conditions on them, it's possible to have a case where all methods under a resource path have conditions on them. If all of these conditions evaluate to false, the entire resource path should not be defined either. This method checks all resource paths' methods and if all methods under a given path contain a condition, a composite condition is added to the overall template Conditions section and that composite condition is added to the resource path. """ for api_id, api in template.iterate(SamResourceType.Api.value): if not api.properties.get('__MANAGE_SWAGGER'): continue swagger = api.properties.get("DefinitionBody") editor = SwaggerEditor(swagger) for path in editor.iter_on_path(): all_method_conditions = set( [condition for method, condition in self.api_conditions[api_id][path].items()] ) at_least_one_method = len(all_method_conditions) > 0 all_methods_contain_conditions = None not in all_method_conditions if at_least_one_method and all_methods_contain_conditions: if len(all_method_conditions) == 1: editor.make_path_conditional(path, all_method_conditions.pop()) else: path_condition_name = self._path_condition_name(api_id, path) self._add_combined_condition_to_template( template.template_dict, path_condition_name, all_method_conditions) editor.make_path_conditional(path, path_condition_name) api.properties["DefinitionBody"] = editor.swagger template.set(api_id, api)
[ "def", "_maybe_add_conditions_to_implicit_api_paths", "(", "self", ",", "template", ")", ":", "for", "api_id", ",", "api", "in", "template", ".", "iterate", "(", "SamResourceType", ".", "Api", ".", "value", ")", ":", "if", "not", "api", ".", "properties", ".", "get", "(", "'__MANAGE_SWAGGER'", ")", ":", "continue", "swagger", "=", "api", ".", "properties", ".", "get", "(", "\"DefinitionBody\"", ")", "editor", "=", "SwaggerEditor", "(", "swagger", ")", "for", "path", "in", "editor", ".", "iter_on_path", "(", ")", ":", "all_method_conditions", "=", "set", "(", "[", "condition", "for", "method", ",", "condition", "in", "self", ".", "api_conditions", "[", "api_id", "]", "[", "path", "]", ".", "items", "(", ")", "]", ")", "at_least_one_method", "=", "len", "(", "all_method_conditions", ")", ">", "0", "all_methods_contain_conditions", "=", "None", "not", "in", "all_method_conditions", "if", "at_least_one_method", "and", "all_methods_contain_conditions", ":", "if", "len", "(", "all_method_conditions", ")", "==", "1", ":", "editor", ".", "make_path_conditional", "(", "path", ",", "all_method_conditions", ".", "pop", "(", ")", ")", "else", ":", "path_condition_name", "=", "self", ".", "_path_condition_name", "(", "api_id", ",", "path", ")", "self", ".", "_add_combined_condition_to_template", "(", "template", ".", "template_dict", ",", "path_condition_name", ",", "all_method_conditions", ")", "editor", ".", "make_path_conditional", "(", "path", ",", "path_condition_name", ")", "api", ".", "properties", "[", "\"DefinitionBody\"", "]", "=", "editor", ".", "swagger", "template", ".", "set", "(", "api_id", ",", "api", ")" ]
Add conditions to implicit API paths if necessary. Implicit API resource methods are constructed from API events on individual serverless functions within the SAM template. Since serverless functions can have conditions on them, it's possible to have a case where all methods under a resource path have conditions on them. If all of these conditions evaluate to false, the entire resource path should not be defined either. This method checks all resource paths' methods and if all methods under a given path contain a condition, a composite condition is added to the overall template Conditions section and that composite condition is added to the resource path.
[ "Add", "conditions", "to", "implicit", "API", "paths", "if", "necessary", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L282-L317
train
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._path_condition_name
def _path_condition_name(self, api_id, path): """ Generate valid condition logical id from the given API logical id and swagger resource path. """ # only valid characters for CloudFormation logical id are [A-Za-z0-9], but swagger paths can contain # slashes and curly braces for templated params, e.g., /foo/{customerId}. So we'll replace # non-alphanumeric characters. path_logical_id = path.replace('/', 'SLASH').replace('{', 'OB').replace('}', 'CB') return '{}{}PathCondition'.format(api_id, path_logical_id)
python
def _path_condition_name(self, api_id, path): """ Generate valid condition logical id from the given API logical id and swagger resource path. """ # only valid characters for CloudFormation logical id are [A-Za-z0-9], but swagger paths can contain # slashes and curly braces for templated params, e.g., /foo/{customerId}. So we'll replace # non-alphanumeric characters. path_logical_id = path.replace('/', 'SLASH').replace('{', 'OB').replace('}', 'CB') return '{}{}PathCondition'.format(api_id, path_logical_id)
[ "def", "_path_condition_name", "(", "self", ",", "api_id", ",", "path", ")", ":", "# only valid characters for CloudFormation logical id are [A-Za-z0-9], but swagger paths can contain", "# slashes and curly braces for templated params, e.g., /foo/{customerId}. So we'll replace", "# non-alphanumeric characters.", "path_logical_id", "=", "path", ".", "replace", "(", "'/'", ",", "'SLASH'", ")", ".", "replace", "(", "'{'", ",", "'OB'", ")", ".", "replace", "(", "'}'", ",", "'CB'", ")", "return", "'{}{}PathCondition'", ".", "format", "(", "api_id", ",", "path_logical_id", ")" ]
Generate valid condition logical id from the given API logical id and swagger resource path.
[ "Generate", "valid", "condition", "logical", "id", "from", "the", "given", "API", "logical", "id", "and", "swagger", "resource", "path", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L319-L327
train
awslabs/serverless-application-model
samtranslator/plugins/api/implicit_api_plugin.py
ImplicitApiPlugin._maybe_remove_implicit_api
def _maybe_remove_implicit_api(self, template): """ Implicit API resource are tentatively added to the template for uniform handling of both Implicit & Explicit APIs. They need to removed from the template, if there are *no* API events attached to this resource. This method removes the Implicit API if it does not contain any Swagger paths (added in response to API events). :param SamTemplate template: SAM Template containing the Implicit API resource """ # Remove Implicit API resource if no paths got added implicit_api_resource = template.get(self.implicit_api_logical_id) if implicit_api_resource and len(implicit_api_resource.properties["DefinitionBody"]["paths"]) == 0: # If there's no implicit api and the author defined a "ServerlessRestApi" # resource, restore it if self.existing_implicit_api_resource: template.set(self.implicit_api_logical_id, self.existing_implicit_api_resource) else: template.delete(self.implicit_api_logical_id)
python
def _maybe_remove_implicit_api(self, template): """ Implicit API resource are tentatively added to the template for uniform handling of both Implicit & Explicit APIs. They need to removed from the template, if there are *no* API events attached to this resource. This method removes the Implicit API if it does not contain any Swagger paths (added in response to API events). :param SamTemplate template: SAM Template containing the Implicit API resource """ # Remove Implicit API resource if no paths got added implicit_api_resource = template.get(self.implicit_api_logical_id) if implicit_api_resource and len(implicit_api_resource.properties["DefinitionBody"]["paths"]) == 0: # If there's no implicit api and the author defined a "ServerlessRestApi" # resource, restore it if self.existing_implicit_api_resource: template.set(self.implicit_api_logical_id, self.existing_implicit_api_resource) else: template.delete(self.implicit_api_logical_id)
[ "def", "_maybe_remove_implicit_api", "(", "self", ",", "template", ")", ":", "# Remove Implicit API resource if no paths got added", "implicit_api_resource", "=", "template", ".", "get", "(", "self", ".", "implicit_api_logical_id", ")", "if", "implicit_api_resource", "and", "len", "(", "implicit_api_resource", ".", "properties", "[", "\"DefinitionBody\"", "]", "[", "\"paths\"", "]", ")", "==", "0", ":", "# If there's no implicit api and the author defined a \"ServerlessRestApi\"", "# resource, restore it", "if", "self", ".", "existing_implicit_api_resource", ":", "template", ".", "set", "(", "self", ".", "implicit_api_logical_id", ",", "self", ".", "existing_implicit_api_resource", ")", "else", ":", "template", ".", "delete", "(", "self", ".", "implicit_api_logical_id", ")" ]
Implicit API resource are tentatively added to the template for uniform handling of both Implicit & Explicit APIs. They need to removed from the template, if there are *no* API events attached to this resource. This method removes the Implicit API if it does not contain any Swagger paths (added in response to API events). :param SamTemplate template: SAM Template containing the Implicit API resource
[ "Implicit", "API", "resource", "are", "tentatively", "added", "to", "the", "template", "for", "uniform", "handling", "of", "both", "Implicit", "&", "Explicit", "APIs", ".", "They", "need", "to", "removed", "from", "the", "template", "if", "there", "are", "*", "no", "*", "API", "events", "attached", "to", "this", "resource", ".", "This", "method", "removes", "the", "Implicit", "API", "if", "it", "does", "not", "contain", "any", "Swagger", "paths", "(", "added", "in", "response", "to", "API", "events", ")", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/api/implicit_api_plugin.py#L329-L347
train
awslabs/serverless-application-model
samtranslator/model/apigateway.py
ApiGatewayDeployment.make_auto_deployable
def make_auto_deployable(self, stage, swagger=None): """ Sets up the resource such that it will triggers a re-deployment when Swagger changes :param swagger: Dictionary containing the Swagger definition of the API """ if not swagger: return # CloudFormation does NOT redeploy the API unless it has a new deployment resource # that points to latest RestApi resource. Append a hash of Swagger Body location to # redeploy only when the API data changes. First 10 characters of hash is good enough # to prevent redeployment when API has not changed # NOTE: `str(swagger)` is for backwards compatibility. Changing it to a JSON or something will break compat generator = logical_id_generator.LogicalIdGenerator(self.logical_id, str(swagger)) self.logical_id = generator.gen() hash = generator.get_hash(length=40) # Get the full hash self.Description = "RestApi deployment id: {}".format(hash) stage.update_deployment_ref(self.logical_id)
python
def make_auto_deployable(self, stage, swagger=None): """ Sets up the resource such that it will triggers a re-deployment when Swagger changes :param swagger: Dictionary containing the Swagger definition of the API """ if not swagger: return # CloudFormation does NOT redeploy the API unless it has a new deployment resource # that points to latest RestApi resource. Append a hash of Swagger Body location to # redeploy only when the API data changes. First 10 characters of hash is good enough # to prevent redeployment when API has not changed # NOTE: `str(swagger)` is for backwards compatibility. Changing it to a JSON or something will break compat generator = logical_id_generator.LogicalIdGenerator(self.logical_id, str(swagger)) self.logical_id = generator.gen() hash = generator.get_hash(length=40) # Get the full hash self.Description = "RestApi deployment id: {}".format(hash) stage.update_deployment_ref(self.logical_id)
[ "def", "make_auto_deployable", "(", "self", ",", "stage", ",", "swagger", "=", "None", ")", ":", "if", "not", "swagger", ":", "return", "# CloudFormation does NOT redeploy the API unless it has a new deployment resource", "# that points to latest RestApi resource. Append a hash of Swagger Body location to", "# redeploy only when the API data changes. First 10 characters of hash is good enough", "# to prevent redeployment when API has not changed", "# NOTE: `str(swagger)` is for backwards compatibility. Changing it to a JSON or something will break compat", "generator", "=", "logical_id_generator", ".", "LogicalIdGenerator", "(", "self", ".", "logical_id", ",", "str", "(", "swagger", ")", ")", "self", ".", "logical_id", "=", "generator", ".", "gen", "(", ")", "hash", "=", "generator", ".", "get_hash", "(", "length", "=", "40", ")", "# Get the full hash", "self", ".", "Description", "=", "\"RestApi deployment id: {}\"", ".", "format", "(", "hash", ")", "stage", ".", "update_deployment_ref", "(", "self", ".", "logical_id", ")" ]
Sets up the resource such that it will triggers a re-deployment when Swagger changes :param swagger: Dictionary containing the Swagger definition of the API
[ "Sets", "up", "the", "resource", "such", "that", "it", "will", "triggers", "a", "re", "-", "deployment", "when", "Swagger", "changes" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/apigateway.py#L76-L95
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/Lambda.py
Client._invoke_internal
def _invoke_internal(self, function_arn, payload, client_context, invocation_type="RequestResponse"): """ This private method is seperate from the main, public invoke method so that other code within this SDK can give this Lambda client a raw payload/client context to invoke with, rather than having it built for them. This lets you include custom ExtensionMap_ values like subject which are needed for our internal pinned Lambdas. """ customer_logger.info('Invoking Lambda function "{}" with Greengrass Message "{}"'.format(function_arn, payload)) try: invocation_id = self.ipc.post_work(function_arn, payload, client_context, invocation_type) if invocation_type == "Event": # TODO: Properly return errors based on BOTO response # https://boto3.readthedocs.io/en/latest/reference/services/lambda.html#Lambda.Client.invoke return {'Payload': b'', 'FunctionError': ''} work_result_output = self.ipc.get_work_result(function_arn, invocation_id) if not work_result_output.func_err: output_payload = StreamingBody(work_result_output.payload) else: output_payload = work_result_output.payload invoke_output = { 'Payload': output_payload, 'FunctionError': work_result_output.func_err, } return invoke_output except IPCException as e: customer_logger.exception(e) raise InvocationException('Failed to invoke function due to ' + str(e))
python
def _invoke_internal(self, function_arn, payload, client_context, invocation_type="RequestResponse"): """ This private method is seperate from the main, public invoke method so that other code within this SDK can give this Lambda client a raw payload/client context to invoke with, rather than having it built for them. This lets you include custom ExtensionMap_ values like subject which are needed for our internal pinned Lambdas. """ customer_logger.info('Invoking Lambda function "{}" with Greengrass Message "{}"'.format(function_arn, payload)) try: invocation_id = self.ipc.post_work(function_arn, payload, client_context, invocation_type) if invocation_type == "Event": # TODO: Properly return errors based on BOTO response # https://boto3.readthedocs.io/en/latest/reference/services/lambda.html#Lambda.Client.invoke return {'Payload': b'', 'FunctionError': ''} work_result_output = self.ipc.get_work_result(function_arn, invocation_id) if not work_result_output.func_err: output_payload = StreamingBody(work_result_output.payload) else: output_payload = work_result_output.payload invoke_output = { 'Payload': output_payload, 'FunctionError': work_result_output.func_err, } return invoke_output except IPCException as e: customer_logger.exception(e) raise InvocationException('Failed to invoke function due to ' + str(e))
[ "def", "_invoke_internal", "(", "self", ",", "function_arn", ",", "payload", ",", "client_context", ",", "invocation_type", "=", "\"RequestResponse\"", ")", ":", "customer_logger", ".", "info", "(", "'Invoking Lambda function \"{}\" with Greengrass Message \"{}\"'", ".", "format", "(", "function_arn", ",", "payload", ")", ")", "try", ":", "invocation_id", "=", "self", ".", "ipc", ".", "post_work", "(", "function_arn", ",", "payload", ",", "client_context", ",", "invocation_type", ")", "if", "invocation_type", "==", "\"Event\"", ":", "# TODO: Properly return errors based on BOTO response", "# https://boto3.readthedocs.io/en/latest/reference/services/lambda.html#Lambda.Client.invoke", "return", "{", "'Payload'", ":", "b''", ",", "'FunctionError'", ":", "''", "}", "work_result_output", "=", "self", ".", "ipc", ".", "get_work_result", "(", "function_arn", ",", "invocation_id", ")", "if", "not", "work_result_output", ".", "func_err", ":", "output_payload", "=", "StreamingBody", "(", "work_result_output", ".", "payload", ")", "else", ":", "output_payload", "=", "work_result_output", ".", "payload", "invoke_output", "=", "{", "'Payload'", ":", "output_payload", ",", "'FunctionError'", ":", "work_result_output", ".", "func_err", ",", "}", "return", "invoke_output", "except", "IPCException", "as", "e", ":", "customer_logger", ".", "exception", "(", "e", ")", "raise", "InvocationException", "(", "'Failed to invoke function due to '", "+", "str", "(", "e", ")", ")" ]
This private method is seperate from the main, public invoke method so that other code within this SDK can give this Lambda client a raw payload/client context to invoke with, rather than having it built for them. This lets you include custom ExtensionMap_ values like subject which are needed for our internal pinned Lambdas.
[ "This", "private", "method", "is", "seperate", "from", "the", "main", "public", "invoke", "method", "so", "that", "other", "code", "within", "this", "SDK", "can", "give", "this", "Lambda", "client", "a", "raw", "payload", "/", "client", "context", "to", "invoke", "with", "rather", "than", "having", "it", "built", "for", "them", ".", "This", "lets", "you", "include", "custom", "ExtensionMap_", "values", "like", "subject", "which", "are", "needed", "for", "our", "internal", "pinned", "Lambdas", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/Lambda.py#L86-L114
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrasssdk/Lambda.py
StreamingBody.read
def read(self, amt=None): """Read at most amt bytes from the stream. If the amt argument is omitted, read all data. """ chunk = self._raw_stream.read(amt) self._amount_read += len(chunk) return chunk
python
def read(self, amt=None): """Read at most amt bytes from the stream. If the amt argument is omitted, read all data. """ chunk = self._raw_stream.read(amt) self._amount_read += len(chunk) return chunk
[ "def", "read", "(", "self", ",", "amt", "=", "None", ")", ":", "chunk", "=", "self", ".", "_raw_stream", ".", "read", "(", "amt", ")", "self", ".", "_amount_read", "+=", "len", "(", "chunk", ")", "return", "chunk" ]
Read at most amt bytes from the stream. If the amt argument is omitted, read all data.
[ "Read", "at", "most", "amt", "bytes", "from", "the", "stream", ".", "If", "the", "amt", "argument", "is", "omitted", "read", "all", "data", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrasssdk/Lambda.py#L126-L132
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/ipc_client.py
IPCClient.post_work
def post_work(self, function_arn, input_bytes, client_context, invocation_type="RequestResponse"): """ Send work item to specified :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param input_bytes: The data making up the work being posted. :type input_bytes: bytes :param client_context: The base64 encoded client context byte string that will be provided to the Lambda function being invoked. :type client_context: bytes :returns: Invocation ID for obtaining result of the work. :type returns: str """ url = self._get_url(function_arn) runtime_logger.info('Posting work for function [{}] to {}'.format(function_arn, url)) request = Request(url, input_bytes or b'') request.add_header(HEADER_CLIENT_CONTEXT, client_context) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) request.add_header(HEADER_INVOCATION_TYPE, invocation_type) response = urlopen(request) invocation_id = response.info().get(HEADER_INVOCATION_ID) runtime_logger.info('Work posted with invocation id [{}]'.format(invocation_id)) return invocation_id
python
def post_work(self, function_arn, input_bytes, client_context, invocation_type="RequestResponse"): """ Send work item to specified :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param input_bytes: The data making up the work being posted. :type input_bytes: bytes :param client_context: The base64 encoded client context byte string that will be provided to the Lambda function being invoked. :type client_context: bytes :returns: Invocation ID for obtaining result of the work. :type returns: str """ url = self._get_url(function_arn) runtime_logger.info('Posting work for function [{}] to {}'.format(function_arn, url)) request = Request(url, input_bytes or b'') request.add_header(HEADER_CLIENT_CONTEXT, client_context) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) request.add_header(HEADER_INVOCATION_TYPE, invocation_type) response = urlopen(request) invocation_id = response.info().get(HEADER_INVOCATION_ID) runtime_logger.info('Work posted with invocation id [{}]'.format(invocation_id)) return invocation_id
[ "def", "post_work", "(", "self", ",", "function_arn", ",", "input_bytes", ",", "client_context", ",", "invocation_type", "=", "\"RequestResponse\"", ")", ":", "url", "=", "self", ".", "_get_url", "(", "function_arn", ")", "runtime_logger", ".", "info", "(", "'Posting work for function [{}] to {}'", ".", "format", "(", "function_arn", ",", "url", ")", ")", "request", "=", "Request", "(", "url", ",", "input_bytes", "or", "b''", ")", "request", ".", "add_header", "(", "HEADER_CLIENT_CONTEXT", ",", "client_context", ")", "request", ".", "add_header", "(", "HEADER_AUTH_TOKEN", ",", "self", ".", "auth_token", ")", "request", ".", "add_header", "(", "HEADER_INVOCATION_TYPE", ",", "invocation_type", ")", "response", "=", "urlopen", "(", "request", ")", "invocation_id", "=", "response", ".", "info", "(", ")", ".", "get", "(", "HEADER_INVOCATION_ID", ")", "runtime_logger", ".", "info", "(", "'Work posted with invocation id [{}]'", ".", "format", "(", "invocation_id", ")", ")", "return", "invocation_id" ]
Send work item to specified :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param input_bytes: The data making up the work being posted. :type input_bytes: bytes :param client_context: The base64 encoded client context byte string that will be provided to the Lambda function being invoked. :type client_context: bytes :returns: Invocation ID for obtaining result of the work. :type returns: str
[ "Send", "work", "item", "to", "specified", ":", "code", ":", "function_arn", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/ipc_client.py#L81-L110
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/ipc_client.py
IPCClient.get_work
def get_work(self, function_arn): """ Retrieve the next work item for specified :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :returns: Next work item to be processed by the function. :type returns: WorkItem """ url = self._get_work_url(function_arn) runtime_logger.info('Getting work for function [{}] from {}'.format(function_arn, url)) request = Request(url) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) response = urlopen(request) invocation_id = response.info().get(HEADER_INVOCATION_ID) client_context = response.info().get(HEADER_CLIENT_CONTEXT) runtime_logger.info('Got work item with invocation id [{}]'.format(invocation_id)) return WorkItem( invocation_id=invocation_id, payload=response.read(), client_context=client_context)
python
def get_work(self, function_arn): """ Retrieve the next work item for specified :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :returns: Next work item to be processed by the function. :type returns: WorkItem """ url = self._get_work_url(function_arn) runtime_logger.info('Getting work for function [{}] from {}'.format(function_arn, url)) request = Request(url) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) response = urlopen(request) invocation_id = response.info().get(HEADER_INVOCATION_ID) client_context = response.info().get(HEADER_CLIENT_CONTEXT) runtime_logger.info('Got work item with invocation id [{}]'.format(invocation_id)) return WorkItem( invocation_id=invocation_id, payload=response.read(), client_context=client_context)
[ "def", "get_work", "(", "self", ",", "function_arn", ")", ":", "url", "=", "self", ".", "_get_work_url", "(", "function_arn", ")", "runtime_logger", ".", "info", "(", "'Getting work for function [{}] from {}'", ".", "format", "(", "function_arn", ",", "url", ")", ")", "request", "=", "Request", "(", "url", ")", "request", ".", "add_header", "(", "HEADER_AUTH_TOKEN", ",", "self", ".", "auth_token", ")", "response", "=", "urlopen", "(", "request", ")", "invocation_id", "=", "response", ".", "info", "(", ")", ".", "get", "(", "HEADER_INVOCATION_ID", ")", "client_context", "=", "response", ".", "info", "(", ")", ".", "get", "(", "HEADER_CLIENT_CONTEXT", ")", "runtime_logger", ".", "info", "(", "'Got work item with invocation id [{}]'", ".", "format", "(", "invocation_id", ")", ")", "return", "WorkItem", "(", "invocation_id", "=", "invocation_id", ",", "payload", "=", "response", ".", "read", "(", ")", ",", "client_context", "=", "client_context", ")" ]
Retrieve the next work item for specified :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :returns: Next work item to be processed by the function. :type returns: WorkItem
[ "Retrieve", "the", "next", "work", "item", "for", "specified", ":", "code", ":", "function_arn", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/ipc_client.py#L113-L138
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/ipc_client.py
IPCClient.post_work_result
def post_work_result(self, function_arn, work_item): """ Post the result of processing work item by :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param work_item: The WorkItem holding the results of the work being posted. :type work_item: WorkItem :returns: None """ url = self._get_work_url(function_arn) runtime_logger.info('Posting work result for invocation id [{}] to {}'.format(work_item.invocation_id, url)) request = Request(url, work_item.payload or b'') request.add_header(HEADER_INVOCATION_ID, work_item.invocation_id) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) urlopen(request) runtime_logger.info('Posted work result for invocation id [{}]'.format(work_item.invocation_id))
python
def post_work_result(self, function_arn, work_item): """ Post the result of processing work item by :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param work_item: The WorkItem holding the results of the work being posted. :type work_item: WorkItem :returns: None """ url = self._get_work_url(function_arn) runtime_logger.info('Posting work result for invocation id [{}] to {}'.format(work_item.invocation_id, url)) request = Request(url, work_item.payload or b'') request.add_header(HEADER_INVOCATION_ID, work_item.invocation_id) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) urlopen(request) runtime_logger.info('Posted work result for invocation id [{}]'.format(work_item.invocation_id))
[ "def", "post_work_result", "(", "self", ",", "function_arn", ",", "work_item", ")", ":", "url", "=", "self", ".", "_get_work_url", "(", "function_arn", ")", "runtime_logger", ".", "info", "(", "'Posting work result for invocation id [{}] to {}'", ".", "format", "(", "work_item", ".", "invocation_id", ",", "url", ")", ")", "request", "=", "Request", "(", "url", ",", "work_item", ".", "payload", "or", "b''", ")", "request", ".", "add_header", "(", "HEADER_INVOCATION_ID", ",", "work_item", ".", "invocation_id", ")", "request", ".", "add_header", "(", "HEADER_AUTH_TOKEN", ",", "self", ".", "auth_token", ")", "urlopen", "(", "request", ")", "runtime_logger", ".", "info", "(", "'Posted work result for invocation id [{}]'", ".", "format", "(", "work_item", ".", "invocation_id", ")", ")" ]
Post the result of processing work item by :code:`function_arn`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param work_item: The WorkItem holding the results of the work being posted. :type work_item: WorkItem :returns: None
[ "Post", "the", "result", "of", "processing", "work", "item", "by", ":", "code", ":", "function_arn", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/ipc_client.py#L141-L163
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/ipc_client.py
IPCClient.post_handler_err
def post_handler_err(self, function_arn, invocation_id, handler_err): """ Post the error message from executing the function handler for :code:`function_arn` with specifid :code:`invocation_id` :param function_arn: Arn of the Lambda function which has the handler error message. :type function_arn: string :param invocation_id: Invocation ID of the work that is being requested :type invocation_id: string :param handler_err: the error message caught from handler :type handler_err: string """ url = self._get_work_url(function_arn) runtime_logger.info('Posting handler error for invocation id [{}] to {}'.format(invocation_id, url)) payload = json.dumps({ "errorMessage": handler_err, }).encode('utf-8') request = Request(url, payload) request.add_header(HEADER_INVOCATION_ID, invocation_id) request.add_header(HEADER_FUNCTION_ERR_TYPE, "Handled") request.add_header(HEADER_AUTH_TOKEN, self.auth_token) urlopen(request) runtime_logger.info('Posted handler error for invocation id [{}]'.format(invocation_id))
python
def post_handler_err(self, function_arn, invocation_id, handler_err): """ Post the error message from executing the function handler for :code:`function_arn` with specifid :code:`invocation_id` :param function_arn: Arn of the Lambda function which has the handler error message. :type function_arn: string :param invocation_id: Invocation ID of the work that is being requested :type invocation_id: string :param handler_err: the error message caught from handler :type handler_err: string """ url = self._get_work_url(function_arn) runtime_logger.info('Posting handler error for invocation id [{}] to {}'.format(invocation_id, url)) payload = json.dumps({ "errorMessage": handler_err, }).encode('utf-8') request = Request(url, payload) request.add_header(HEADER_INVOCATION_ID, invocation_id) request.add_header(HEADER_FUNCTION_ERR_TYPE, "Handled") request.add_header(HEADER_AUTH_TOKEN, self.auth_token) urlopen(request) runtime_logger.info('Posted handler error for invocation id [{}]'.format(invocation_id))
[ "def", "post_handler_err", "(", "self", ",", "function_arn", ",", "invocation_id", ",", "handler_err", ")", ":", "url", "=", "self", ".", "_get_work_url", "(", "function_arn", ")", "runtime_logger", ".", "info", "(", "'Posting handler error for invocation id [{}] to {}'", ".", "format", "(", "invocation_id", ",", "url", ")", ")", "payload", "=", "json", ".", "dumps", "(", "{", "\"errorMessage\"", ":", "handler_err", ",", "}", ")", ".", "encode", "(", "'utf-8'", ")", "request", "=", "Request", "(", "url", ",", "payload", ")", "request", ".", "add_header", "(", "HEADER_INVOCATION_ID", ",", "invocation_id", ")", "request", ".", "add_header", "(", "HEADER_FUNCTION_ERR_TYPE", ",", "\"Handled\"", ")", "request", ".", "add_header", "(", "HEADER_AUTH_TOKEN", ",", "self", ".", "auth_token", ")", "urlopen", "(", "request", ")", "runtime_logger", ".", "info", "(", "'Posted handler error for invocation id [{}]'", ".", "format", "(", "invocation_id", ")", ")" ]
Post the error message from executing the function handler for :code:`function_arn` with specifid :code:`invocation_id` :param function_arn: Arn of the Lambda function which has the handler error message. :type function_arn: string :param invocation_id: Invocation ID of the work that is being requested :type invocation_id: string :param handler_err: the error message caught from handler :type handler_err: string
[ "Post", "the", "error", "message", "from", "executing", "the", "function", "handler", "for", ":", "code", ":", "function_arn", "with", "specifid", ":", "code", ":", "invocation_id" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/ipc_client.py#L166-L196
train
awslabs/serverless-application-model
examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/ipc_client.py
IPCClient.get_work_result
def get_work_result(self, function_arn, invocation_id): """ Retrieve the result of the work processed by :code:`function_arn` with specified :code:`invocation_id`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param invocation_id: Invocation ID of the work that is being requested :type invocation_id: string :returns: The get work result output contains result payload and function error type if the invoking is failed. :type returns: GetWorkResultOutput """ url = self._get_url(function_arn) runtime_logger.info('Getting work result for invocation id [{}] from {}'.format(invocation_id, url)) request = Request(url) request.add_header(HEADER_INVOCATION_ID, invocation_id) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) response = urlopen(request) runtime_logger.info('Got result for invocation id [{}]'.format(invocation_id)) payload = response.read() func_err = response.info().get(HEADER_FUNCTION_ERR_TYPE) return GetWorkResultOutput( payload=payload, func_err=func_err)
python
def get_work_result(self, function_arn, invocation_id): """ Retrieve the result of the work processed by :code:`function_arn` with specified :code:`invocation_id`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param invocation_id: Invocation ID of the work that is being requested :type invocation_id: string :returns: The get work result output contains result payload and function error type if the invoking is failed. :type returns: GetWorkResultOutput """ url = self._get_url(function_arn) runtime_logger.info('Getting work result for invocation id [{}] from {}'.format(invocation_id, url)) request = Request(url) request.add_header(HEADER_INVOCATION_ID, invocation_id) request.add_header(HEADER_AUTH_TOKEN, self.auth_token) response = urlopen(request) runtime_logger.info('Got result for invocation id [{}]'.format(invocation_id)) payload = response.read() func_err = response.info().get(HEADER_FUNCTION_ERR_TYPE) return GetWorkResultOutput( payload=payload, func_err=func_err)
[ "def", "get_work_result", "(", "self", ",", "function_arn", ",", "invocation_id", ")", ":", "url", "=", "self", ".", "_get_url", "(", "function_arn", ")", "runtime_logger", ".", "info", "(", "'Getting work result for invocation id [{}] from {}'", ".", "format", "(", "invocation_id", ",", "url", ")", ")", "request", "=", "Request", "(", "url", ")", "request", ".", "add_header", "(", "HEADER_INVOCATION_ID", ",", "invocation_id", ")", "request", ".", "add_header", "(", "HEADER_AUTH_TOKEN", ",", "self", ".", "auth_token", ")", "response", "=", "urlopen", "(", "request", ")", "runtime_logger", ".", "info", "(", "'Got result for invocation id [{}]'", ".", "format", "(", "invocation_id", ")", ")", "payload", "=", "response", ".", "read", "(", ")", "func_err", "=", "response", ".", "info", "(", ")", ".", "get", "(", "HEADER_FUNCTION_ERR_TYPE", ")", "return", "GetWorkResultOutput", "(", "payload", "=", "payload", ",", "func_err", "=", "func_err", ")" ]
Retrieve the result of the work processed by :code:`function_arn` with specified :code:`invocation_id`. :param function_arn: Arn of the Lambda function intended to receive the work for processing. :type function_arn: string :param invocation_id: Invocation ID of the work that is being requested :type invocation_id: string :returns: The get work result output contains result payload and function error type if the invoking is failed. :type returns: GetWorkResultOutput
[ "Retrieve", "the", "result", "of", "the", "work", "processed", "by", ":", "code", ":", "function_arn", "with", "specified", ":", "code", ":", "invocation_id", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/greengrass-hello-world/greengrass_ipc_python_sdk/ipc_client.py#L199-L230
train
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin.on_before_transform_template
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. This plugin needs to run as soon as possible to allow some time for templates to become available. This verifies that the user has access to all specified applications. :param dict template_dict: Dictionary of the SAM template :return: Nothing """ template = SamTemplate(template_dict) intrinsic_resolvers = self._get_intrinsic_resolvers(template_dict.get('Mappings', {})) service_call = None if self._validate_only: service_call = self._handle_get_application_request else: service_call = self._handle_create_cfn_template_request for logical_id, app in template.iterate(SamResourceType.Application.value): if not self._can_process_application(app): # Handle these cases in the on_before_transform_resource event continue app_id = self._replace_value(app.properties[self.LOCATION_KEY], self.APPLICATION_ID_KEY, intrinsic_resolvers) semver = self._replace_value(app.properties[self.LOCATION_KEY], self.SEMANTIC_VERSION_KEY, intrinsic_resolvers) if isinstance(app_id, dict) or isinstance(semver, dict): key = (json.dumps(app_id), json.dumps(semver)) self._applications[key] = False continue key = (app_id, semver) if key not in self._applications: try: # Lazy initialization of the client- create it when it is needed if not self._sar_client: self._sar_client = boto3.client('serverlessrepo') service_call(app_id, semver, key, logical_id) except InvalidResourceException as e: # Catch all InvalidResourceExceptions, raise those in the before_resource_transform target. self._applications[key] = e
python
def on_before_transform_template(self, template_dict): """ Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. This plugin needs to run as soon as possible to allow some time for templates to become available. This verifies that the user has access to all specified applications. :param dict template_dict: Dictionary of the SAM template :return: Nothing """ template = SamTemplate(template_dict) intrinsic_resolvers = self._get_intrinsic_resolvers(template_dict.get('Mappings', {})) service_call = None if self._validate_only: service_call = self._handle_get_application_request else: service_call = self._handle_create_cfn_template_request for logical_id, app in template.iterate(SamResourceType.Application.value): if not self._can_process_application(app): # Handle these cases in the on_before_transform_resource event continue app_id = self._replace_value(app.properties[self.LOCATION_KEY], self.APPLICATION_ID_KEY, intrinsic_resolvers) semver = self._replace_value(app.properties[self.LOCATION_KEY], self.SEMANTIC_VERSION_KEY, intrinsic_resolvers) if isinstance(app_id, dict) or isinstance(semver, dict): key = (json.dumps(app_id), json.dumps(semver)) self._applications[key] = False continue key = (app_id, semver) if key not in self._applications: try: # Lazy initialization of the client- create it when it is needed if not self._sar_client: self._sar_client = boto3.client('serverlessrepo') service_call(app_id, semver, key, logical_id) except InvalidResourceException as e: # Catch all InvalidResourceExceptions, raise those in the before_resource_transform target. self._applications[key] = e
[ "def", "on_before_transform_template", "(", "self", ",", "template_dict", ")", ":", "template", "=", "SamTemplate", "(", "template_dict", ")", "intrinsic_resolvers", "=", "self", ".", "_get_intrinsic_resolvers", "(", "template_dict", ".", "get", "(", "'Mappings'", ",", "{", "}", ")", ")", "service_call", "=", "None", "if", "self", ".", "_validate_only", ":", "service_call", "=", "self", ".", "_handle_get_application_request", "else", ":", "service_call", "=", "self", ".", "_handle_create_cfn_template_request", "for", "logical_id", ",", "app", "in", "template", ".", "iterate", "(", "SamResourceType", ".", "Application", ".", "value", ")", ":", "if", "not", "self", ".", "_can_process_application", "(", "app", ")", ":", "# Handle these cases in the on_before_transform_resource event", "continue", "app_id", "=", "self", ".", "_replace_value", "(", "app", ".", "properties", "[", "self", ".", "LOCATION_KEY", "]", ",", "self", ".", "APPLICATION_ID_KEY", ",", "intrinsic_resolvers", ")", "semver", "=", "self", ".", "_replace_value", "(", "app", ".", "properties", "[", "self", ".", "LOCATION_KEY", "]", ",", "self", ".", "SEMANTIC_VERSION_KEY", ",", "intrinsic_resolvers", ")", "if", "isinstance", "(", "app_id", ",", "dict", ")", "or", "isinstance", "(", "semver", ",", "dict", ")", ":", "key", "=", "(", "json", ".", "dumps", "(", "app_id", ")", ",", "json", ".", "dumps", "(", "semver", ")", ")", "self", ".", "_applications", "[", "key", "]", "=", "False", "continue", "key", "=", "(", "app_id", ",", "semver", ")", "if", "key", "not", "in", "self", ".", "_applications", ":", "try", ":", "# Lazy initialization of the client- create it when it is needed", "if", "not", "self", ".", "_sar_client", ":", "self", ".", "_sar_client", "=", "boto3", ".", "client", "(", "'serverlessrepo'", ")", "service_call", "(", "app_id", ",", "semver", ",", "key", ",", "logical_id", ")", "except", "InvalidResourceException", "as", "e", ":", "# Catch all InvalidResourceExceptions, raise those in the before_resource_transform target.", "self", ".", "_applications", "[", "key", "]", "=", "e" ]
Hook method that gets called before the SAM template is processed. The template has passed the validation and is guaranteed to contain a non-empty "Resources" section. This plugin needs to run as soon as possible to allow some time for templates to become available. This verifies that the user has access to all specified applications. :param dict template_dict: Dictionary of the SAM template :return: Nothing
[ "Hook", "method", "that", "gets", "called", "before", "the", "SAM", "template", "is", "processed", ".", "The", "template", "has", "passed", "the", "validation", "and", "is", "guaranteed", "to", "contain", "a", "non", "-", "empty", "Resources", "section", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L64-L109
train
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._can_process_application
def _can_process_application(self, app): """ Determines whether or not the on_before_transform_template event can process this application :param dict app: the application and its properties """ return (self.LOCATION_KEY in app.properties and isinstance(app.properties[self.LOCATION_KEY], dict) and self.APPLICATION_ID_KEY in app.properties[self.LOCATION_KEY] and self.SEMANTIC_VERSION_KEY in app.properties[self.LOCATION_KEY])
python
def _can_process_application(self, app): """ Determines whether or not the on_before_transform_template event can process this application :param dict app: the application and its properties """ return (self.LOCATION_KEY in app.properties and isinstance(app.properties[self.LOCATION_KEY], dict) and self.APPLICATION_ID_KEY in app.properties[self.LOCATION_KEY] and self.SEMANTIC_VERSION_KEY in app.properties[self.LOCATION_KEY])
[ "def", "_can_process_application", "(", "self", ",", "app", ")", ":", "return", "(", "self", ".", "LOCATION_KEY", "in", "app", ".", "properties", "and", "isinstance", "(", "app", ".", "properties", "[", "self", ".", "LOCATION_KEY", "]", ",", "dict", ")", "and", "self", ".", "APPLICATION_ID_KEY", "in", "app", ".", "properties", "[", "self", ".", "LOCATION_KEY", "]", "and", "self", ".", "SEMANTIC_VERSION_KEY", "in", "app", ".", "properties", "[", "self", ".", "LOCATION_KEY", "]", ")" ]
Determines whether or not the on_before_transform_template event can process this application :param dict app: the application and its properties
[ "Determines", "whether", "or", "not", "the", "on_before_transform_template", "event", "can", "process", "this", "application" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L126-L135
train
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._handle_get_application_request
def _handle_get_application_request(self, app_id, semver, key, logical_id): """ Method that handles the get_application API call to the serverless application repo This method puts something in the `_applications` dictionary because the plugin expects something there in a later event. :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource """ get_application = (lambda app_id, semver: self._sar_client.get_application( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver))) try: self._sar_service_call(get_application, logical_id, app_id, semver) self._applications[key] = {'Available'} except EndpointConnectionError as e: # No internet connection. Don't break verification, but do show a warning. warning_message = "{}. Unable to verify access to {}/{}.".format(e, app_id, semver) logging.warning(warning_message) self._applications[key] = {'Unable to verify'}
python
def _handle_get_application_request(self, app_id, semver, key, logical_id): """ Method that handles the get_application API call to the serverless application repo This method puts something in the `_applications` dictionary because the plugin expects something there in a later event. :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource """ get_application = (lambda app_id, semver: self._sar_client.get_application( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver))) try: self._sar_service_call(get_application, logical_id, app_id, semver) self._applications[key] = {'Available'} except EndpointConnectionError as e: # No internet connection. Don't break verification, but do show a warning. warning_message = "{}. Unable to verify access to {}/{}.".format(e, app_id, semver) logging.warning(warning_message) self._applications[key] = {'Unable to verify'}
[ "def", "_handle_get_application_request", "(", "self", ",", "app_id", ",", "semver", ",", "key", ",", "logical_id", ")", ":", "get_application", "=", "(", "lambda", "app_id", ",", "semver", ":", "self", ".", "_sar_client", ".", "get_application", "(", "ApplicationId", "=", "self", ".", "_sanitize_sar_str_param", "(", "app_id", ")", ",", "SemanticVersion", "=", "self", ".", "_sanitize_sar_str_param", "(", "semver", ")", ")", ")", "try", ":", "self", ".", "_sar_service_call", "(", "get_application", ",", "logical_id", ",", "app_id", ",", "semver", ")", "self", ".", "_applications", "[", "key", "]", "=", "{", "'Available'", "}", "except", "EndpointConnectionError", "as", "e", ":", "# No internet connection. Don't break verification, but do show a warning.", "warning_message", "=", "\"{}. Unable to verify access to {}/{}.\"", ".", "format", "(", "e", ",", "app_id", ",", "semver", ")", "logging", ".", "warning", "(", "warning_message", ")", "self", ".", "_applications", "[", "key", "]", "=", "{", "'Unable to verify'", "}" ]
Method that handles the get_application API call to the serverless application repo This method puts something in the `_applications` dictionary because the plugin expects something there in a later event. :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource
[ "Method", "that", "handles", "the", "get_application", "API", "call", "to", "the", "serverless", "application", "repo" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L137-L159
train
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._handle_create_cfn_template_request
def _handle_create_cfn_template_request(self, app_id, semver, key, logical_id): """ Method that handles the create_cloud_formation_template API call to the serverless application repo :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource """ create_cfn_template = (lambda app_id, semver: self._sar_client.create_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver) )) response = self._sar_service_call(create_cfn_template, logical_id, app_id, semver) self._applications[key] = response[self.TEMPLATE_URL_KEY] if response['Status'] != "ACTIVE": self._in_progress_templates.append((response[self.APPLICATION_ID_KEY], response['TemplateId']))
python
def _handle_create_cfn_template_request(self, app_id, semver, key, logical_id): """ Method that handles the create_cloud_formation_template API call to the serverless application repo :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource """ create_cfn_template = (lambda app_id, semver: self._sar_client.create_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(app_id), SemanticVersion=self._sanitize_sar_str_param(semver) )) response = self._sar_service_call(create_cfn_template, logical_id, app_id, semver) self._applications[key] = response[self.TEMPLATE_URL_KEY] if response['Status'] != "ACTIVE": self._in_progress_templates.append((response[self.APPLICATION_ID_KEY], response['TemplateId']))
[ "def", "_handle_create_cfn_template_request", "(", "self", ",", "app_id", ",", "semver", ",", "key", ",", "logical_id", ")", ":", "create_cfn_template", "=", "(", "lambda", "app_id", ",", "semver", ":", "self", ".", "_sar_client", ".", "create_cloud_formation_template", "(", "ApplicationId", "=", "self", ".", "_sanitize_sar_str_param", "(", "app_id", ")", ",", "SemanticVersion", "=", "self", ".", "_sanitize_sar_str_param", "(", "semver", ")", ")", ")", "response", "=", "self", ".", "_sar_service_call", "(", "create_cfn_template", ",", "logical_id", ",", "app_id", ",", "semver", ")", "self", ".", "_applications", "[", "key", "]", "=", "response", "[", "self", ".", "TEMPLATE_URL_KEY", "]", "if", "response", "[", "'Status'", "]", "!=", "\"ACTIVE\"", ":", "self", ".", "_in_progress_templates", ".", "append", "(", "(", "response", "[", "self", ".", "APPLICATION_ID_KEY", "]", ",", "response", "[", "'TemplateId'", "]", ")", ")" ]
Method that handles the create_cloud_formation_template API call to the serverless application repo :param string app_id: ApplicationId :param string semver: SemanticVersion :param string key: The dictionary key consisting of (ApplicationId, SemanticVersion) :param string logical_id: the logical_id of this application resource
[ "Method", "that", "handles", "the", "create_cloud_formation_template", "API", "call", "to", "the", "serverless", "application", "repo" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L161-L177
train
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin.on_before_transform_resource
def on_before_transform_resource(self, logical_id, resource_type, resource_properties): """ Hook method that gets called before "each" SAM resource gets processed Replaces the ApplicationId and Semantic Version pairs with a TemplateUrl. :param string logical_id: Logical ID of the resource being processed :param string resource_type: Type of the resource being processed :param dict resource_properties: Properties of the resource :return: Nothing """ if not self._resource_is_supported(resource_type): return # Sanitize properties self._check_for_dictionary_key(logical_id, resource_properties, [self.LOCATION_KEY]) # If location isn't a dictionary, don't modify the resource. if not isinstance(resource_properties[self.LOCATION_KEY], dict): resource_properties[self.TEMPLATE_URL_KEY] = resource_properties[self.LOCATION_KEY] return # If it is a dictionary, check for other required parameters self._check_for_dictionary_key(logical_id, resource_properties[self.LOCATION_KEY], [self.APPLICATION_ID_KEY, self.SEMANTIC_VERSION_KEY]) app_id = resource_properties[self.LOCATION_KEY].get(self.APPLICATION_ID_KEY) if not app_id: raise InvalidResourceException(logical_id, "Property 'ApplicationId' cannot be blank.") if isinstance(app_id, dict): raise InvalidResourceException(logical_id, "Property 'ApplicationId' cannot be resolved. Only FindInMap " "and Ref intrinsic functions are supported.") semver = resource_properties[self.LOCATION_KEY].get(self.SEMANTIC_VERSION_KEY) if not semver: raise InvalidResourceException(logical_id, "Property 'SemanticVersion' cannot be blank.") if isinstance(semver, dict): raise InvalidResourceException(logical_id, "Property 'SemanticVersion' cannot be resolved. Only FindInMap " "and Ref intrinsic functions are supported.") key = (app_id, semver) # Throw any resource exceptions saved from the before_transform_template event if isinstance(self._applications[key], InvalidResourceException): raise self._applications[key] # validation does not resolve an actual template url if not self._validate_only: resource_properties[self.TEMPLATE_URL_KEY] = self._applications[key]
python
def on_before_transform_resource(self, logical_id, resource_type, resource_properties): """ Hook method that gets called before "each" SAM resource gets processed Replaces the ApplicationId and Semantic Version pairs with a TemplateUrl. :param string logical_id: Logical ID of the resource being processed :param string resource_type: Type of the resource being processed :param dict resource_properties: Properties of the resource :return: Nothing """ if not self._resource_is_supported(resource_type): return # Sanitize properties self._check_for_dictionary_key(logical_id, resource_properties, [self.LOCATION_KEY]) # If location isn't a dictionary, don't modify the resource. if not isinstance(resource_properties[self.LOCATION_KEY], dict): resource_properties[self.TEMPLATE_URL_KEY] = resource_properties[self.LOCATION_KEY] return # If it is a dictionary, check for other required parameters self._check_for_dictionary_key(logical_id, resource_properties[self.LOCATION_KEY], [self.APPLICATION_ID_KEY, self.SEMANTIC_VERSION_KEY]) app_id = resource_properties[self.LOCATION_KEY].get(self.APPLICATION_ID_KEY) if not app_id: raise InvalidResourceException(logical_id, "Property 'ApplicationId' cannot be blank.") if isinstance(app_id, dict): raise InvalidResourceException(logical_id, "Property 'ApplicationId' cannot be resolved. Only FindInMap " "and Ref intrinsic functions are supported.") semver = resource_properties[self.LOCATION_KEY].get(self.SEMANTIC_VERSION_KEY) if not semver: raise InvalidResourceException(logical_id, "Property 'SemanticVersion' cannot be blank.") if isinstance(semver, dict): raise InvalidResourceException(logical_id, "Property 'SemanticVersion' cannot be resolved. Only FindInMap " "and Ref intrinsic functions are supported.") key = (app_id, semver) # Throw any resource exceptions saved from the before_transform_template event if isinstance(self._applications[key], InvalidResourceException): raise self._applications[key] # validation does not resolve an actual template url if not self._validate_only: resource_properties[self.TEMPLATE_URL_KEY] = self._applications[key]
[ "def", "on_before_transform_resource", "(", "self", ",", "logical_id", ",", "resource_type", ",", "resource_properties", ")", ":", "if", "not", "self", ".", "_resource_is_supported", "(", "resource_type", ")", ":", "return", "# Sanitize properties", "self", ".", "_check_for_dictionary_key", "(", "logical_id", ",", "resource_properties", ",", "[", "self", ".", "LOCATION_KEY", "]", ")", "# If location isn't a dictionary, don't modify the resource.", "if", "not", "isinstance", "(", "resource_properties", "[", "self", ".", "LOCATION_KEY", "]", ",", "dict", ")", ":", "resource_properties", "[", "self", ".", "TEMPLATE_URL_KEY", "]", "=", "resource_properties", "[", "self", ".", "LOCATION_KEY", "]", "return", "# If it is a dictionary, check for other required parameters", "self", ".", "_check_for_dictionary_key", "(", "logical_id", ",", "resource_properties", "[", "self", ".", "LOCATION_KEY", "]", ",", "[", "self", ".", "APPLICATION_ID_KEY", ",", "self", ".", "SEMANTIC_VERSION_KEY", "]", ")", "app_id", "=", "resource_properties", "[", "self", ".", "LOCATION_KEY", "]", ".", "get", "(", "self", ".", "APPLICATION_ID_KEY", ")", "if", "not", "app_id", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Property 'ApplicationId' cannot be blank.\"", ")", "if", "isinstance", "(", "app_id", ",", "dict", ")", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Property 'ApplicationId' cannot be resolved. Only FindInMap \"", "\"and Ref intrinsic functions are supported.\"", ")", "semver", "=", "resource_properties", "[", "self", ".", "LOCATION_KEY", "]", ".", "get", "(", "self", ".", "SEMANTIC_VERSION_KEY", ")", "if", "not", "semver", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Property 'SemanticVersion' cannot be blank.\"", ")", "if", "isinstance", "(", "semver", ",", "dict", ")", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Property 'SemanticVersion' cannot be resolved. Only FindInMap \"", "\"and Ref intrinsic functions are supported.\"", ")", "key", "=", "(", "app_id", ",", "semver", ")", "# Throw any resource exceptions saved from the before_transform_template event", "if", "isinstance", "(", "self", ".", "_applications", "[", "key", "]", ",", "InvalidResourceException", ")", ":", "raise", "self", ".", "_applications", "[", "key", "]", "# validation does not resolve an actual template url", "if", "not", "self", ".", "_validate_only", ":", "resource_properties", "[", "self", ".", "TEMPLATE_URL_KEY", "]", "=", "self", ".", "_applications", "[", "key", "]" ]
Hook method that gets called before "each" SAM resource gets processed Replaces the ApplicationId and Semantic Version pairs with a TemplateUrl. :param string logical_id: Logical ID of the resource being processed :param string resource_type: Type of the resource being processed :param dict resource_properties: Properties of the resource :return: Nothing
[ "Hook", "method", "that", "gets", "called", "before", "each", "SAM", "resource", "gets", "processed" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L194-L247
train
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._check_for_dictionary_key
def _check_for_dictionary_key(self, logical_id, dictionary, keys): """ Checks a dictionary to make sure it has a specific key. If it does not, an InvalidResourceException is thrown. :param string logical_id: logical id of this resource :param dict dictionary: the dictionary to check :param list keys: list of keys that should exist in the dictionary """ for key in keys: if key not in dictionary: raise InvalidResourceException(logical_id, 'Resource is missing the required [{}] ' 'property.'.format(key))
python
def _check_for_dictionary_key(self, logical_id, dictionary, keys): """ Checks a dictionary to make sure it has a specific key. If it does not, an InvalidResourceException is thrown. :param string logical_id: logical id of this resource :param dict dictionary: the dictionary to check :param list keys: list of keys that should exist in the dictionary """ for key in keys: if key not in dictionary: raise InvalidResourceException(logical_id, 'Resource is missing the required [{}] ' 'property.'.format(key))
[ "def", "_check_for_dictionary_key", "(", "self", ",", "logical_id", ",", "dictionary", ",", "keys", ")", ":", "for", "key", "in", "keys", ":", "if", "key", "not", "in", "dictionary", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "'Resource is missing the required [{}] '", "'property.'", ".", "format", "(", "key", ")", ")" ]
Checks a dictionary to make sure it has a specific key. If it does not, an InvalidResourceException is thrown. :param string logical_id: logical id of this resource :param dict dictionary: the dictionary to check :param list keys: list of keys that should exist in the dictionary
[ "Checks", "a", "dictionary", "to", "make", "sure", "it", "has", "a", "specific", "key", ".", "If", "it", "does", "not", "an", "InvalidResourceException", "is", "thrown", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L249-L261
train
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin.on_after_transform_template
def on_after_transform_template(self, template): """ Hook method that gets called after the template is processed Go through all the stored applications and make sure they're all ACTIVE. :param dict template: Dictionary of the SAM template :return: Nothing """ if self._wait_for_template_active_status and not self._validate_only: start_time = time() while (time() - start_time) < self.TEMPLATE_WAIT_TIMEOUT_SECONDS: temp = self._in_progress_templates self._in_progress_templates = [] # Check each resource to make sure it's active for application_id, template_id in temp: get_cfn_template = (lambda application_id, template_id: self._sar_client.get_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(application_id), TemplateId=self._sanitize_sar_str_param(template_id))) response = self._sar_service_call(get_cfn_template, application_id, application_id, template_id) self._handle_get_cfn_template_response(response, application_id, template_id) # Don't sleep if there are no more templates with PREPARING status if len(self._in_progress_templates) == 0: break # Sleep a little so we don't spam service calls sleep(self.SLEEP_TIME_SECONDS) # Not all templates reached active status if len(self._in_progress_templates) != 0: application_ids = [items[0] for items in self._in_progress_templates] raise InvalidResourceException(application_ids, "Timed out waiting for nested stack templates " "to reach ACTIVE status.")
python
def on_after_transform_template(self, template): """ Hook method that gets called after the template is processed Go through all the stored applications and make sure they're all ACTIVE. :param dict template: Dictionary of the SAM template :return: Nothing """ if self._wait_for_template_active_status and not self._validate_only: start_time = time() while (time() - start_time) < self.TEMPLATE_WAIT_TIMEOUT_SECONDS: temp = self._in_progress_templates self._in_progress_templates = [] # Check each resource to make sure it's active for application_id, template_id in temp: get_cfn_template = (lambda application_id, template_id: self._sar_client.get_cloud_formation_template( ApplicationId=self._sanitize_sar_str_param(application_id), TemplateId=self._sanitize_sar_str_param(template_id))) response = self._sar_service_call(get_cfn_template, application_id, application_id, template_id) self._handle_get_cfn_template_response(response, application_id, template_id) # Don't sleep if there are no more templates with PREPARING status if len(self._in_progress_templates) == 0: break # Sleep a little so we don't spam service calls sleep(self.SLEEP_TIME_SECONDS) # Not all templates reached active status if len(self._in_progress_templates) != 0: application_ids = [items[0] for items in self._in_progress_templates] raise InvalidResourceException(application_ids, "Timed out waiting for nested stack templates " "to reach ACTIVE status.")
[ "def", "on_after_transform_template", "(", "self", ",", "template", ")", ":", "if", "self", ".", "_wait_for_template_active_status", "and", "not", "self", ".", "_validate_only", ":", "start_time", "=", "time", "(", ")", "while", "(", "time", "(", ")", "-", "start_time", ")", "<", "self", ".", "TEMPLATE_WAIT_TIMEOUT_SECONDS", ":", "temp", "=", "self", ".", "_in_progress_templates", "self", ".", "_in_progress_templates", "=", "[", "]", "# Check each resource to make sure it's active", "for", "application_id", ",", "template_id", "in", "temp", ":", "get_cfn_template", "=", "(", "lambda", "application_id", ",", "template_id", ":", "self", ".", "_sar_client", ".", "get_cloud_formation_template", "(", "ApplicationId", "=", "self", ".", "_sanitize_sar_str_param", "(", "application_id", ")", ",", "TemplateId", "=", "self", ".", "_sanitize_sar_str_param", "(", "template_id", ")", ")", ")", "response", "=", "self", ".", "_sar_service_call", "(", "get_cfn_template", ",", "application_id", ",", "application_id", ",", "template_id", ")", "self", ".", "_handle_get_cfn_template_response", "(", "response", ",", "application_id", ",", "template_id", ")", "# Don't sleep if there are no more templates with PREPARING status", "if", "len", "(", "self", ".", "_in_progress_templates", ")", "==", "0", ":", "break", "# Sleep a little so we don't spam service calls", "sleep", "(", "self", ".", "SLEEP_TIME_SECONDS", ")", "# Not all templates reached active status", "if", "len", "(", "self", ".", "_in_progress_templates", ")", "!=", "0", ":", "application_ids", "=", "[", "items", "[", "0", "]", "for", "items", "in", "self", ".", "_in_progress_templates", "]", "raise", "InvalidResourceException", "(", "application_ids", ",", "\"Timed out waiting for nested stack templates \"", "\"to reach ACTIVE status.\"", ")" ]
Hook method that gets called after the template is processed Go through all the stored applications and make sure they're all ACTIVE. :param dict template: Dictionary of the SAM template :return: Nothing
[ "Hook", "method", "that", "gets", "called", "after", "the", "template", "is", "processed" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L263-L298
train
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._handle_get_cfn_template_response
def _handle_get_cfn_template_response(self, response, application_id, template_id): """ Handles the response from the SAR service call :param dict response: the response dictionary from the app repo :param string application_id: the ApplicationId :param string template_id: the unique TemplateId for this application """ status = response['Status'] if status != "ACTIVE": # Other options are PREPARING and EXPIRED. if status == 'EXPIRED': message = ("Template for {} with id {} returned status: {}. Cannot access an expired " "template.".format(application_id, template_id, status)) raise InvalidResourceException(application_id, message) self._in_progress_templates.append((application_id, template_id))
python
def _handle_get_cfn_template_response(self, response, application_id, template_id): """ Handles the response from the SAR service call :param dict response: the response dictionary from the app repo :param string application_id: the ApplicationId :param string template_id: the unique TemplateId for this application """ status = response['Status'] if status != "ACTIVE": # Other options are PREPARING and EXPIRED. if status == 'EXPIRED': message = ("Template for {} with id {} returned status: {}. Cannot access an expired " "template.".format(application_id, template_id, status)) raise InvalidResourceException(application_id, message) self._in_progress_templates.append((application_id, template_id))
[ "def", "_handle_get_cfn_template_response", "(", "self", ",", "response", ",", "application_id", ",", "template_id", ")", ":", "status", "=", "response", "[", "'Status'", "]", "if", "status", "!=", "\"ACTIVE\"", ":", "# Other options are PREPARING and EXPIRED.", "if", "status", "==", "'EXPIRED'", ":", "message", "=", "(", "\"Template for {} with id {} returned status: {}. Cannot access an expired \"", "\"template.\"", ".", "format", "(", "application_id", ",", "template_id", ",", "status", ")", ")", "raise", "InvalidResourceException", "(", "application_id", ",", "message", ")", "self", ".", "_in_progress_templates", ".", "append", "(", "(", "application_id", ",", "template_id", ")", ")" ]
Handles the response from the SAR service call :param dict response: the response dictionary from the app repo :param string application_id: the ApplicationId :param string template_id: the unique TemplateId for this application
[ "Handles", "the", "response", "from", "the", "SAR", "service", "call" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L300-L315
train
awslabs/serverless-application-model
samtranslator/plugins/application/serverless_app_plugin.py
ServerlessAppPlugin._sar_service_call
def _sar_service_call(self, service_call_lambda, logical_id, *args): """ Handles service calls and exception management for service calls to the Serverless Application Repository. :param lambda service_call_lambda: lambda function that contains the service call :param string logical_id: Logical ID of the resource being processed :param list *args: arguments for the service call lambda """ try: response = service_call_lambda(*args) logging.info(response) return response except ClientError as e: error_code = e.response['Error']['Code'] if error_code in ('AccessDeniedException', 'NotFoundException'): raise InvalidResourceException(logical_id, e.response['Error']['Message']) # 'ForbiddenException'- SAR rejects connection logging.exception(e) raise e
python
def _sar_service_call(self, service_call_lambda, logical_id, *args): """ Handles service calls and exception management for service calls to the Serverless Application Repository. :param lambda service_call_lambda: lambda function that contains the service call :param string logical_id: Logical ID of the resource being processed :param list *args: arguments for the service call lambda """ try: response = service_call_lambda(*args) logging.info(response) return response except ClientError as e: error_code = e.response['Error']['Code'] if error_code in ('AccessDeniedException', 'NotFoundException'): raise InvalidResourceException(logical_id, e.response['Error']['Message']) # 'ForbiddenException'- SAR rejects connection logging.exception(e) raise e
[ "def", "_sar_service_call", "(", "self", ",", "service_call_lambda", ",", "logical_id", ",", "*", "args", ")", ":", "try", ":", "response", "=", "service_call_lambda", "(", "*", "args", ")", "logging", ".", "info", "(", "response", ")", "return", "response", "except", "ClientError", "as", "e", ":", "error_code", "=", "e", ".", "response", "[", "'Error'", "]", "[", "'Code'", "]", "if", "error_code", "in", "(", "'AccessDeniedException'", ",", "'NotFoundException'", ")", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "e", ".", "response", "[", "'Error'", "]", "[", "'Message'", "]", ")", "# 'ForbiddenException'- SAR rejects connection", "logging", ".", "exception", "(", "e", ")", "raise", "e" ]
Handles service calls and exception management for service calls to the Serverless Application Repository. :param lambda service_call_lambda: lambda function that contains the service call :param string logical_id: Logical ID of the resource being processed :param list *args: arguments for the service call lambda
[ "Handles", "service", "calls", "and", "exception", "management", "for", "service", "calls", "to", "the", "Serverless", "Application", "Repository", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/plugins/application/serverless_app_plugin.py#L317-L337
train
awslabs/serverless-application-model
samtranslator/parser/parser.py
Parser._validate
def _validate(self, sam_template, parameter_values): """ Validates the template and parameter values and raises exceptions if there's an issue :param dict sam_template: SAM template :param dict parameter_values: Dictionary of parameter values provided by the user """ if parameter_values is None: raise ValueError("`parameter_values` argument is required") if ("Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) or not sam_template["Resources"]): raise InvalidDocumentException( [InvalidTemplateException("'Resources' section is required")]) if (not all(isinstance(sam_resource, dict) for sam_resource in sam_template["Resources"].values())): raise InvalidDocumentException( [InvalidTemplateException( "All 'Resources' must be Objects. If you're using YAML, this may be an " "indentation issue." )]) sam_template_instance = SamTemplate(sam_template) for resource_logical_id, sam_resource in sam_template_instance.iterate(): # NOTE: Properties isn't required for SimpleTable, so we can't check # `not isinstance(sam_resources.get("Properties"), dict)` as this would be a breaking change. # sam_resource.properties defaults to {} in SamTemplate init if (not isinstance(sam_resource.properties, dict)): raise InvalidDocumentException( [InvalidResourceException(resource_logical_id, "All 'Resources' must be Objects and have a 'Properties' Object. If " "you're using YAML, this may be an indentation issue." )]) SamTemplateValidator.validate(sam_template)
python
def _validate(self, sam_template, parameter_values): """ Validates the template and parameter values and raises exceptions if there's an issue :param dict sam_template: SAM template :param dict parameter_values: Dictionary of parameter values provided by the user """ if parameter_values is None: raise ValueError("`parameter_values` argument is required") if ("Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) or not sam_template["Resources"]): raise InvalidDocumentException( [InvalidTemplateException("'Resources' section is required")]) if (not all(isinstance(sam_resource, dict) for sam_resource in sam_template["Resources"].values())): raise InvalidDocumentException( [InvalidTemplateException( "All 'Resources' must be Objects. If you're using YAML, this may be an " "indentation issue." )]) sam_template_instance = SamTemplate(sam_template) for resource_logical_id, sam_resource in sam_template_instance.iterate(): # NOTE: Properties isn't required for SimpleTable, so we can't check # `not isinstance(sam_resources.get("Properties"), dict)` as this would be a breaking change. # sam_resource.properties defaults to {} in SamTemplate init if (not isinstance(sam_resource.properties, dict)): raise InvalidDocumentException( [InvalidResourceException(resource_logical_id, "All 'Resources' must be Objects and have a 'Properties' Object. If " "you're using YAML, this may be an indentation issue." )]) SamTemplateValidator.validate(sam_template)
[ "def", "_validate", "(", "self", ",", "sam_template", ",", "parameter_values", ")", ":", "if", "parameter_values", "is", "None", ":", "raise", "ValueError", "(", "\"`parameter_values` argument is required\"", ")", "if", "(", "\"Resources\"", "not", "in", "sam_template", "or", "not", "isinstance", "(", "sam_template", "[", "\"Resources\"", "]", ",", "dict", ")", "or", "not", "sam_template", "[", "\"Resources\"", "]", ")", ":", "raise", "InvalidDocumentException", "(", "[", "InvalidTemplateException", "(", "\"'Resources' section is required\"", ")", "]", ")", "if", "(", "not", "all", "(", "isinstance", "(", "sam_resource", ",", "dict", ")", "for", "sam_resource", "in", "sam_template", "[", "\"Resources\"", "]", ".", "values", "(", ")", ")", ")", ":", "raise", "InvalidDocumentException", "(", "[", "InvalidTemplateException", "(", "\"All 'Resources' must be Objects. If you're using YAML, this may be an \"", "\"indentation issue.\"", ")", "]", ")", "sam_template_instance", "=", "SamTemplate", "(", "sam_template", ")", "for", "resource_logical_id", ",", "sam_resource", "in", "sam_template_instance", ".", "iterate", "(", ")", ":", "# NOTE: Properties isn't required for SimpleTable, so we can't check", "# `not isinstance(sam_resources.get(\"Properties\"), dict)` as this would be a breaking change.", "# sam_resource.properties defaults to {} in SamTemplate init", "if", "(", "not", "isinstance", "(", "sam_resource", ".", "properties", ",", "dict", ")", ")", ":", "raise", "InvalidDocumentException", "(", "[", "InvalidResourceException", "(", "resource_logical_id", ",", "\"All 'Resources' must be Objects and have a 'Properties' Object. If \"", "\"you're using YAML, this may be an indentation issue.\"", ")", "]", ")", "SamTemplateValidator", ".", "validate", "(", "sam_template", ")" ]
Validates the template and parameter values and raises exceptions if there's an issue :param dict sam_template: SAM template :param dict parameter_values: Dictionary of parameter values provided by the user
[ "Validates", "the", "template", "and", "parameter", "values", "and", "raises", "exceptions", "if", "there", "s", "an", "issue" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/parser/parser.py#L16-L50
train
awslabs/serverless-application-model
samtranslator/sdk/template.py
SamTemplate.iterate
def iterate(self, resource_type=None): """ Iterate over all resources within the SAM template, optionally filtering by type :param string resource_type: Optional type to filter the resources by :yields (string, SamResource): Tuple containing LogicalId and the resource """ for logicalId, resource_dict in self.resources.items(): resource = SamResource(resource_dict) needs_filter = resource.valid() if resource_type: needs_filter = needs_filter and resource.type == resource_type if needs_filter: yield logicalId, resource
python
def iterate(self, resource_type=None): """ Iterate over all resources within the SAM template, optionally filtering by type :param string resource_type: Optional type to filter the resources by :yields (string, SamResource): Tuple containing LogicalId and the resource """ for logicalId, resource_dict in self.resources.items(): resource = SamResource(resource_dict) needs_filter = resource.valid() if resource_type: needs_filter = needs_filter and resource.type == resource_type if needs_filter: yield logicalId, resource
[ "def", "iterate", "(", "self", ",", "resource_type", "=", "None", ")", ":", "for", "logicalId", ",", "resource_dict", "in", "self", ".", "resources", ".", "items", "(", ")", ":", "resource", "=", "SamResource", "(", "resource_dict", ")", "needs_filter", "=", "resource", ".", "valid", "(", ")", "if", "resource_type", ":", "needs_filter", "=", "needs_filter", "and", "resource", ".", "type", "==", "resource_type", "if", "needs_filter", ":", "yield", "logicalId", ",", "resource" ]
Iterate over all resources within the SAM template, optionally filtering by type :param string resource_type: Optional type to filter the resources by :yields (string, SamResource): Tuple containing LogicalId and the resource
[ "Iterate", "over", "all", "resources", "within", "the", "SAM", "template", "optionally", "filtering", "by", "type" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/template.py#L22-L38
train
awslabs/serverless-application-model
samtranslator/sdk/template.py
SamTemplate.set
def set(self, logicalId, resource): """ Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used. :param string logicalId: Logical Id to set to :param SamResource or dict resource: The actual resource data """ resource_dict = resource if isinstance(resource, SamResource): resource_dict = resource.to_dict() self.resources[logicalId] = resource_dict
python
def set(self, logicalId, resource): """ Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used. :param string logicalId: Logical Id to set to :param SamResource or dict resource: The actual resource data """ resource_dict = resource if isinstance(resource, SamResource): resource_dict = resource.to_dict() self.resources[logicalId] = resource_dict
[ "def", "set", "(", "self", ",", "logicalId", ",", "resource", ")", ":", "resource_dict", "=", "resource", "if", "isinstance", "(", "resource", ",", "SamResource", ")", ":", "resource_dict", "=", "resource", ".", "to_dict", "(", ")", "self", ".", "resources", "[", "logicalId", "]", "=", "resource_dict" ]
Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used. :param string logicalId: Logical Id to set to :param SamResource or dict resource: The actual resource data
[ "Adds", "the", "resource", "to", "dictionary", "with", "given", "logical", "Id", ".", "It", "will", "overwrite", "if", "the", "logicalId", "is", "already", "used", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/template.py#L40-L52
train
awslabs/serverless-application-model
samtranslator/sdk/template.py
SamTemplate.get
def get(self, logicalId): """ Gets the resource at the given logicalId if present :param string logicalId: Id of the resource :return SamResource: Resource, if available at the Id. None, otherwise """ if logicalId not in self.resources: return None return SamResource(self.resources.get(logicalId))
python
def get(self, logicalId): """ Gets the resource at the given logicalId if present :param string logicalId: Id of the resource :return SamResource: Resource, if available at the Id. None, otherwise """ if logicalId not in self.resources: return None return SamResource(self.resources.get(logicalId))
[ "def", "get", "(", "self", ",", "logicalId", ")", ":", "if", "logicalId", "not", "in", "self", ".", "resources", ":", "return", "None", "return", "SamResource", "(", "self", ".", "resources", ".", "get", "(", "logicalId", ")", ")" ]
Gets the resource at the given logicalId if present :param string logicalId: Id of the resource :return SamResource: Resource, if available at the Id. None, otherwise
[ "Gets", "the", "resource", "at", "the", "given", "logicalId", "if", "present" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/template.py#L54-L64
train
awslabs/serverless-application-model
samtranslator/translator/translator.py
prepare_plugins
def prepare_plugins(plugins, parameters={}): """ Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins, we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec. :param plugins: list of samtranslator.plugins.BasePlugin plugins: List of plugins to install :param parameters: Dictionary of parameter values :return samtranslator.plugins.SamPlugins: Instance of `SamPlugins` """ required_plugins = [ DefaultDefinitionBodyPlugin(), make_implicit_api_plugin(), GlobalsPlugin(), make_policy_template_for_function_plugin(), ] plugins = [] if not plugins else plugins # If a ServerlessAppPlugin does not yet exist, create one and add to the beginning of the required plugins list. if not any(isinstance(plugin, ServerlessAppPlugin) for plugin in plugins): required_plugins.insert(0, ServerlessAppPlugin(parameters=parameters)) # Execute customer's plugins first before running SAM plugins. It is very important to retain this order because # other plugins will be dependent on this ordering. return SamPlugins(plugins + required_plugins)
python
def prepare_plugins(plugins, parameters={}): """ Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins, we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec. :param plugins: list of samtranslator.plugins.BasePlugin plugins: List of plugins to install :param parameters: Dictionary of parameter values :return samtranslator.plugins.SamPlugins: Instance of `SamPlugins` """ required_plugins = [ DefaultDefinitionBodyPlugin(), make_implicit_api_plugin(), GlobalsPlugin(), make_policy_template_for_function_plugin(), ] plugins = [] if not plugins else plugins # If a ServerlessAppPlugin does not yet exist, create one and add to the beginning of the required plugins list. if not any(isinstance(plugin, ServerlessAppPlugin) for plugin in plugins): required_plugins.insert(0, ServerlessAppPlugin(parameters=parameters)) # Execute customer's plugins first before running SAM plugins. It is very important to retain this order because # other plugins will be dependent on this ordering. return SamPlugins(plugins + required_plugins)
[ "def", "prepare_plugins", "(", "plugins", ",", "parameters", "=", "{", "}", ")", ":", "required_plugins", "=", "[", "DefaultDefinitionBodyPlugin", "(", ")", ",", "make_implicit_api_plugin", "(", ")", ",", "GlobalsPlugin", "(", ")", ",", "make_policy_template_for_function_plugin", "(", ")", ",", "]", "plugins", "=", "[", "]", "if", "not", "plugins", "else", "plugins", "# If a ServerlessAppPlugin does not yet exist, create one and add to the beginning of the required plugins list.", "if", "not", "any", "(", "isinstance", "(", "plugin", ",", "ServerlessAppPlugin", ")", "for", "plugin", "in", "plugins", ")", ":", "required_plugins", ".", "insert", "(", "0", ",", "ServerlessAppPlugin", "(", "parameters", "=", "parameters", ")", ")", "# Execute customer's plugins first before running SAM plugins. It is very important to retain this order because", "# other plugins will be dependent on this ordering.", "return", "SamPlugins", "(", "plugins", "+", "required_plugins", ")" ]
Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins, we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec. :param plugins: list of samtranslator.plugins.BasePlugin plugins: List of plugins to install :param parameters: Dictionary of parameter values :return samtranslator.plugins.SamPlugins: Instance of `SamPlugins`
[ "Creates", "&", "returns", "a", "plugins", "object", "with", "the", "given", "list", "of", "plugins", "installed", ".", "In", "addition", "to", "the", "given", "plugins", "we", "will", "also", "install", "a", "few", "required", "plugins", "that", "are", "necessary", "to", "provide", "complete", "support", "for", "SAM", "template", "spec", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/translator.py#L163-L188
train
awslabs/serverless-application-model
samtranslator/translator/translator.py
Translator.translate
def translate(self, sam_template, parameter_values): """Loads the SAM resources from the given SAM manifest, replaces them with their corresponding CloudFormation resources, and returns the resulting CloudFormation template. :param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \ CloudFormation transforms. :param dict parameter_values: Map of template parameter names to their values. It is a required parameter that should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea that some functionality that relies on resolving parameter references might not work as expected (ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is why this parameter is required :returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \ be dumped into a valid CloudFormation JSON or YAML template """ sam_parameter_values = SamParameterValues(parameter_values) sam_parameter_values.add_default_parameter_values(sam_template) sam_parameter_values.add_pseudo_parameter_values() parameter_values = sam_parameter_values.parameter_values # Create & Install plugins sam_plugins = prepare_plugins(self.plugins, parameter_values) self.sam_parser.parse( sam_template=sam_template, parameter_values=parameter_values, sam_plugins=sam_plugins ) template = copy.deepcopy(sam_template) macro_resolver = ResourceTypeResolver(sam_resources) intrinsics_resolver = IntrinsicsResolver(parameter_values) deployment_preference_collection = DeploymentPreferenceCollection() supported_resource_refs = SupportedResourceReferences() document_errors = [] changed_logical_ids = {} for logical_id, resource_dict in self._get_resources_to_iterate(sam_template, macro_resolver): try: macro = macro_resolver\ .resolve_resource_type(resource_dict)\ .from_dict(logical_id, resource_dict, sam_plugins=sam_plugins) kwargs = macro.resources_to_link(sam_template['Resources']) kwargs['managed_policy_map'] = self.managed_policy_map kwargs['intrinsics_resolver'] = intrinsics_resolver kwargs['deployment_preference_collection'] = deployment_preference_collection translated = macro.to_cloudformation(**kwargs) supported_resource_refs = macro.get_resource_references(translated, supported_resource_refs) # Some resources mutate their logical ids. Track those to change all references to them: if logical_id != macro.logical_id: changed_logical_ids[logical_id] = macro.logical_id del template['Resources'][logical_id] for resource in translated: if verify_unique_logical_id(resource, sam_template['Resources']): template['Resources'].update(resource.to_dict()) else: document_errors.append(DuplicateLogicalIdException( logical_id, resource.logical_id, resource.resource_type)) except (InvalidResourceException, InvalidEventException) as e: document_errors.append(e) if deployment_preference_collection.any_enabled(): template['Resources'].update(deployment_preference_collection.codedeploy_application.to_dict()) if not deployment_preference_collection.can_skip_service_role(): template['Resources'].update(deployment_preference_collection.codedeploy_iam_role.to_dict()) for logical_id in deployment_preference_collection.enabled_logical_ids(): template['Resources'].update(deployment_preference_collection.deployment_group(logical_id).to_dict()) # Run the after-transform plugin target try: sam_plugins.act(LifeCycleEvents.after_transform_template, template) except (InvalidDocumentException, InvalidResourceException) as e: document_errors.append(e) # Cleanup if 'Transform' in template: del template['Transform'] if len(document_errors) == 0: template = intrinsics_resolver.resolve_sam_resource_id_refs(template, changed_logical_ids) template = intrinsics_resolver.resolve_sam_resource_refs(template, supported_resource_refs) return template else: raise InvalidDocumentException(document_errors)
python
def translate(self, sam_template, parameter_values): """Loads the SAM resources from the given SAM manifest, replaces them with their corresponding CloudFormation resources, and returns the resulting CloudFormation template. :param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \ CloudFormation transforms. :param dict parameter_values: Map of template parameter names to their values. It is a required parameter that should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea that some functionality that relies on resolving parameter references might not work as expected (ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is why this parameter is required :returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \ be dumped into a valid CloudFormation JSON or YAML template """ sam_parameter_values = SamParameterValues(parameter_values) sam_parameter_values.add_default_parameter_values(sam_template) sam_parameter_values.add_pseudo_parameter_values() parameter_values = sam_parameter_values.parameter_values # Create & Install plugins sam_plugins = prepare_plugins(self.plugins, parameter_values) self.sam_parser.parse( sam_template=sam_template, parameter_values=parameter_values, sam_plugins=sam_plugins ) template = copy.deepcopy(sam_template) macro_resolver = ResourceTypeResolver(sam_resources) intrinsics_resolver = IntrinsicsResolver(parameter_values) deployment_preference_collection = DeploymentPreferenceCollection() supported_resource_refs = SupportedResourceReferences() document_errors = [] changed_logical_ids = {} for logical_id, resource_dict in self._get_resources_to_iterate(sam_template, macro_resolver): try: macro = macro_resolver\ .resolve_resource_type(resource_dict)\ .from_dict(logical_id, resource_dict, sam_plugins=sam_plugins) kwargs = macro.resources_to_link(sam_template['Resources']) kwargs['managed_policy_map'] = self.managed_policy_map kwargs['intrinsics_resolver'] = intrinsics_resolver kwargs['deployment_preference_collection'] = deployment_preference_collection translated = macro.to_cloudformation(**kwargs) supported_resource_refs = macro.get_resource_references(translated, supported_resource_refs) # Some resources mutate their logical ids. Track those to change all references to them: if logical_id != macro.logical_id: changed_logical_ids[logical_id] = macro.logical_id del template['Resources'][logical_id] for resource in translated: if verify_unique_logical_id(resource, sam_template['Resources']): template['Resources'].update(resource.to_dict()) else: document_errors.append(DuplicateLogicalIdException( logical_id, resource.logical_id, resource.resource_type)) except (InvalidResourceException, InvalidEventException) as e: document_errors.append(e) if deployment_preference_collection.any_enabled(): template['Resources'].update(deployment_preference_collection.codedeploy_application.to_dict()) if not deployment_preference_collection.can_skip_service_role(): template['Resources'].update(deployment_preference_collection.codedeploy_iam_role.to_dict()) for logical_id in deployment_preference_collection.enabled_logical_ids(): template['Resources'].update(deployment_preference_collection.deployment_group(logical_id).to_dict()) # Run the after-transform plugin target try: sam_plugins.act(LifeCycleEvents.after_transform_template, template) except (InvalidDocumentException, InvalidResourceException) as e: document_errors.append(e) # Cleanup if 'Transform' in template: del template['Transform'] if len(document_errors) == 0: template = intrinsics_resolver.resolve_sam_resource_id_refs(template, changed_logical_ids) template = intrinsics_resolver.resolve_sam_resource_refs(template, supported_resource_refs) return template else: raise InvalidDocumentException(document_errors)
[ "def", "translate", "(", "self", ",", "sam_template", ",", "parameter_values", ")", ":", "sam_parameter_values", "=", "SamParameterValues", "(", "parameter_values", ")", "sam_parameter_values", ".", "add_default_parameter_values", "(", "sam_template", ")", "sam_parameter_values", ".", "add_pseudo_parameter_values", "(", ")", "parameter_values", "=", "sam_parameter_values", ".", "parameter_values", "# Create & Install plugins", "sam_plugins", "=", "prepare_plugins", "(", "self", ".", "plugins", ",", "parameter_values", ")", "self", ".", "sam_parser", ".", "parse", "(", "sam_template", "=", "sam_template", ",", "parameter_values", "=", "parameter_values", ",", "sam_plugins", "=", "sam_plugins", ")", "template", "=", "copy", ".", "deepcopy", "(", "sam_template", ")", "macro_resolver", "=", "ResourceTypeResolver", "(", "sam_resources", ")", "intrinsics_resolver", "=", "IntrinsicsResolver", "(", "parameter_values", ")", "deployment_preference_collection", "=", "DeploymentPreferenceCollection", "(", ")", "supported_resource_refs", "=", "SupportedResourceReferences", "(", ")", "document_errors", "=", "[", "]", "changed_logical_ids", "=", "{", "}", "for", "logical_id", ",", "resource_dict", "in", "self", ".", "_get_resources_to_iterate", "(", "sam_template", ",", "macro_resolver", ")", ":", "try", ":", "macro", "=", "macro_resolver", ".", "resolve_resource_type", "(", "resource_dict", ")", ".", "from_dict", "(", "logical_id", ",", "resource_dict", ",", "sam_plugins", "=", "sam_plugins", ")", "kwargs", "=", "macro", ".", "resources_to_link", "(", "sam_template", "[", "'Resources'", "]", ")", "kwargs", "[", "'managed_policy_map'", "]", "=", "self", ".", "managed_policy_map", "kwargs", "[", "'intrinsics_resolver'", "]", "=", "intrinsics_resolver", "kwargs", "[", "'deployment_preference_collection'", "]", "=", "deployment_preference_collection", "translated", "=", "macro", ".", "to_cloudformation", "(", "*", "*", "kwargs", ")", "supported_resource_refs", "=", "macro", ".", "get_resource_references", "(", "translated", ",", "supported_resource_refs", ")", "# Some resources mutate their logical ids. Track those to change all references to them:", "if", "logical_id", "!=", "macro", ".", "logical_id", ":", "changed_logical_ids", "[", "logical_id", "]", "=", "macro", ".", "logical_id", "del", "template", "[", "'Resources'", "]", "[", "logical_id", "]", "for", "resource", "in", "translated", ":", "if", "verify_unique_logical_id", "(", "resource", ",", "sam_template", "[", "'Resources'", "]", ")", ":", "template", "[", "'Resources'", "]", ".", "update", "(", "resource", ".", "to_dict", "(", ")", ")", "else", ":", "document_errors", ".", "append", "(", "DuplicateLogicalIdException", "(", "logical_id", ",", "resource", ".", "logical_id", ",", "resource", ".", "resource_type", ")", ")", "except", "(", "InvalidResourceException", ",", "InvalidEventException", ")", "as", "e", ":", "document_errors", ".", "append", "(", "e", ")", "if", "deployment_preference_collection", ".", "any_enabled", "(", ")", ":", "template", "[", "'Resources'", "]", ".", "update", "(", "deployment_preference_collection", ".", "codedeploy_application", ".", "to_dict", "(", ")", ")", "if", "not", "deployment_preference_collection", ".", "can_skip_service_role", "(", ")", ":", "template", "[", "'Resources'", "]", ".", "update", "(", "deployment_preference_collection", ".", "codedeploy_iam_role", ".", "to_dict", "(", ")", ")", "for", "logical_id", "in", "deployment_preference_collection", ".", "enabled_logical_ids", "(", ")", ":", "template", "[", "'Resources'", "]", ".", "update", "(", "deployment_preference_collection", ".", "deployment_group", "(", "logical_id", ")", ".", "to_dict", "(", ")", ")", "# Run the after-transform plugin target", "try", ":", "sam_plugins", ".", "act", "(", "LifeCycleEvents", ".", "after_transform_template", ",", "template", ")", "except", "(", "InvalidDocumentException", ",", "InvalidResourceException", ")", "as", "e", ":", "document_errors", ".", "append", "(", "e", ")", "# Cleanup", "if", "'Transform'", "in", "template", ":", "del", "template", "[", "'Transform'", "]", "if", "len", "(", "document_errors", ")", "==", "0", ":", "template", "=", "intrinsics_resolver", ".", "resolve_sam_resource_id_refs", "(", "template", ",", "changed_logical_ids", ")", "template", "=", "intrinsics_resolver", ".", "resolve_sam_resource_refs", "(", "template", ",", "supported_resource_refs", ")", "return", "template", "else", ":", "raise", "InvalidDocumentException", "(", "document_errors", ")" ]
Loads the SAM resources from the given SAM manifest, replaces them with their corresponding CloudFormation resources, and returns the resulting CloudFormation template. :param dict sam_template: the SAM manifest, as loaded by json.load() or yaml.load(), or as provided by \ CloudFormation transforms. :param dict parameter_values: Map of template parameter names to their values. It is a required parameter that should at least be an empty map. By providing an empty map, the caller explicitly opts-into the idea that some functionality that relies on resolving parameter references might not work as expected (ex: auto-creating new Lambda Version when CodeUri contains reference to template parameter). This is why this parameter is required :returns: a copy of the template with SAM resources replaced with the corresponding CloudFormation, which may \ be dumped into a valid CloudFormation JSON or YAML template
[ "Loads", "the", "SAM", "resources", "from", "the", "given", "SAM", "manifest", "replaces", "them", "with", "their", "corresponding", "CloudFormation", "resources", "and", "returns", "the", "resulting", "CloudFormation", "template", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/translator.py#L34-L122
train
awslabs/serverless-application-model
samtranslator/translator/translator.py
Translator._get_resources_to_iterate
def _get_resources_to_iterate(self, sam_template, macro_resolver): """ Returns a list of resources to iterate, order them based on the following order: 1. AWS::Serverless::Function - because API Events need to modify the corresponding Serverless::Api resource. 2. AWS::Serverless::Api 3. Anything else This is necessary because a Function resource with API Events will modify the API resource's Swagger JSON. Therefore API resource needs to be parsed only after all the Swagger modifications are complete. :param dict sam_template: SAM template :param macro_resolver: Resolver that knows if a resource can be processed or not :return list: List containing tuple of (logicalId, resource_dict) in the order of processing """ functions = [] apis = [] others = [] resources = sam_template["Resources"] for logicalId, resource in resources.items(): data = (logicalId, resource) # Skip over the resource if it is not a SAM defined Resource if not macro_resolver.can_resolve(resource): continue elif resource["Type"] == "AWS::Serverless::Function": functions.append(data) elif resource["Type"] == "AWS::Serverless::Api": apis.append(data) else: others.append(data) return functions + apis + others
python
def _get_resources_to_iterate(self, sam_template, macro_resolver): """ Returns a list of resources to iterate, order them based on the following order: 1. AWS::Serverless::Function - because API Events need to modify the corresponding Serverless::Api resource. 2. AWS::Serverless::Api 3. Anything else This is necessary because a Function resource with API Events will modify the API resource's Swagger JSON. Therefore API resource needs to be parsed only after all the Swagger modifications are complete. :param dict sam_template: SAM template :param macro_resolver: Resolver that knows if a resource can be processed or not :return list: List containing tuple of (logicalId, resource_dict) in the order of processing """ functions = [] apis = [] others = [] resources = sam_template["Resources"] for logicalId, resource in resources.items(): data = (logicalId, resource) # Skip over the resource if it is not a SAM defined Resource if not macro_resolver.can_resolve(resource): continue elif resource["Type"] == "AWS::Serverless::Function": functions.append(data) elif resource["Type"] == "AWS::Serverless::Api": apis.append(data) else: others.append(data) return functions + apis + others
[ "def", "_get_resources_to_iterate", "(", "self", ",", "sam_template", ",", "macro_resolver", ")", ":", "functions", "=", "[", "]", "apis", "=", "[", "]", "others", "=", "[", "]", "resources", "=", "sam_template", "[", "\"Resources\"", "]", "for", "logicalId", ",", "resource", "in", "resources", ".", "items", "(", ")", ":", "data", "=", "(", "logicalId", ",", "resource", ")", "# Skip over the resource if it is not a SAM defined Resource", "if", "not", "macro_resolver", ".", "can_resolve", "(", "resource", ")", ":", "continue", "elif", "resource", "[", "\"Type\"", "]", "==", "\"AWS::Serverless::Function\"", ":", "functions", ".", "append", "(", "data", ")", "elif", "resource", "[", "\"Type\"", "]", "==", "\"AWS::Serverless::Api\"", ":", "apis", ".", "append", "(", "data", ")", "else", ":", "others", ".", "append", "(", "data", ")", "return", "functions", "+", "apis", "+", "others" ]
Returns a list of resources to iterate, order them based on the following order: 1. AWS::Serverless::Function - because API Events need to modify the corresponding Serverless::Api resource. 2. AWS::Serverless::Api 3. Anything else This is necessary because a Function resource with API Events will modify the API resource's Swagger JSON. Therefore API resource needs to be parsed only after all the Swagger modifications are complete. :param dict sam_template: SAM template :param macro_resolver: Resolver that knows if a resource can be processed or not :return list: List containing tuple of (logicalId, resource_dict) in the order of processing
[ "Returns", "a", "list", "of", "resources", "to", "iterate", "order", "them", "based", "on", "the", "following", "order", ":" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/translator/translator.py#L125-L160
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource.from_dict
def from_dict(cls, logical_id, resource_dict, relative_id=None, sam_plugins=None): """Constructs a Resource object with the given logical id, based on the given resource dict. The resource dict is the value associated with the logical id in a CloudFormation template's Resources section, and takes the following format. :: { "Type": "<resource type>", "Properties": { <set of properties> } } :param str logical_id: The logical id of this Resource :param dict resource_dict: The value associated with this logical id in the CloudFormation template, a mapping \ containing the resource's Type and Properties. :param str relative_id: The logical id of this resource relative to the logical_id. This is useful to identify sub-resources. :param samtranslator.plugins.SamPlugins sam_plugins: Optional plugins object to help enhance functionality of translator :returns: a Resource object populated from the provided parameters :rtype: Resource :raises TypeError: if the provided parameters are invalid """ resource = cls(logical_id, relative_id=relative_id) resource._validate_resource_dict(logical_id, resource_dict) # Default to empty properties dictionary. If customers skip the Properties section, an empty dictionary # accurately captures the intent. properties = resource_dict.get("Properties", {}) if sam_plugins: sam_plugins.act(LifeCycleEvents.before_transform_resource, logical_id, cls.resource_type, properties) for name, value in properties.items(): setattr(resource, name, value) if 'DependsOn' in resource_dict: resource.depends_on = resource_dict['DependsOn'] # Parse only well known properties. This is consistent with earlier behavior where we used to ignore resource # all resource attributes ie. all attributes were unsupported before for attr in resource._supported_resource_attributes: if attr in resource_dict: resource.set_resource_attribute(attr, resource_dict[attr]) resource.validate_properties() return resource
python
def from_dict(cls, logical_id, resource_dict, relative_id=None, sam_plugins=None): """Constructs a Resource object with the given logical id, based on the given resource dict. The resource dict is the value associated with the logical id in a CloudFormation template's Resources section, and takes the following format. :: { "Type": "<resource type>", "Properties": { <set of properties> } } :param str logical_id: The logical id of this Resource :param dict resource_dict: The value associated with this logical id in the CloudFormation template, a mapping \ containing the resource's Type and Properties. :param str relative_id: The logical id of this resource relative to the logical_id. This is useful to identify sub-resources. :param samtranslator.plugins.SamPlugins sam_plugins: Optional plugins object to help enhance functionality of translator :returns: a Resource object populated from the provided parameters :rtype: Resource :raises TypeError: if the provided parameters are invalid """ resource = cls(logical_id, relative_id=relative_id) resource._validate_resource_dict(logical_id, resource_dict) # Default to empty properties dictionary. If customers skip the Properties section, an empty dictionary # accurately captures the intent. properties = resource_dict.get("Properties", {}) if sam_plugins: sam_plugins.act(LifeCycleEvents.before_transform_resource, logical_id, cls.resource_type, properties) for name, value in properties.items(): setattr(resource, name, value) if 'DependsOn' in resource_dict: resource.depends_on = resource_dict['DependsOn'] # Parse only well known properties. This is consistent with earlier behavior where we used to ignore resource # all resource attributes ie. all attributes were unsupported before for attr in resource._supported_resource_attributes: if attr in resource_dict: resource.set_resource_attribute(attr, resource_dict[attr]) resource.validate_properties() return resource
[ "def", "from_dict", "(", "cls", ",", "logical_id", ",", "resource_dict", ",", "relative_id", "=", "None", ",", "sam_plugins", "=", "None", ")", ":", "resource", "=", "cls", "(", "logical_id", ",", "relative_id", "=", "relative_id", ")", "resource", ".", "_validate_resource_dict", "(", "logical_id", ",", "resource_dict", ")", "# Default to empty properties dictionary. If customers skip the Properties section, an empty dictionary", "# accurately captures the intent.", "properties", "=", "resource_dict", ".", "get", "(", "\"Properties\"", ",", "{", "}", ")", "if", "sam_plugins", ":", "sam_plugins", ".", "act", "(", "LifeCycleEvents", ".", "before_transform_resource", ",", "logical_id", ",", "cls", ".", "resource_type", ",", "properties", ")", "for", "name", ",", "value", "in", "properties", ".", "items", "(", ")", ":", "setattr", "(", "resource", ",", "name", ",", "value", ")", "if", "'DependsOn'", "in", "resource_dict", ":", "resource", ".", "depends_on", "=", "resource_dict", "[", "'DependsOn'", "]", "# Parse only well known properties. This is consistent with earlier behavior where we used to ignore resource", "# all resource attributes ie. all attributes were unsupported before", "for", "attr", "in", "resource", ".", "_supported_resource_attributes", ":", "if", "attr", "in", "resource_dict", ":", "resource", ".", "set_resource_attribute", "(", "attr", ",", "resource_dict", "[", "attr", "]", ")", "resource", ".", "validate_properties", "(", ")", "return", "resource" ]
Constructs a Resource object with the given logical id, based on the given resource dict. The resource dict is the value associated with the logical id in a CloudFormation template's Resources section, and takes the following format. :: { "Type": "<resource type>", "Properties": { <set of properties> } } :param str logical_id: The logical id of this Resource :param dict resource_dict: The value associated with this logical id in the CloudFormation template, a mapping \ containing the resource's Type and Properties. :param str relative_id: The logical id of this resource relative to the logical_id. This is useful to identify sub-resources. :param samtranslator.plugins.SamPlugins sam_plugins: Optional plugins object to help enhance functionality of translator :returns: a Resource object populated from the provided parameters :rtype: Resource :raises TypeError: if the provided parameters are invalid
[ "Constructs", "a", "Resource", "object", "with", "the", "given", "logical", "id", "based", "on", "the", "given", "resource", "dict", ".", "The", "resource", "dict", "is", "the", "value", "associated", "with", "the", "logical", "id", "in", "a", "CloudFormation", "template", "s", "Resources", "section", "and", "takes", "the", "following", "format", ".", "::" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L78-L126
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource._validate_logical_id
def _validate_logical_id(cls, logical_id): """Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid """ pattern = re.compile(r'^[A-Za-z0-9]+$') if logical_id is not None and pattern.match(logical_id): return True raise InvalidResourceException(logical_id, "Logical ids must be alphanumeric.")
python
def _validate_logical_id(cls, logical_id): """Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid """ pattern = re.compile(r'^[A-Za-z0-9]+$') if logical_id is not None and pattern.match(logical_id): return True raise InvalidResourceException(logical_id, "Logical ids must be alphanumeric.")
[ "def", "_validate_logical_id", "(", "cls", ",", "logical_id", ")", ":", "pattern", "=", "re", ".", "compile", "(", "r'^[A-Za-z0-9]+$'", ")", "if", "logical_id", "is", "not", "None", "and", "pattern", ".", "match", "(", "logical_id", ")", ":", "return", "True", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Logical ids must be alphanumeric.\"", ")" ]
Validates that the provided logical id is an alphanumeric string. :param str logical_id: the logical id to validate :returns: True if the logical id is valid :rtype: bool :raises TypeError: if the logical id is invalid
[ "Validates", "that", "the", "provided", "logical", "id", "is", "an", "alphanumeric", "string", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L129-L140
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource._validate_resource_dict
def _validate_resource_dict(cls, logical_id, resource_dict): """Validates that the provided resource dict contains the correct Type string, and the required Properties dict. :param dict resource_dict: the resource dict to validate :returns: True if the resource dict has the expected format :rtype: bool :raises InvalidResourceException: if the resource dict has an invalid format """ if 'Type' not in resource_dict: raise InvalidResourceException(logical_id, "Resource dict missing key 'Type'.") if resource_dict['Type'] != cls.resource_type: raise InvalidResourceException(logical_id, "Resource has incorrect Type; expected '{expected}', " "got '{actual}'".format( expected=cls.resource_type, actual=resource_dict['Type'])) if 'Properties' in resource_dict and not isinstance(resource_dict['Properties'], dict): raise InvalidResourceException(logical_id, "Properties of a resource must be an object.")
python
def _validate_resource_dict(cls, logical_id, resource_dict): """Validates that the provided resource dict contains the correct Type string, and the required Properties dict. :param dict resource_dict: the resource dict to validate :returns: True if the resource dict has the expected format :rtype: bool :raises InvalidResourceException: if the resource dict has an invalid format """ if 'Type' not in resource_dict: raise InvalidResourceException(logical_id, "Resource dict missing key 'Type'.") if resource_dict['Type'] != cls.resource_type: raise InvalidResourceException(logical_id, "Resource has incorrect Type; expected '{expected}', " "got '{actual}'".format( expected=cls.resource_type, actual=resource_dict['Type'])) if 'Properties' in resource_dict and not isinstance(resource_dict['Properties'], dict): raise InvalidResourceException(logical_id, "Properties of a resource must be an object.")
[ "def", "_validate_resource_dict", "(", "cls", ",", "logical_id", ",", "resource_dict", ")", ":", "if", "'Type'", "not", "in", "resource_dict", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Resource dict missing key 'Type'.\"", ")", "if", "resource_dict", "[", "'Type'", "]", "!=", "cls", ".", "resource_type", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Resource has incorrect Type; expected '{expected}', \"", "\"got '{actual}'\"", ".", "format", "(", "expected", "=", "cls", ".", "resource_type", ",", "actual", "=", "resource_dict", "[", "'Type'", "]", ")", ")", "if", "'Properties'", "in", "resource_dict", "and", "not", "isinstance", "(", "resource_dict", "[", "'Properties'", "]", ",", "dict", ")", ":", "raise", "InvalidResourceException", "(", "logical_id", ",", "\"Properties of a resource must be an object.\"", ")" ]
Validates that the provided resource dict contains the correct Type string, and the required Properties dict. :param dict resource_dict: the resource dict to validate :returns: True if the resource dict has the expected format :rtype: bool :raises InvalidResourceException: if the resource dict has an invalid format
[ "Validates", "that", "the", "provided", "resource", "dict", "contains", "the", "correct", "Type", "string", "and", "the", "required", "Properties", "dict", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L143-L160
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource.to_dict
def to_dict(self): """Validates that the required properties for this Resource have been provided, then returns a dict corresponding to the given Resource object. This dict will take the format of a single entry in the Resources section of a CloudFormation template, and will take the following format. :: { "<logical id>": { "Type": "<resource type>", "DependsOn": "<value specified by user>", "Properties": { <set of properties> } } } The resulting dict can then be serialized to JSON or YAML and included as part of a CloudFormation template. :returns: a dict corresponding to this Resource's entry in a CloudFormation template :rtype: dict :raises TypeError: if a required property is missing from this Resource """ self.validate_properties() resource_dict = self._generate_resource_dict() return {self.logical_id: resource_dict}
python
def to_dict(self): """Validates that the required properties for this Resource have been provided, then returns a dict corresponding to the given Resource object. This dict will take the format of a single entry in the Resources section of a CloudFormation template, and will take the following format. :: { "<logical id>": { "Type": "<resource type>", "DependsOn": "<value specified by user>", "Properties": { <set of properties> } } } The resulting dict can then be serialized to JSON or YAML and included as part of a CloudFormation template. :returns: a dict corresponding to this Resource's entry in a CloudFormation template :rtype: dict :raises TypeError: if a required property is missing from this Resource """ self.validate_properties() resource_dict = self._generate_resource_dict() return {self.logical_id: resource_dict}
[ "def", "to_dict", "(", "self", ")", ":", "self", ".", "validate_properties", "(", ")", "resource_dict", "=", "self", ".", "_generate_resource_dict", "(", ")", "return", "{", "self", ".", "logical_id", ":", "resource_dict", "}" ]
Validates that the required properties for this Resource have been provided, then returns a dict corresponding to the given Resource object. This dict will take the format of a single entry in the Resources section of a CloudFormation template, and will take the following format. :: { "<logical id>": { "Type": "<resource type>", "DependsOn": "<value specified by user>", "Properties": { <set of properties> } } } The resulting dict can then be serialized to JSON or YAML and included as part of a CloudFormation template. :returns: a dict corresponding to this Resource's entry in a CloudFormation template :rtype: dict :raises TypeError: if a required property is missing from this Resource
[ "Validates", "that", "the", "required", "properties", "for", "this", "Resource", "have", "been", "provided", "then", "returns", "a", "dict", "corresponding", "to", "the", "given", "Resource", "object", ".", "This", "dict", "will", "take", "the", "format", "of", "a", "single", "entry", "in", "the", "Resources", "section", "of", "a", "CloudFormation", "template", "and", "will", "take", "the", "following", "format", ".", "::" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L162-L187
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource._generate_resource_dict
def _generate_resource_dict(self): """Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation template's Resources section. :returns: the resource dict for this Resource :rtype: dict """ resource_dict = {} resource_dict['Type'] = self.resource_type if self.depends_on: resource_dict['DependsOn'] = self.depends_on resource_dict.update(self.resource_attributes) properties_dict = {} for name in self.property_types: value = getattr(self, name) if value is not None: properties_dict[name] = value resource_dict['Properties'] = properties_dict return resource_dict
python
def _generate_resource_dict(self): """Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation template's Resources section. :returns: the resource dict for this Resource :rtype: dict """ resource_dict = {} resource_dict['Type'] = self.resource_type if self.depends_on: resource_dict['DependsOn'] = self.depends_on resource_dict.update(self.resource_attributes) properties_dict = {} for name in self.property_types: value = getattr(self, name) if value is not None: properties_dict[name] = value resource_dict['Properties'] = properties_dict return resource_dict
[ "def", "_generate_resource_dict", "(", "self", ")", ":", "resource_dict", "=", "{", "}", "resource_dict", "[", "'Type'", "]", "=", "self", ".", "resource_type", "if", "self", ".", "depends_on", ":", "resource_dict", "[", "'DependsOn'", "]", "=", "self", ".", "depends_on", "resource_dict", ".", "update", "(", "self", ".", "resource_attributes", ")", "properties_dict", "=", "{", "}", "for", "name", "in", "self", ".", "property_types", ":", "value", "=", "getattr", "(", "self", ",", "name", ")", "if", "value", "is", "not", "None", ":", "properties_dict", "[", "name", "]", "=", "value", "resource_dict", "[", "'Properties'", "]", "=", "properties_dict", "return", "resource_dict" ]
Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation template's Resources section. :returns: the resource dict for this Resource :rtype: dict
[ "Generates", "the", "resource", "dict", "for", "this", "Resource", "the", "value", "associated", "with", "the", "logical", "id", "in", "a", "CloudFormation", "template", "s", "Resources", "section", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L189-L213
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource.validate_properties
def validate_properties(self): """Validates that the required properties for this Resource have been populated, and that all properties have valid values. :returns: True if all properties are valid :rtype: bool :raises TypeError: if any properties are invalid """ for name, property_type in self.property_types.items(): value = getattr(self, name) # If the property value is an intrinsic function, any remaining validation has to be left to CloudFormation if property_type.supports_intrinsics and self._is_intrinsic_function(value): continue # If the property value has not been set, verify that the property is not required. if value is None: if property_type.required: raise InvalidResourceException( self.logical_id, "Missing required property '{property_name}'.".format(property_name=name)) # Otherwise, validate the value of the property. elif not property_type.validate(value, should_raise=False): raise InvalidResourceException( self.logical_id, "Type of property '{property_name}' is invalid.".format(property_name=name))
python
def validate_properties(self): """Validates that the required properties for this Resource have been populated, and that all properties have valid values. :returns: True if all properties are valid :rtype: bool :raises TypeError: if any properties are invalid """ for name, property_type in self.property_types.items(): value = getattr(self, name) # If the property value is an intrinsic function, any remaining validation has to be left to CloudFormation if property_type.supports_intrinsics and self._is_intrinsic_function(value): continue # If the property value has not been set, verify that the property is not required. if value is None: if property_type.required: raise InvalidResourceException( self.logical_id, "Missing required property '{property_name}'.".format(property_name=name)) # Otherwise, validate the value of the property. elif not property_type.validate(value, should_raise=False): raise InvalidResourceException( self.logical_id, "Type of property '{property_name}' is invalid.".format(property_name=name))
[ "def", "validate_properties", "(", "self", ")", ":", "for", "name", ",", "property_type", "in", "self", ".", "property_types", ".", "items", "(", ")", ":", "value", "=", "getattr", "(", "self", ",", "name", ")", "# If the property value is an intrinsic function, any remaining validation has to be left to CloudFormation", "if", "property_type", ".", "supports_intrinsics", "and", "self", ".", "_is_intrinsic_function", "(", "value", ")", ":", "continue", "# If the property value has not been set, verify that the property is not required.", "if", "value", "is", "None", ":", "if", "property_type", ".", "required", ":", "raise", "InvalidResourceException", "(", "self", ".", "logical_id", ",", "\"Missing required property '{property_name}'.\"", ".", "format", "(", "property_name", "=", "name", ")", ")", "# Otherwise, validate the value of the property.", "elif", "not", "property_type", ".", "validate", "(", "value", ",", "should_raise", "=", "False", ")", ":", "raise", "InvalidResourceException", "(", "self", ".", "logical_id", ",", "\"Type of property '{property_name}' is invalid.\"", ".", "format", "(", "property_name", "=", "name", ")", ")" ]
Validates that the required properties for this Resource have been populated, and that all properties have valid values. :returns: True if all properties are valid :rtype: bool :raises TypeError: if any properties are invalid
[ "Validates", "that", "the", "required", "properties", "for", "this", "Resource", "have", "been", "populated", "and", "that", "all", "properties", "have", "valid", "values", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L230-L255
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource.set_resource_attribute
def set_resource_attribute(self, attr, value): """Sets attributes on resource. Resource attributes are top-level entries of a CloudFormation resource that exist outside of the Properties dictionary :param attr: Attribute name :param value: Attribute value :return: None :raises KeyError if `attr` is not in the supported attribute list """ if attr not in self._supported_resource_attributes: raise KeyError("Unsupported resource attribute specified: %s" % attr) self.resource_attributes[attr] = value
python
def set_resource_attribute(self, attr, value): """Sets attributes on resource. Resource attributes are top-level entries of a CloudFormation resource that exist outside of the Properties dictionary :param attr: Attribute name :param value: Attribute value :return: None :raises KeyError if `attr` is not in the supported attribute list """ if attr not in self._supported_resource_attributes: raise KeyError("Unsupported resource attribute specified: %s" % attr) self.resource_attributes[attr] = value
[ "def", "set_resource_attribute", "(", "self", ",", "attr", ",", "value", ")", ":", "if", "attr", "not", "in", "self", ".", "_supported_resource_attributes", ":", "raise", "KeyError", "(", "\"Unsupported resource attribute specified: %s\"", "%", "attr", ")", "self", ".", "resource_attributes", "[", "attr", "]", "=", "value" ]
Sets attributes on resource. Resource attributes are top-level entries of a CloudFormation resource that exist outside of the Properties dictionary :param attr: Attribute name :param value: Attribute value :return: None :raises KeyError if `attr` is not in the supported attribute list
[ "Sets", "attributes", "on", "resource", ".", "Resource", "attributes", "are", "top", "-", "level", "entries", "of", "a", "CloudFormation", "resource", "that", "exist", "outside", "of", "the", "Properties", "dictionary" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L257-L270
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource.get_resource_attribute
def get_resource_attribute(self, attr): """Gets the resource attribute if available :param attr: Name of the attribute :return: Value of the attribute, if set in the resource. None otherwise """ if attr not in self.resource_attributes: raise KeyError("%s is not in resource attributes" % attr) return self.resource_attributes[attr]
python
def get_resource_attribute(self, attr): """Gets the resource attribute if available :param attr: Name of the attribute :return: Value of the attribute, if set in the resource. None otherwise """ if attr not in self.resource_attributes: raise KeyError("%s is not in resource attributes" % attr) return self.resource_attributes[attr]
[ "def", "get_resource_attribute", "(", "self", ",", "attr", ")", ":", "if", "attr", "not", "in", "self", ".", "resource_attributes", ":", "raise", "KeyError", "(", "\"%s is not in resource attributes\"", "%", "attr", ")", "return", "self", ".", "resource_attributes", "[", "attr", "]" ]
Gets the resource attribute if available :param attr: Name of the attribute :return: Value of the attribute, if set in the resource. None otherwise
[ "Gets", "the", "resource", "attribute", "if", "available" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L272-L281
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
Resource.get_runtime_attr
def get_runtime_attr(self, attr_name): """ Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide this attribute, then this method raises an exception :return: Dictionary that will resolve to value of the attribute when CloudFormation stack update is executed """ if attr_name in self.runtime_attrs: return self.runtime_attrs[attr_name](self) else: raise NotImplementedError(attr_name + " attribute is not implemented for resource " + self.resource_type)
python
def get_runtime_attr(self, attr_name): """ Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide this attribute, then this method raises an exception :return: Dictionary that will resolve to value of the attribute when CloudFormation stack update is executed """ if attr_name in self.runtime_attrs: return self.runtime_attrs[attr_name](self) else: raise NotImplementedError(attr_name + " attribute is not implemented for resource " + self.resource_type)
[ "def", "get_runtime_attr", "(", "self", ",", "attr_name", ")", ":", "if", "attr_name", "in", "self", ".", "runtime_attrs", ":", "return", "self", ".", "runtime_attrs", "[", "attr_name", "]", "(", "self", ")", "else", ":", "raise", "NotImplementedError", "(", "attr_name", "+", "\" attribute is not implemented for resource \"", "+", "self", ".", "resource_type", ")" ]
Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide this attribute, then this method raises an exception :return: Dictionary that will resolve to value of the attribute when CloudFormation stack update is executed
[ "Returns", "a", "CloudFormation", "construct", "that", "provides", "value", "for", "this", "attribute", ".", "If", "the", "resource", "does", "not", "provide", "this", "attribute", "then", "this", "method", "raises", "an", "exception" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L295-L306
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
SamResourceMacro.get_resource_references
def get_resource_references(self, generated_cfn_resources, supported_resource_refs): """ Constructs the list of supported resource references by going through the list of CFN resources generated by to_cloudformation() on this SAM resource. Each SAM resource must provide a map of properties that it supports and the type of CFN resource this property resolves to. :param list of Resource object generated_cfn_resources: List of CloudFormation resources generated by this SAM resource :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Object holding the mapping between property names and LogicalId of the generated CFN resource it maps to :return: Updated supported_resource_refs """ if supported_resource_refs is None: raise ValueError("`supported_resource_refs` object is required") # Create a map of {ResourceType: LogicalId} for quick access resource_id_by_type = {resource.resource_type: resource.logical_id for resource in generated_cfn_resources} for property, cfn_type in self.referable_properties.items(): if cfn_type in resource_id_by_type: supported_resource_refs.add(self.logical_id, property, resource_id_by_type[cfn_type]) return supported_resource_refs
python
def get_resource_references(self, generated_cfn_resources, supported_resource_refs): """ Constructs the list of supported resource references by going through the list of CFN resources generated by to_cloudformation() on this SAM resource. Each SAM resource must provide a map of properties that it supports and the type of CFN resource this property resolves to. :param list of Resource object generated_cfn_resources: List of CloudFormation resources generated by this SAM resource :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Object holding the mapping between property names and LogicalId of the generated CFN resource it maps to :return: Updated supported_resource_refs """ if supported_resource_refs is None: raise ValueError("`supported_resource_refs` object is required") # Create a map of {ResourceType: LogicalId} for quick access resource_id_by_type = {resource.resource_type: resource.logical_id for resource in generated_cfn_resources} for property, cfn_type in self.referable_properties.items(): if cfn_type in resource_id_by_type: supported_resource_refs.add(self.logical_id, property, resource_id_by_type[cfn_type]) return supported_resource_refs
[ "def", "get_resource_references", "(", "self", ",", "generated_cfn_resources", ",", "supported_resource_refs", ")", ":", "if", "supported_resource_refs", "is", "None", ":", "raise", "ValueError", "(", "\"`supported_resource_refs` object is required\"", ")", "# Create a map of {ResourceType: LogicalId} for quick access", "resource_id_by_type", "=", "{", "resource", ".", "resource_type", ":", "resource", ".", "logical_id", "for", "resource", "in", "generated_cfn_resources", "}", "for", "property", ",", "cfn_type", "in", "self", ".", "referable_properties", ".", "items", "(", ")", ":", "if", "cfn_type", "in", "resource_id_by_type", ":", "supported_resource_refs", ".", "add", "(", "self", ".", "logical_id", ",", "property", ",", "resource_id_by_type", "[", "cfn_type", "]", ")", "return", "supported_resource_refs" ]
Constructs the list of supported resource references by going through the list of CFN resources generated by to_cloudformation() on this SAM resource. Each SAM resource must provide a map of properties that it supports and the type of CFN resource this property resolves to. :param list of Resource object generated_cfn_resources: List of CloudFormation resources generated by this SAM resource :param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Object holding the mapping between property names and LogicalId of the generated CFN resource it maps to :return: Updated supported_resource_refs
[ "Constructs", "the", "list", "of", "supported", "resource", "references", "by", "going", "through", "the", "list", "of", "CFN", "resources", "generated", "by", "to_cloudformation", "()", "on", "this", "SAM", "resource", ".", "Each", "SAM", "resource", "must", "provide", "a", "map", "of", "properties", "that", "it", "supports", "and", "the", "type", "of", "CFN", "resource", "this", "property", "resolves", "to", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L383-L406
train
awslabs/serverless-application-model
samtranslator/model/__init__.py
ResourceTypeResolver.resolve_resource_type
def resolve_resource_type(self, resource_dict): """Returns the Resource class corresponding to the 'Type' key in the given resource dict. :param dict resource_dict: the resource dict to resolve :returns: the resolved Resource class :rtype: class """ if not self.can_resolve(resource_dict): raise TypeError("Resource dict has missing or invalid value for key Type. Event Type is: {}.".format( resource_dict.get('Type'))) if resource_dict['Type'] not in self.resource_types: raise TypeError("Invalid resource type {resource_type}".format(resource_type=resource_dict['Type'])) return self.resource_types[resource_dict['Type']]
python
def resolve_resource_type(self, resource_dict): """Returns the Resource class corresponding to the 'Type' key in the given resource dict. :param dict resource_dict: the resource dict to resolve :returns: the resolved Resource class :rtype: class """ if not self.can_resolve(resource_dict): raise TypeError("Resource dict has missing or invalid value for key Type. Event Type is: {}.".format( resource_dict.get('Type'))) if resource_dict['Type'] not in self.resource_types: raise TypeError("Invalid resource type {resource_type}".format(resource_type=resource_dict['Type'])) return self.resource_types[resource_dict['Type']]
[ "def", "resolve_resource_type", "(", "self", ",", "resource_dict", ")", ":", "if", "not", "self", ".", "can_resolve", "(", "resource_dict", ")", ":", "raise", "TypeError", "(", "\"Resource dict has missing or invalid value for key Type. Event Type is: {}.\"", ".", "format", "(", "resource_dict", ".", "get", "(", "'Type'", ")", ")", ")", "if", "resource_dict", "[", "'Type'", "]", "not", "in", "self", ".", "resource_types", ":", "raise", "TypeError", "(", "\"Invalid resource type {resource_type}\"", ".", "format", "(", "resource_type", "=", "resource_dict", "[", "'Type'", "]", ")", ")", "return", "self", ".", "resource_types", "[", "resource_dict", "[", "'Type'", "]", "]" ]
Returns the Resource class corresponding to the 'Type' key in the given resource dict. :param dict resource_dict: the resource dict to resolve :returns: the resolved Resource class :rtype: class
[ "Returns", "the", "Resource", "class", "corresponding", "to", "the", "Type", "key", "in", "the", "given", "resource", "dict", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/model/__init__.py#L469-L481
train
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
build_response_card
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.append(options[i]) return { 'contentType': 'application/vnd.amazonaws.card.generic', 'version': 1, 'genericAttachments': [{ 'title': title, 'subTitle': subtitle, 'buttons': buttons }] }
python
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.append(options[i]) return { 'contentType': 'application/vnd.amazonaws.card.generic', 'version': 1, 'genericAttachments': [{ 'title': title, 'subTitle': subtitle, 'buttons': buttons }] }
[ "def", "build_response_card", "(", "title", ",", "subtitle", ",", "options", ")", ":", "buttons", "=", "None", "if", "options", "is", "not", "None", ":", "buttons", "=", "[", "]", "for", "i", "in", "range", "(", "min", "(", "5", ",", "len", "(", "options", ")", ")", ")", ":", "buttons", ".", "append", "(", "options", "[", "i", "]", ")", "return", "{", "'contentType'", ":", "'application/vnd.amazonaws.card.generic'", ",", "'version'", ":", "1", ",", "'genericAttachments'", ":", "[", "{", "'title'", ":", "title", ",", "'subTitle'", ":", "subtitle", ",", "'buttons'", ":", "buttons", "}", "]", "}" ]
Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.
[ "Build", "a", "responseCard", "with", "a", "title", "subtitle", "and", "an", "optional", "set", "of", "options", "which", "should", "be", "displayed", "as", "buttons", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L75-L93
train
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
get_random_int
def get_random_int(minimum, maximum): """ Returns a random integer between min (included) and max (excluded) """ min_int = math.ceil(minimum) max_int = math.floor(maximum) return random.randint(min_int, max_int - 1)
python
def get_random_int(minimum, maximum): """ Returns a random integer between min (included) and max (excluded) """ min_int = math.ceil(minimum) max_int = math.floor(maximum) return random.randint(min_int, max_int - 1)
[ "def", "get_random_int", "(", "minimum", ",", "maximum", ")", ":", "min_int", "=", "math", ".", "ceil", "(", "minimum", ")", "max_int", "=", "math", ".", "floor", "(", "maximum", ")", "return", "random", ".", "randint", "(", "min_int", ",", "max_int", "-", "1", ")" ]
Returns a random integer between min (included) and max (excluded)
[ "Returns", "a", "random", "integer", "between", "min", "(", "included", ")", "and", "max", "(", "excluded", ")" ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L125-L132
train
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
get_availabilities
def get_availabilities(date): """ Helper function which in a full implementation would feed into a backend API to provide query schedule availability. The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format. In order to enable quick demonstration of all possible conversation paths supported in this example, the function returns a mixture of fixed and randomized results. On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at 10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday. """ day_of_week = dateutil.parser.parse(date).weekday() availabilities = [] available_probability = 0.3 if day_of_week == 0: start_hour = 10 while start_hour <= 16: if random.random() < available_probability: # Add an availability window for the given hour, with duration determined by another random number. appointment_type = get_random_int(1, 4) if appointment_type == 1: availabilities.append('{}:00'.format(start_hour)) elif appointment_type == 2: availabilities.append('{}:30'.format(start_hour)) else: availabilities.append('{}:00'.format(start_hour)) availabilities.append('{}:30'.format(start_hour)) start_hour += 1 if day_of_week == 2 or day_of_week == 4: availabilities.append('10:00') availabilities.append('16:00') availabilities.append('16:30') return availabilities
python
def get_availabilities(date): """ Helper function which in a full implementation would feed into a backend API to provide query schedule availability. The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format. In order to enable quick demonstration of all possible conversation paths supported in this example, the function returns a mixture of fixed and randomized results. On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at 10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday. """ day_of_week = dateutil.parser.parse(date).weekday() availabilities = [] available_probability = 0.3 if day_of_week == 0: start_hour = 10 while start_hour <= 16: if random.random() < available_probability: # Add an availability window for the given hour, with duration determined by another random number. appointment_type = get_random_int(1, 4) if appointment_type == 1: availabilities.append('{}:00'.format(start_hour)) elif appointment_type == 2: availabilities.append('{}:30'.format(start_hour)) else: availabilities.append('{}:00'.format(start_hour)) availabilities.append('{}:30'.format(start_hour)) start_hour += 1 if day_of_week == 2 or day_of_week == 4: availabilities.append('10:00') availabilities.append('16:00') availabilities.append('16:30') return availabilities
[ "def", "get_availabilities", "(", "date", ")", ":", "day_of_week", "=", "dateutil", ".", "parser", ".", "parse", "(", "date", ")", ".", "weekday", "(", ")", "availabilities", "=", "[", "]", "available_probability", "=", "0.3", "if", "day_of_week", "==", "0", ":", "start_hour", "=", "10", "while", "start_hour", "<=", "16", ":", "if", "random", ".", "random", "(", ")", "<", "available_probability", ":", "# Add an availability window for the given hour, with duration determined by another random number.", "appointment_type", "=", "get_random_int", "(", "1", ",", "4", ")", "if", "appointment_type", "==", "1", ":", "availabilities", ".", "append", "(", "'{}:00'", ".", "format", "(", "start_hour", ")", ")", "elif", "appointment_type", "==", "2", ":", "availabilities", ".", "append", "(", "'{}:30'", ".", "format", "(", "start_hour", ")", ")", "else", ":", "availabilities", ".", "append", "(", "'{}:00'", ".", "format", "(", "start_hour", ")", ")", "availabilities", ".", "append", "(", "'{}:30'", ".", "format", "(", "start_hour", ")", ")", "start_hour", "+=", "1", "if", "day_of_week", "==", "2", "or", "day_of_week", "==", "4", ":", "availabilities", ".", "append", "(", "'10:00'", ")", "availabilities", ".", "append", "(", "'16:00'", ")", "availabilities", ".", "append", "(", "'16:30'", ")", "return", "availabilities" ]
Helper function which in a full implementation would feed into a backend API to provide query schedule availability. The output of this function is an array of 30 minute periods of availability, expressed in ISO-8601 time format. In order to enable quick demonstration of all possible conversation paths supported in this example, the function returns a mixture of fixed and randomized results. On Mondays, availability is randomized; otherwise there is no availability on Tuesday / Thursday and availability at 10:00 - 10:30 and 4:00 - 5:00 on Wednesday / Friday.
[ "Helper", "function", "which", "in", "a", "full", "implementation", "would", "feed", "into", "a", "backend", "API", "to", "provide", "query", "schedule", "availability", ".", "The", "output", "of", "this", "function", "is", "an", "array", "of", "30", "minute", "periods", "of", "availability", "expressed", "in", "ISO", "-", "8601", "time", "format", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L135-L169
train
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
is_available
def is_available(time, duration, availabilities): """ Helper function to check if the given time and duration fits within a known set of availability windows. Duration is assumed to be one of 30, 60 (meaning minutes). Availabilities is expected to contain entries of the format HH:MM. """ if duration == 30: return time in availabilities elif duration == 60: second_half_hour_time = increment_time_by_thirty_mins(time) return time in availabilities and second_half_hour_time in availabilities # Invalid duration ; throw error. We should not have reached this branch due to earlier validation. raise Exception('Was not able to understand duration {}'.format(duration))
python
def is_available(time, duration, availabilities): """ Helper function to check if the given time and duration fits within a known set of availability windows. Duration is assumed to be one of 30, 60 (meaning minutes). Availabilities is expected to contain entries of the format HH:MM. """ if duration == 30: return time in availabilities elif duration == 60: second_half_hour_time = increment_time_by_thirty_mins(time) return time in availabilities and second_half_hour_time in availabilities # Invalid duration ; throw error. We should not have reached this branch due to earlier validation. raise Exception('Was not able to understand duration {}'.format(duration))
[ "def", "is_available", "(", "time", ",", "duration", ",", "availabilities", ")", ":", "if", "duration", "==", "30", ":", "return", "time", "in", "availabilities", "elif", "duration", "==", "60", ":", "second_half_hour_time", "=", "increment_time_by_thirty_mins", "(", "time", ")", "return", "time", "in", "availabilities", "and", "second_half_hour_time", "in", "availabilities", "# Invalid duration ; throw error. We should not have reached this branch due to earlier validation.", "raise", "Exception", "(", "'Was not able to understand duration {}'", ".", "format", "(", "duration", ")", ")" ]
Helper function to check if the given time and duration fits within a known set of availability windows. Duration is assumed to be one of 30, 60 (meaning minutes). Availabilities is expected to contain entries of the format HH:MM.
[ "Helper", "function", "to", "check", "if", "the", "given", "time", "and", "duration", "fits", "within", "a", "known", "set", "of", "availability", "windows", ".", "Duration", "is", "assumed", "to", "be", "one", "of", "30", "60", "(", "meaning", "minutes", ")", ".", "Availabilities", "is", "expected", "to", "contain", "entries", "of", "the", "format", "HH", ":", "MM", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L172-L184
train
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
get_availabilities_for_duration
def get_availabilities_for_duration(duration, availabilities): """ Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows. """ duration_availabilities = [] start_time = '10:00' while start_time != '17:00': if start_time in availabilities: if duration == 30: duration_availabilities.append(start_time) elif increment_time_by_thirty_mins(start_time) in availabilities: duration_availabilities.append(start_time) start_time = increment_time_by_thirty_mins(start_time) return duration_availabilities
python
def get_availabilities_for_duration(duration, availabilities): """ Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows. """ duration_availabilities = [] start_time = '10:00' while start_time != '17:00': if start_time in availabilities: if duration == 30: duration_availabilities.append(start_time) elif increment_time_by_thirty_mins(start_time) in availabilities: duration_availabilities.append(start_time) start_time = increment_time_by_thirty_mins(start_time) return duration_availabilities
[ "def", "get_availabilities_for_duration", "(", "duration", ",", "availabilities", ")", ":", "duration_availabilities", "=", "[", "]", "start_time", "=", "'10:00'", "while", "start_time", "!=", "'17:00'", ":", "if", "start_time", "in", "availabilities", ":", "if", "duration", "==", "30", ":", "duration_availabilities", ".", "append", "(", "start_time", ")", "elif", "increment_time_by_thirty_mins", "(", "start_time", ")", "in", "availabilities", ":", "duration_availabilities", ".", "append", "(", "start_time", ")", "start_time", "=", "increment_time_by_thirty_mins", "(", "start_time", ")", "return", "duration_availabilities" ]
Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows.
[ "Helper", "function", "to", "return", "the", "windows", "of", "availability", "of", "the", "given", "duration", "when", "provided", "a", "set", "of", "30", "minute", "windows", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L192-L207
train
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
build_available_time_string
def build_available_time_string(availabilities): """ Build a string eliciting for a possible time slot among at least two availabilities. """ prefix = 'We have availabilities at ' if len(availabilities) > 3: prefix = 'We have plenty of availability, including ' prefix += build_time_output_string(availabilities[0]) if len(availabilities) == 2: return '{} and {}'.format(prefix, build_time_output_string(availabilities[1])) return '{}, {} and {}'.format(prefix, build_time_output_string(availabilities[1]), build_time_output_string(availabilities[2]))
python
def build_available_time_string(availabilities): """ Build a string eliciting for a possible time slot among at least two availabilities. """ prefix = 'We have availabilities at ' if len(availabilities) > 3: prefix = 'We have plenty of availability, including ' prefix += build_time_output_string(availabilities[0]) if len(availabilities) == 2: return '{} and {}'.format(prefix, build_time_output_string(availabilities[1])) return '{}, {} and {}'.format(prefix, build_time_output_string(availabilities[1]), build_time_output_string(availabilities[2]))
[ "def", "build_available_time_string", "(", "availabilities", ")", ":", "prefix", "=", "'We have availabilities at '", "if", "len", "(", "availabilities", ")", ">", "3", ":", "prefix", "=", "'We have plenty of availability, including '", "prefix", "+=", "build_time_output_string", "(", "availabilities", "[", "0", "]", ")", "if", "len", "(", "availabilities", ")", "==", "2", ":", "return", "'{} and {}'", ".", "format", "(", "prefix", ",", "build_time_output_string", "(", "availabilities", "[", "1", "]", ")", ")", "return", "'{}, {} and {}'", ".", "format", "(", "prefix", ",", "build_time_output_string", "(", "availabilities", "[", "1", "]", ")", ",", "build_time_output_string", "(", "availabilities", "[", "2", "]", ")", ")" ]
Build a string eliciting for a possible time slot among at least two availabilities.
[ "Build", "a", "string", "eliciting", "for", "a", "possible", "time", "slot", "among", "at", "least", "two", "availabilities", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L261-L273
train
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
build_options
def build_options(slot, appointment_type, date, booking_map): """ Build a list of potential options for a given slot, to be used in responseCard generation. """ day_strings = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] if slot == 'AppointmentType': return [ {'text': 'cleaning (30 min)', 'value': 'cleaning'}, {'text': 'root canal (60 min)', 'value': 'root canal'}, {'text': 'whitening (30 min)', 'value': 'whitening'} ] elif slot == 'Date': # Return the next five weekdays. options = [] potential_date = datetime.datetime.today() while len(options) < 5: potential_date = potential_date + datetime.timedelta(days=1) if potential_date.weekday() < 5: options.append({'text': '{}-{} ({})'.format((potential_date.month), potential_date.day, day_strings[potential_date.weekday()]), 'value': potential_date.strftime('%A, %B %d, %Y')}) return options elif slot == 'Time': # Return the availabilities on the given date. if not appointment_type or not date: return None availabilities = try_ex(lambda: booking_map[date]) if not availabilities: return None availabilities = get_availabilities_for_duration(get_duration(appointment_type), availabilities) if len(availabilities) == 0: return None options = [] for i in range(min(len(availabilities), 5)): options.append({'text': build_time_output_string(availabilities[i]), 'value': build_time_output_string(availabilities[i])}) return options
python
def build_options(slot, appointment_type, date, booking_map): """ Build a list of potential options for a given slot, to be used in responseCard generation. """ day_strings = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] if slot == 'AppointmentType': return [ {'text': 'cleaning (30 min)', 'value': 'cleaning'}, {'text': 'root canal (60 min)', 'value': 'root canal'}, {'text': 'whitening (30 min)', 'value': 'whitening'} ] elif slot == 'Date': # Return the next five weekdays. options = [] potential_date = datetime.datetime.today() while len(options) < 5: potential_date = potential_date + datetime.timedelta(days=1) if potential_date.weekday() < 5: options.append({'text': '{}-{} ({})'.format((potential_date.month), potential_date.day, day_strings[potential_date.weekday()]), 'value': potential_date.strftime('%A, %B %d, %Y')}) return options elif slot == 'Time': # Return the availabilities on the given date. if not appointment_type or not date: return None availabilities = try_ex(lambda: booking_map[date]) if not availabilities: return None availabilities = get_availabilities_for_duration(get_duration(appointment_type), availabilities) if len(availabilities) == 0: return None options = [] for i in range(min(len(availabilities), 5)): options.append({'text': build_time_output_string(availabilities[i]), 'value': build_time_output_string(availabilities[i])}) return options
[ "def", "build_options", "(", "slot", ",", "appointment_type", ",", "date", ",", "booking_map", ")", ":", "day_strings", "=", "[", "'Mon'", ",", "'Tue'", ",", "'Wed'", ",", "'Thu'", ",", "'Fri'", ",", "'Sat'", ",", "'Sun'", "]", "if", "slot", "==", "'AppointmentType'", ":", "return", "[", "{", "'text'", ":", "'cleaning (30 min)'", ",", "'value'", ":", "'cleaning'", "}", ",", "{", "'text'", ":", "'root canal (60 min)'", ",", "'value'", ":", "'root canal'", "}", ",", "{", "'text'", ":", "'whitening (30 min)'", ",", "'value'", ":", "'whitening'", "}", "]", "elif", "slot", "==", "'Date'", ":", "# Return the next five weekdays.", "options", "=", "[", "]", "potential_date", "=", "datetime", ".", "datetime", ".", "today", "(", ")", "while", "len", "(", "options", ")", "<", "5", ":", "potential_date", "=", "potential_date", "+", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "if", "potential_date", ".", "weekday", "(", ")", "<", "5", ":", "options", ".", "append", "(", "{", "'text'", ":", "'{}-{} ({})'", ".", "format", "(", "(", "potential_date", ".", "month", ")", ",", "potential_date", ".", "day", ",", "day_strings", "[", "potential_date", ".", "weekday", "(", ")", "]", ")", ",", "'value'", ":", "potential_date", ".", "strftime", "(", "'%A, %B %d, %Y'", ")", "}", ")", "return", "options", "elif", "slot", "==", "'Time'", ":", "# Return the availabilities on the given date.", "if", "not", "appointment_type", "or", "not", "date", ":", "return", "None", "availabilities", "=", "try_ex", "(", "lambda", ":", "booking_map", "[", "date", "]", ")", "if", "not", "availabilities", ":", "return", "None", "availabilities", "=", "get_availabilities_for_duration", "(", "get_duration", "(", "appointment_type", ")", ",", "availabilities", ")", "if", "len", "(", "availabilities", ")", "==", "0", ":", "return", "None", "options", "=", "[", "]", "for", "i", "in", "range", "(", "min", "(", "len", "(", "availabilities", ")", ",", "5", ")", ")", ":", "options", ".", "append", "(", "{", "'text'", ":", "build_time_output_string", "(", "availabilities", "[", "i", "]", ")", ",", "'value'", ":", "build_time_output_string", "(", "availabilities", "[", "i", "]", ")", "}", ")", "return", "options" ]
Build a list of potential options for a given slot, to be used in responseCard generation.
[ "Build", "a", "list", "of", "potential", "options", "for", "a", "given", "slot", "to", "be", "used", "in", "responseCard", "generation", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L276-L314
train
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
make_appointment
def make_appointment(intent_request): """ Performs dialog management and fulfillment for booking a dentists appointment. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of confirmIntent to support the confirmation of inferred slot values, when confirmation is required on the bot model and the inferred slot values fully specify the intent. """ appointment_type = intent_request['currentIntent']['slots']['AppointmentType'] date = intent_request['currentIntent']['slots']['Date'] time = intent_request['currentIntent']['slots']['Time'] source = intent_request['invocationSource'] output_session_attributes = intent_request['sessionAttributes'] booking_map = json.loads(try_ex(lambda: output_session_attributes['bookingMap']) or '{}') if source == 'DialogCodeHook': # Perform basic validation on the supplied input slots. slots = intent_request['currentIntent']['slots'] validation_result = validate_book_appointment(appointment_type, date, time) if not validation_result['isValid']: slots[validation_result['violatedSlot']] = None return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, validation_result['violatedSlot'], validation_result['message'], build_response_card( 'Specify {}'.format(validation_result['violatedSlot']), validation_result['message']['content'], build_options(validation_result['violatedSlot'], appointment_type, date, booking_map) ) ) if not appointment_type: return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], intent_request['currentIntent']['slots'], 'AppointmentType', {'contentType': 'PlainText', 'content': 'What type of appointment would you like to schedule?'}, build_response_card( 'Specify Appointment Type', 'What type of appointment would you like to schedule?', build_options('AppointmentType', appointment_type, date, None) ) ) if appointment_type and not date: return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], intent_request['currentIntent']['slots'], 'Date', {'contentType': 'PlainText', 'content': 'When would you like to schedule your {}?'.format(appointment_type)}, build_response_card( 'Specify Date', 'When would you like to schedule your {}?'.format(appointment_type), build_options('Date', appointment_type, date, None) ) ) if appointment_type and date: # Fetch or generate the availabilities for the given date. booking_availabilities = try_ex(lambda: booking_map[date]) if booking_availabilities is None: booking_availabilities = get_availabilities(date) booking_map[date] = booking_availabilities output_session_attributes['bookingMap'] = json.dumps(booking_map) appointment_type_availabilities = get_availabilities_for_duration(get_duration(appointment_type), booking_availabilities) if len(appointment_type_availabilities) == 0: # No availability on this day at all; ask for a new date and time. slots['Date'] = None slots['Time'] = None return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, 'Date', {'contentType': 'PlainText', 'content': 'We do not have any availability on that date, is there another day which works for you?'}, build_response_card( 'Specify Date', 'What day works best for you?', build_options('Date', appointment_type, date, booking_map) ) ) message_content = 'What time on {} works for you? '.format(date) if time: output_session_attributes['formattedTime'] = build_time_output_string(time) # Validate that proposed time for the appointment can be booked by first fetching the availabilities for the given day. To # give consistent behavior in the sample, this is stored in sessionAttributes after the first lookup. if is_available(time, get_duration(appointment_type), booking_availabilities): return delegate(output_session_attributes, slots) message_content = 'The time you requested is not available. ' if len(appointment_type_availabilities) == 1: # If there is only one availability on the given date, try to confirm it. slots['Time'] = appointment_type_availabilities[0] return confirm_intent( output_session_attributes, intent_request['currentIntent']['name'], slots, { 'contentType': 'PlainText', 'content': '{}{} is our only availability, does that work for you?'.format (message_content, build_time_output_string(appointment_type_availabilities[0])) }, build_response_card( 'Confirm Appointment', 'Is {} on {} okay?'.format(build_time_output_string(appointment_type_availabilities[0]), date), [{'text': 'yes', 'value': 'yes'}, {'text': 'no', 'value': 'no'}] ) ) available_time_string = build_available_time_string(appointment_type_availabilities) return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, 'Time', {'contentType': 'PlainText', 'content': '{}{}'.format(message_content, available_time_string)}, build_response_card( 'Specify Time', 'What time works best for you?', build_options('Time', appointment_type, date, booking_map) ) ) return delegate(output_session_attributes, slots) # Book the appointment. In a real bot, this would likely involve a call to a backend service. duration = get_duration(appointment_type) booking_availabilities = booking_map[date] if booking_availabilities: # Remove the availability slot for the given date as it has now been booked. booking_availabilities.remove(time) if duration == 60: second_half_hour_time = increment_time_by_thirty_mins(time) booking_availabilities.remove(second_half_hour_time) booking_map[date] = booking_availabilities output_session_attributes['bookingMap'] = json.dumps(booking_map) else: # This is not treated as an error as this code sample supports functionality either as fulfillment or dialog code hook. logger.debug('Availabilities for {} were null at fulfillment time. ' 'This should have been initialized if this function was configured as the dialog code hook'.format(date)) return close( output_session_attributes, 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Okay, I have booked your appointment. We will see you at {} on {}'.format(build_time_output_string(time), date) } )
python
def make_appointment(intent_request): """ Performs dialog management and fulfillment for booking a dentists appointment. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of confirmIntent to support the confirmation of inferred slot values, when confirmation is required on the bot model and the inferred slot values fully specify the intent. """ appointment_type = intent_request['currentIntent']['slots']['AppointmentType'] date = intent_request['currentIntent']['slots']['Date'] time = intent_request['currentIntent']['slots']['Time'] source = intent_request['invocationSource'] output_session_attributes = intent_request['sessionAttributes'] booking_map = json.loads(try_ex(lambda: output_session_attributes['bookingMap']) or '{}') if source == 'DialogCodeHook': # Perform basic validation on the supplied input slots. slots = intent_request['currentIntent']['slots'] validation_result = validate_book_appointment(appointment_type, date, time) if not validation_result['isValid']: slots[validation_result['violatedSlot']] = None return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, validation_result['violatedSlot'], validation_result['message'], build_response_card( 'Specify {}'.format(validation_result['violatedSlot']), validation_result['message']['content'], build_options(validation_result['violatedSlot'], appointment_type, date, booking_map) ) ) if not appointment_type: return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], intent_request['currentIntent']['slots'], 'AppointmentType', {'contentType': 'PlainText', 'content': 'What type of appointment would you like to schedule?'}, build_response_card( 'Specify Appointment Type', 'What type of appointment would you like to schedule?', build_options('AppointmentType', appointment_type, date, None) ) ) if appointment_type and not date: return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], intent_request['currentIntent']['slots'], 'Date', {'contentType': 'PlainText', 'content': 'When would you like to schedule your {}?'.format(appointment_type)}, build_response_card( 'Specify Date', 'When would you like to schedule your {}?'.format(appointment_type), build_options('Date', appointment_type, date, None) ) ) if appointment_type and date: # Fetch or generate the availabilities for the given date. booking_availabilities = try_ex(lambda: booking_map[date]) if booking_availabilities is None: booking_availabilities = get_availabilities(date) booking_map[date] = booking_availabilities output_session_attributes['bookingMap'] = json.dumps(booking_map) appointment_type_availabilities = get_availabilities_for_duration(get_duration(appointment_type), booking_availabilities) if len(appointment_type_availabilities) == 0: # No availability on this day at all; ask for a new date and time. slots['Date'] = None slots['Time'] = None return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, 'Date', {'contentType': 'PlainText', 'content': 'We do not have any availability on that date, is there another day which works for you?'}, build_response_card( 'Specify Date', 'What day works best for you?', build_options('Date', appointment_type, date, booking_map) ) ) message_content = 'What time on {} works for you? '.format(date) if time: output_session_attributes['formattedTime'] = build_time_output_string(time) # Validate that proposed time for the appointment can be booked by first fetching the availabilities for the given day. To # give consistent behavior in the sample, this is stored in sessionAttributes after the first lookup. if is_available(time, get_duration(appointment_type), booking_availabilities): return delegate(output_session_attributes, slots) message_content = 'The time you requested is not available. ' if len(appointment_type_availabilities) == 1: # If there is only one availability on the given date, try to confirm it. slots['Time'] = appointment_type_availabilities[0] return confirm_intent( output_session_attributes, intent_request['currentIntent']['name'], slots, { 'contentType': 'PlainText', 'content': '{}{} is our only availability, does that work for you?'.format (message_content, build_time_output_string(appointment_type_availabilities[0])) }, build_response_card( 'Confirm Appointment', 'Is {} on {} okay?'.format(build_time_output_string(appointment_type_availabilities[0]), date), [{'text': 'yes', 'value': 'yes'}, {'text': 'no', 'value': 'no'}] ) ) available_time_string = build_available_time_string(appointment_type_availabilities) return elicit_slot( output_session_attributes, intent_request['currentIntent']['name'], slots, 'Time', {'contentType': 'PlainText', 'content': '{}{}'.format(message_content, available_time_string)}, build_response_card( 'Specify Time', 'What time works best for you?', build_options('Time', appointment_type, date, booking_map) ) ) return delegate(output_session_attributes, slots) # Book the appointment. In a real bot, this would likely involve a call to a backend service. duration = get_duration(appointment_type) booking_availabilities = booking_map[date] if booking_availabilities: # Remove the availability slot for the given date as it has now been booked. booking_availabilities.remove(time) if duration == 60: second_half_hour_time = increment_time_by_thirty_mins(time) booking_availabilities.remove(second_half_hour_time) booking_map[date] = booking_availabilities output_session_attributes['bookingMap'] = json.dumps(booking_map) else: # This is not treated as an error as this code sample supports functionality either as fulfillment or dialog code hook. logger.debug('Availabilities for {} were null at fulfillment time. ' 'This should have been initialized if this function was configured as the dialog code hook'.format(date)) return close( output_session_attributes, 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Okay, I have booked your appointment. We will see you at {} on {}'.format(build_time_output_string(time), date) } )
[ "def", "make_appointment", "(", "intent_request", ")", ":", "appointment_type", "=", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "[", "'AppointmentType'", "]", "date", "=", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "[", "'Date'", "]", "time", "=", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "[", "'Time'", "]", "source", "=", "intent_request", "[", "'invocationSource'", "]", "output_session_attributes", "=", "intent_request", "[", "'sessionAttributes'", "]", "booking_map", "=", "json", ".", "loads", "(", "try_ex", "(", "lambda", ":", "output_session_attributes", "[", "'bookingMap'", "]", ")", "or", "'{}'", ")", "if", "source", "==", "'DialogCodeHook'", ":", "# Perform basic validation on the supplied input slots.", "slots", "=", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", "validation_result", "=", "validate_book_appointment", "(", "appointment_type", ",", "date", ",", "time", ")", "if", "not", "validation_result", "[", "'isValid'", "]", ":", "slots", "[", "validation_result", "[", "'violatedSlot'", "]", "]", "=", "None", "return", "elicit_slot", "(", "output_session_attributes", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ",", "slots", ",", "validation_result", "[", "'violatedSlot'", "]", ",", "validation_result", "[", "'message'", "]", ",", "build_response_card", "(", "'Specify {}'", ".", "format", "(", "validation_result", "[", "'violatedSlot'", "]", ")", ",", "validation_result", "[", "'message'", "]", "[", "'content'", "]", ",", "build_options", "(", "validation_result", "[", "'violatedSlot'", "]", ",", "appointment_type", ",", "date", ",", "booking_map", ")", ")", ")", "if", "not", "appointment_type", ":", "return", "elicit_slot", "(", "output_session_attributes", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", ",", "'AppointmentType'", ",", "{", "'contentType'", ":", "'PlainText'", ",", "'content'", ":", "'What type of appointment would you like to schedule?'", "}", ",", "build_response_card", "(", "'Specify Appointment Type'", ",", "'What type of appointment would you like to schedule?'", ",", "build_options", "(", "'AppointmentType'", ",", "appointment_type", ",", "date", ",", "None", ")", ")", ")", "if", "appointment_type", "and", "not", "date", ":", "return", "elicit_slot", "(", "output_session_attributes", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'slots'", "]", ",", "'Date'", ",", "{", "'contentType'", ":", "'PlainText'", ",", "'content'", ":", "'When would you like to schedule your {}?'", ".", "format", "(", "appointment_type", ")", "}", ",", "build_response_card", "(", "'Specify Date'", ",", "'When would you like to schedule your {}?'", ".", "format", "(", "appointment_type", ")", ",", "build_options", "(", "'Date'", ",", "appointment_type", ",", "date", ",", "None", ")", ")", ")", "if", "appointment_type", "and", "date", ":", "# Fetch or generate the availabilities for the given date.", "booking_availabilities", "=", "try_ex", "(", "lambda", ":", "booking_map", "[", "date", "]", ")", "if", "booking_availabilities", "is", "None", ":", "booking_availabilities", "=", "get_availabilities", "(", "date", ")", "booking_map", "[", "date", "]", "=", "booking_availabilities", "output_session_attributes", "[", "'bookingMap'", "]", "=", "json", ".", "dumps", "(", "booking_map", ")", "appointment_type_availabilities", "=", "get_availabilities_for_duration", "(", "get_duration", "(", "appointment_type", ")", ",", "booking_availabilities", ")", "if", "len", "(", "appointment_type_availabilities", ")", "==", "0", ":", "# No availability on this day at all; ask for a new date and time.", "slots", "[", "'Date'", "]", "=", "None", "slots", "[", "'Time'", "]", "=", "None", "return", "elicit_slot", "(", "output_session_attributes", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ",", "slots", ",", "'Date'", ",", "{", "'contentType'", ":", "'PlainText'", ",", "'content'", ":", "'We do not have any availability on that date, is there another day which works for you?'", "}", ",", "build_response_card", "(", "'Specify Date'", ",", "'What day works best for you?'", ",", "build_options", "(", "'Date'", ",", "appointment_type", ",", "date", ",", "booking_map", ")", ")", ")", "message_content", "=", "'What time on {} works for you? '", ".", "format", "(", "date", ")", "if", "time", ":", "output_session_attributes", "[", "'formattedTime'", "]", "=", "build_time_output_string", "(", "time", ")", "# Validate that proposed time for the appointment can be booked by first fetching the availabilities for the given day. To", "# give consistent behavior in the sample, this is stored in sessionAttributes after the first lookup.", "if", "is_available", "(", "time", ",", "get_duration", "(", "appointment_type", ")", ",", "booking_availabilities", ")", ":", "return", "delegate", "(", "output_session_attributes", ",", "slots", ")", "message_content", "=", "'The time you requested is not available. '", "if", "len", "(", "appointment_type_availabilities", ")", "==", "1", ":", "# If there is only one availability on the given date, try to confirm it.", "slots", "[", "'Time'", "]", "=", "appointment_type_availabilities", "[", "0", "]", "return", "confirm_intent", "(", "output_session_attributes", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ",", "slots", ",", "{", "'contentType'", ":", "'PlainText'", ",", "'content'", ":", "'{}{} is our only availability, does that work for you?'", ".", "format", "(", "message_content", ",", "build_time_output_string", "(", "appointment_type_availabilities", "[", "0", "]", ")", ")", "}", ",", "build_response_card", "(", "'Confirm Appointment'", ",", "'Is {} on {} okay?'", ".", "format", "(", "build_time_output_string", "(", "appointment_type_availabilities", "[", "0", "]", ")", ",", "date", ")", ",", "[", "{", "'text'", ":", "'yes'", ",", "'value'", ":", "'yes'", "}", ",", "{", "'text'", ":", "'no'", ",", "'value'", ":", "'no'", "}", "]", ")", ")", "available_time_string", "=", "build_available_time_string", "(", "appointment_type_availabilities", ")", "return", "elicit_slot", "(", "output_session_attributes", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ",", "slots", ",", "'Time'", ",", "{", "'contentType'", ":", "'PlainText'", ",", "'content'", ":", "'{}{}'", ".", "format", "(", "message_content", ",", "available_time_string", ")", "}", ",", "build_response_card", "(", "'Specify Time'", ",", "'What time works best for you?'", ",", "build_options", "(", "'Time'", ",", "appointment_type", ",", "date", ",", "booking_map", ")", ")", ")", "return", "delegate", "(", "output_session_attributes", ",", "slots", ")", "# Book the appointment. In a real bot, this would likely involve a call to a backend service.", "duration", "=", "get_duration", "(", "appointment_type", ")", "booking_availabilities", "=", "booking_map", "[", "date", "]", "if", "booking_availabilities", ":", "# Remove the availability slot for the given date as it has now been booked.", "booking_availabilities", ".", "remove", "(", "time", ")", "if", "duration", "==", "60", ":", "second_half_hour_time", "=", "increment_time_by_thirty_mins", "(", "time", ")", "booking_availabilities", ".", "remove", "(", "second_half_hour_time", ")", "booking_map", "[", "date", "]", "=", "booking_availabilities", "output_session_attributes", "[", "'bookingMap'", "]", "=", "json", ".", "dumps", "(", "booking_map", ")", "else", ":", "# This is not treated as an error as this code sample supports functionality either as fulfillment or dialog code hook.", "logger", ".", "debug", "(", "'Availabilities for {} were null at fulfillment time. '", "'This should have been initialized if this function was configured as the dialog code hook'", ".", "format", "(", "date", ")", ")", "return", "close", "(", "output_session_attributes", ",", "'Fulfilled'", ",", "{", "'contentType'", ":", "'PlainText'", ",", "'content'", ":", "'Okay, I have booked your appointment. We will see you at {} on {}'", ".", "format", "(", "build_time_output_string", "(", "time", ")", ",", "date", ")", "}", ")" ]
Performs dialog management and fulfillment for booking a dentists appointment. Beyond fulfillment, the implementation for this intent demonstrates the following: 1) Use of elicitSlot in slot validation and re-prompting 2) Use of confirmIntent to support the confirmation of inferred slot values, when confirmation is required on the bot model and the inferred slot values fully specify the intent.
[ "Performs", "dialog", "management", "and", "fulfillment", "for", "booking", "a", "dentists", "appointment", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L320-L476
train
awslabs/serverless-application-model
examples/apps/lex-make-appointment-python/lambda_function.py
dispatch
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot's intent handlers if intent_name == 'MakeAppointment': return make_appointment(intent_request) raise Exception('Intent with name ' + intent_name + ' not supported')
python
def dispatch(intent_request): """ Called when the user specifies an intent for this bot. """ logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name'])) intent_name = intent_request['currentIntent']['name'] # Dispatch to your bot's intent handlers if intent_name == 'MakeAppointment': return make_appointment(intent_request) raise Exception('Intent with name ' + intent_name + ' not supported')
[ "def", "dispatch", "(", "intent_request", ")", ":", "logger", ".", "debug", "(", "'dispatch userId={}, intentName={}'", ".", "format", "(", "intent_request", "[", "'userId'", "]", ",", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", ")", ")", "intent_name", "=", "intent_request", "[", "'currentIntent'", "]", "[", "'name'", "]", "# Dispatch to your bot's intent handlers", "if", "intent_name", "==", "'MakeAppointment'", ":", "return", "make_appointment", "(", "intent_request", ")", "raise", "Exception", "(", "'Intent with name '", "+", "intent_name", "+", "' not supported'", ")" ]
Called when the user specifies an intent for this bot.
[ "Called", "when", "the", "user", "specifies", "an", "intent", "for", "this", "bot", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/lex-make-appointment-python/lambda_function.py#L482-L494
train
awslabs/serverless-application-model
examples/apps/microservice-http-endpoint-python3/lambda_function.py
lambda_handler
def lambda_handler(event, context): '''Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. TableName provided by template.yaml. To scan a DynamoDB table, make a GET request with optional query string parameter. To put, update, or delete an item, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body. ''' print("Received event: " + json.dumps(event, indent=2)) operations = { 'DELETE': lambda dynamo, x: dynamo.delete_item(TableName=table_name, **x), 'GET': lambda dynamo, x: dynamo.scan(TableName=table_name, **x) if x else dynamo.scan(TableName=table_name), 'POST': lambda dynamo, x: dynamo.put_item(TableName=table_name, **x), 'PUT': lambda dynamo, x: dynamo.update_item(TableName=table_name, **x), } operation = event['httpMethod'] if operation in operations: payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body']) return respond(None, operations[operation](dynamo, payload)) else: return respond(ValueError('Unsupported method "{}"'.format(operation)))
python
def lambda_handler(event, context): '''Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. TableName provided by template.yaml. To scan a DynamoDB table, make a GET request with optional query string parameter. To put, update, or delete an item, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body. ''' print("Received event: " + json.dumps(event, indent=2)) operations = { 'DELETE': lambda dynamo, x: dynamo.delete_item(TableName=table_name, **x), 'GET': lambda dynamo, x: dynamo.scan(TableName=table_name, **x) if x else dynamo.scan(TableName=table_name), 'POST': lambda dynamo, x: dynamo.put_item(TableName=table_name, **x), 'PUT': lambda dynamo, x: dynamo.update_item(TableName=table_name, **x), } operation = event['httpMethod'] if operation in operations: payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body']) return respond(None, operations[operation](dynamo, payload)) else: return respond(ValueError('Unsupported method "{}"'.format(operation)))
[ "def", "lambda_handler", "(", "event", ",", "context", ")", ":", "print", "(", "\"Received event: \"", "+", "json", ".", "dumps", "(", "event", ",", "indent", "=", "2", ")", ")", "operations", "=", "{", "'DELETE'", ":", "lambda", "dynamo", ",", "x", ":", "dynamo", ".", "delete_item", "(", "TableName", "=", "table_name", ",", "*", "*", "x", ")", ",", "'GET'", ":", "lambda", "dynamo", ",", "x", ":", "dynamo", ".", "scan", "(", "TableName", "=", "table_name", ",", "*", "*", "x", ")", "if", "x", "else", "dynamo", ".", "scan", "(", "TableName", "=", "table_name", ")", ",", "'POST'", ":", "lambda", "dynamo", ",", "x", ":", "dynamo", ".", "put_item", "(", "TableName", "=", "table_name", ",", "*", "*", "x", ")", ",", "'PUT'", ":", "lambda", "dynamo", ",", "x", ":", "dynamo", ".", "update_item", "(", "TableName", "=", "table_name", ",", "*", "*", "x", ")", ",", "}", "operation", "=", "event", "[", "'httpMethod'", "]", "if", "operation", "in", "operations", ":", "payload", "=", "event", "[", "'queryStringParameters'", "]", "if", "operation", "==", "'GET'", "else", "json", ".", "loads", "(", "event", "[", "'body'", "]", ")", "return", "respond", "(", "None", ",", "operations", "[", "operation", "]", "(", "dynamo", ",", "payload", ")", ")", "else", ":", "return", "respond", "(", "ValueError", "(", "'Unsupported method \"{}\"'", ".", "format", "(", "operation", ")", ")", ")" ]
Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. TableName provided by template.yaml. To scan a DynamoDB table, make a GET request with optional query string parameter. To put, update, or delete an item, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body.
[ "Demonstrates", "a", "simple", "HTTP", "endpoint", "using", "API", "Gateway", ".", "You", "have", "full", "access", "to", "the", "request", "and", "response", "payload", "including", "headers", "and", "status", "code", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/microservice-http-endpoint-python3/lambda_function.py#L21-L46
train
awslabs/serverless-application-model
examples/apps/microservice-http-endpoint-python/lambda_function.py
lambda_handler
def lambda_handler(event, context): '''Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. To scan a DynamoDB table, make a GET request with the TableName as a query string parameter. To put, update, or delete an item, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body. ''' #print("Received event: " + json.dumps(event, indent=2)) operations = { 'DELETE': lambda dynamo, x: dynamo.delete_item(**x), 'GET': lambda dynamo, x: dynamo.scan(**x), 'POST': lambda dynamo, x: dynamo.put_item(**x), 'PUT': lambda dynamo, x: dynamo.update_item(**x), } operation = event['httpMethod'] if operation in operations: payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body']) return respond(None, operations[operation](dynamo, payload)) else: return respond(ValueError('Unsupported method "{}"'.format(operation)))
python
def lambda_handler(event, context): '''Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. To scan a DynamoDB table, make a GET request with the TableName as a query string parameter. To put, update, or delete an item, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body. ''' #print("Received event: " + json.dumps(event, indent=2)) operations = { 'DELETE': lambda dynamo, x: dynamo.delete_item(**x), 'GET': lambda dynamo, x: dynamo.scan(**x), 'POST': lambda dynamo, x: dynamo.put_item(**x), 'PUT': lambda dynamo, x: dynamo.update_item(**x), } operation = event['httpMethod'] if operation in operations: payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body']) return respond(None, operations[operation](dynamo, payload)) else: return respond(ValueError('Unsupported method "{}"'.format(operation)))
[ "def", "lambda_handler", "(", "event", ",", "context", ")", ":", "#print(\"Received event: \" + json.dumps(event, indent=2))", "operations", "=", "{", "'DELETE'", ":", "lambda", "dynamo", ",", "x", ":", "dynamo", ".", "delete_item", "(", "*", "*", "x", ")", ",", "'GET'", ":", "lambda", "dynamo", ",", "x", ":", "dynamo", ".", "scan", "(", "*", "*", "x", ")", ",", "'POST'", ":", "lambda", "dynamo", ",", "x", ":", "dynamo", ".", "put_item", "(", "*", "*", "x", ")", ",", "'PUT'", ":", "lambda", "dynamo", ",", "x", ":", "dynamo", ".", "update_item", "(", "*", "*", "x", ")", ",", "}", "operation", "=", "event", "[", "'httpMethod'", "]", "if", "operation", "in", "operations", ":", "payload", "=", "event", "[", "'queryStringParameters'", "]", "if", "operation", "==", "'GET'", "else", "json", ".", "loads", "(", "event", "[", "'body'", "]", ")", "return", "respond", "(", "None", ",", "operations", "[", "operation", "]", "(", "dynamo", ",", "payload", ")", ")", "else", ":", "return", "respond", "(", "ValueError", "(", "'Unsupported method \"{}\"'", ".", "format", "(", "operation", ")", ")", ")" ]
Demonstrates a simple HTTP endpoint using API Gateway. You have full access to the request and response payload, including headers and status code. To scan a DynamoDB table, make a GET request with the TableName as a query string parameter. To put, update, or delete an item, make a POST, PUT, or DELETE request respectively, passing in the payload to the DynamoDB API as a JSON body.
[ "Demonstrates", "a", "simple", "HTTP", "endpoint", "using", "API", "Gateway", ".", "You", "have", "full", "access", "to", "the", "request", "and", "response", "payload", "including", "headers", "and", "status", "code", "." ]
cccb0c96b5c91e53355ebc07e542467303a5eedd
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/examples/apps/microservice-http-endpoint-python/lambda_function.py#L20-L44
train