text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
r"""
<END_TASK>
<USER_TASK:>
Description:
def get_thing_shadow(self, **kwargs):
r"""
Call shadow lambda to obtain current shadow state.
:Keyword Arguments:
* *thingName* (``string``) --
[REQUIRED]
The name of the thing.
:returns: (``dict``) --
The output from the GetThingShadow operation
* *payload* (``bytes``) --
The state information, in JSON format.
""" |
thing_name = self._get_required_parameter('thingName', **kwargs)
payload = b''
return self._shadow_op('get', thing_name, payload) |
<SYSTEM_TASK:>
r"""
<END_TASK>
<USER_TASK:>
Description:
def delete_thing_shadow(self, **kwargs):
r"""
Deletes the thing shadow for the specified thing.
:Keyword Arguments:
* *thingName* (``string``) --
[REQUIRED]
The name of the thing.
:returns: (``dict``) --
The output from the DeleteThingShadow operation
* *payload* (``bytes``) --
The state information, in JSON format.
""" |
thing_name = self._get_required_parameter('thingName', **kwargs)
payload = b''
return self._shadow_op('delete', thing_name, payload) |
<SYSTEM_TASK:>
r"""
<END_TASK>
<USER_TASK:>
Description:
def publish(self, **kwargs):
r"""
Publishes state information.
:Keyword Arguments:
* *topic* (``string``) --
[REQUIRED]
The name of the MQTT topic.
* *payload* (``bytes or seekable file-like object``) --
The state information, in JSON format.
:returns: None
""" |
topic = self._get_required_parameter('topic', **kwargs)
# payload is an optional parameter
payload = kwargs.get('payload', b'')
function_arn = ROUTER_FUNCTION_ARN
client_context = {
'custom': {
'source': MY_FUNCTION_ARN,
'subject': topic
}
}
customer_logger.info('Publishing message on topic "{}" with Payload "{}"'.format(topic, payload))
self.lambda_client._invoke_internal(
function_arn,
payload,
base64.b64encode(json.dumps(client_context).encode())
) |
<SYSTEM_TASK:>
Adds global properties to the resource, if necessary. This method is a no-op if there are no global properties
<END_TASK>
<USER_TASK:>
Description:
def merge(self, resource_type, resource_properties):
"""
Adds global properties to the resource, if necessary. This method is a no-op if there are no global properties
for this resource type
:param string resource_type: Type of the resource (Ex: AWS::Serverless::Function)
:param dict resource_properties: Properties of the resource that need to be merged
:return dict: Merged properties of the resource
""" |
if resource_type not in self.template_globals:
# Nothing to do. Return the template unmodified
return resource_properties
global_props = self.template_globals[resource_type]
return global_props.merge(resource_properties) |
<SYSTEM_TASK:>
Takes a SAM template as input and parses the Globals section
<END_TASK>
<USER_TASK:>
Description:
def _parse(self, globals_dict):
"""
Takes a SAM template as input and parses the Globals section
:param globals_dict: Dictionary representation of the Globals section
:return: Processed globals dictionary which can be used to quickly identify properties to merge
:raises: InvalidResourceException if the input contains properties that we don't support
""" |
globals = {}
if not isinstance(globals_dict, dict):
raise InvalidGlobalsSectionException(self._KEYWORD,
"It must be a non-empty dictionary".format(self._KEYWORD))
for section_name, properties in globals_dict.items():
resource_type = self._make_resource_type(section_name)
if resource_type not in self.supported_properties:
raise InvalidGlobalsSectionException(self._KEYWORD,
"'{section}' is not supported. "
"Must be one of the following values - {supported}"
.format(section=section_name,
supported=self.supported_resource_section_names))
if not isinstance(properties, dict):
raise InvalidGlobalsSectionException(self._KEYWORD, "Value of ${section} must be a dictionary")
for key, value in properties.items():
supported = self.supported_properties[resource_type]
if key not in supported:
raise InvalidGlobalsSectionException(self._KEYWORD,
"'{key}' is not a supported property of '{section}'. "
"Must be one of the following values - {supported}"
.format(key=key, section=section_name, supported=supported))
# Store all Global properties in a map with key being the AWS::Serverless::* resource type
globals[resource_type] = GlobalProperties(properties)
return globals |
<SYSTEM_TASK:>
Actually perform the merge operation for the given inputs. This method is used as part of the recursion.
<END_TASK>
<USER_TASK:>
Description:
def _do_merge(self, global_value, local_value):
"""
Actually perform the merge operation for the given inputs. This method is used as part of the recursion.
Therefore input values can be of any type. So is the output.
:param global_value: Global value to be merged
:param local_value: Local value to be merged
:return: Merged result
""" |
token_global = self._token_of(global_value)
token_local = self._token_of(local_value)
# The following statements codify the rules explained in the doctring above
if token_global != token_local:
return self._prefer_local(global_value, local_value)
elif self.TOKEN.PRIMITIVE == token_global == token_local:
return self._prefer_local(global_value, local_value)
elif self.TOKEN.DICT == token_global == token_local:
return self._merge_dict(global_value, local_value)
elif self.TOKEN.LIST == token_global == token_local:
return self._merge_lists(global_value, local_value)
else:
raise TypeError(
"Unsupported type of objects. GlobalType={}, LocalType={}".format(token_global, token_local)) |
<SYSTEM_TASK:>
Merges the two dictionaries together
<END_TASK>
<USER_TASK:>
Description:
def _merge_dict(self, global_dict, local_dict):
"""
Merges the two dictionaries together
:param global_dict: Global dictionary to be merged
:param local_dict: Local dictionary to be merged
:return: New merged dictionary with values shallow copied
""" |
# Local has higher priority than global. So iterate over local dict and merge into global if keys are overridden
global_dict = global_dict.copy()
for key in local_dict.keys():
if key in global_dict:
# Both local & global contains the same key. Let's do a merge.
global_dict[key] = self._do_merge(global_dict[key], local_dict[key])
else:
# Key is not in globals, just in local. Copy it over
global_dict[key] = local_dict[key]
return global_dict |
<SYSTEM_TASK:>
Returns the token type of the input.
<END_TASK>
<USER_TASK:>
Description:
def _token_of(self, input):
"""
Returns the token type of the input.
:param input: Input whose type is to be determined
:return TOKENS: Token type of the input
""" |
if isinstance(input, dict):
# Intrinsic functions are always dicts
if is_intrinsics(input):
# Intrinsic functions are handled *exactly* like a primitive type because
# they resolve to a primitive type when creating a stack with CloudFormation
return self.TOKEN.PRIMITIVE
else:
return self.TOKEN.DICT
elif isinstance(input, list):
return self.TOKEN.LIST
else:
return self.TOKEN.PRIMITIVE |
<SYSTEM_TASK:>
Is this a valid SAM template dictionary
<END_TASK>
<USER_TASK:>
Description:
def validate(template_dict, schema=None):
"""
Is this a valid SAM template dictionary
:param dict template_dict: Data to be validated
:param dict schema: Optional, dictionary containing JSON Schema representing SAM template
:return: Empty string if there are no validation errors in template
""" |
if not schema:
schema = SamTemplateValidator._read_schema()
validation_errors = ""
try:
jsonschema.validate(template_dict, schema)
except ValidationError as ex:
# Stringifying the exception will give us useful error message
validation_errors = str(ex)
# Swallowing expected exception here as our caller is expecting validation errors and
# not the valiation exception itself
pass
return validation_errors |
<SYSTEM_TASK:>
Generates a number within a reasonable range that might be expected for a flight.
<END_TASK>
<USER_TASK:>
Description:
def generate_car_price(location, days, age, car_type):
"""
Generates a number within a reasonable range that might be expected for a flight.
The price is fixed for a given pair of locations.
""" |
car_types = ['economy', 'standard', 'midsize', 'full size', 'minivan', 'luxury']
base_location_cost = 0
for i in range(len(location)):
base_location_cost += ord(location.lower()[i]) - 97
age_multiplier = 1.10 if age < 25 else 1
# Select economy is car_type is not found
if car_type not in car_types:
car_type = car_types[0]
return days * ((100 + base_location_cost) + ((car_types.index(car_type) * 50) * age_multiplier)) |
<SYSTEM_TASK:>
Generates a number within a reasonable range that might be expected for a hotel.
<END_TASK>
<USER_TASK:>
Description:
def generate_hotel_price(location, nights, room_type):
"""
Generates a number within a reasonable range that might be expected for a hotel.
The price is fixed for a pair of location and roomType.
""" |
room_types = ['queen', 'king', 'deluxe']
cost_of_living = 0
for i in range(len(location)):
cost_of_living += ord(location.lower()[i]) - 97
return nights * (100 + cost_of_living + (100 + room_types.index(room_type.lower()))) |
<SYSTEM_TASK:>
Performs dialog management and fulfillment for booking a hotel.
<END_TASK>
<USER_TASK:>
Description:
def book_hotel(intent_request):
"""
Performs dialog management and fulfillment for booking a hotel.
Beyond fulfillment, the implementation for this intent demonstrates the following:
1) Use of elicitSlot in slot validation and re-prompting
2) Use of sessionAttributes to pass information that can be used to guide conversation
""" |
location = try_ex(lambda: intent_request['currentIntent']['slots']['Location'])
checkin_date = try_ex(lambda: intent_request['currentIntent']['slots']['CheckInDate'])
nights = safe_int(try_ex(lambda: intent_request['currentIntent']['slots']['Nights']))
room_type = try_ex(lambda: intent_request['currentIntent']['slots']['RoomType'])
session_attributes = intent_request['sessionAttributes']
# Load confirmation history and track the current reservation.
reservation = json.dumps({
'ReservationType': 'Hotel',
'Location': location,
'RoomType': room_type,
'CheckInDate': checkin_date,
'Nights': nights
})
session_attributes['currentReservation'] = reservation
if intent_request['invocationSource'] == 'DialogCodeHook':
# Validate any slots which have been specified. If any are invalid, re-elicit for their value
validation_result = validate_hotel(intent_request['currentIntent']['slots'])
if not validation_result['isValid']:
slots = intent_request['currentIntent']['slots']
slots[validation_result['violatedSlot']] = None
return elicit_slot(
session_attributes,
intent_request['currentIntent']['name'],
slots,
validation_result['violatedSlot'],
validation_result['message']
)
# Otherwise, let native DM rules determine how to elicit for slots and prompt for confirmation. Pass price
# back in sessionAttributes once it can be calculated; otherwise clear any setting from sessionAttributes.
if location and checkin_date and nights and room_type:
# The price of the hotel has yet to be confirmed.
price = generate_hotel_price(location, nights, room_type)
session_attributes['currentReservationPrice'] = price
else:
try_ex(lambda: session_attributes.pop('currentReservationPrice'))
session_attributes['currentReservation'] = reservation
return delegate(session_attributes, intent_request['currentIntent']['slots'])
# Booking the hotel. In a real application, this would likely involve a call to a backend service.
logger.debug('bookHotel under={}'.format(reservation))
try_ex(lambda: session_attributes.pop('currentReservationPrice'))
try_ex(lambda: session_attributes.pop('currentReservation'))
session_attributes['lastConfirmedReservation'] = reservation
return close(
session_attributes,
'Fulfilled',
{
'contentType': 'PlainText',
'content': 'Thanks, I have placed your reservation. Please let me know if you would like to book a car '
'rental, or another hotel.'
}
) |
<SYSTEM_TASK:>
Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed
<END_TASK>
<USER_TASK:>
Description:
def to_cloudformation(self, **kwargs):
"""Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed
policy to the function's execution role, if such a role is provided.
:param dict kwargs: a dict containing the execution role generated for the function
:returns: a list of vanilla CloudFormation Resources, to which this pull event expands
:rtype: list
""" |
function = kwargs.get('function')
if not function:
raise TypeError("Missing required keyword argument: function")
resources = []
lambda_eventsourcemapping = LambdaEventSourceMapping(self.logical_id)
resources.append(lambda_eventsourcemapping)
try:
# Name will not be available for Alias resources
function_name_or_arn = function.get_runtime_attr("name")
except NotImplementedError:
function_name_or_arn = function.get_runtime_attr("arn")
if not self.Stream and not self.Queue:
raise InvalidEventException(
self.relative_id, "No Queue (for SQS) or Stream (for Kinesis or DynamoDB) provided.")
if self.Stream and not self.StartingPosition:
raise InvalidEventException(
self.relative_id, "StartingPosition is required for Kinesis and DynamoDB.")
lambda_eventsourcemapping.FunctionName = function_name_or_arn
lambda_eventsourcemapping.EventSourceArn = self.Stream or self.Queue
lambda_eventsourcemapping.StartingPosition = self.StartingPosition
lambda_eventsourcemapping.BatchSize = self.BatchSize
lambda_eventsourcemapping.Enabled = self.Enabled
if 'Condition' in function.resource_attributes:
lambda_eventsourcemapping.set_resource_attribute('Condition', function.resource_attributes['Condition'])
if 'role' in kwargs:
self._link_policy(kwargs['role'])
return resources |
<SYSTEM_TASK:>
If this source triggers a Lambda function whose execution role is auto-generated by SAM, add the
<END_TASK>
<USER_TASK:>
Description:
def _link_policy(self, role):
"""If this source triggers a Lambda function whose execution role is auto-generated by SAM, add the
appropriate managed policy to this Role.
:param model.iam.IAMROle role: the execution role generated for the function
""" |
policy_arn = self.get_policy_arn()
if role is not None and policy_arn not in role.ManagedPolicyArns:
role.ManagedPolicyArns.append(policy_arn) |
<SYSTEM_TASK:>
Method to read default values for template parameters and merge with user supplied values.
<END_TASK>
<USER_TASK:>
Description:
def add_default_parameter_values(self, sam_template):
"""
Method to read default values for template parameters and merge with user supplied values.
Example:
If the template contains the following parameters defined
Parameters:
Param1:
Type: String
Default: default_value
Param2:
Type: String
Default: default_value
And, the user explicitly provided the following parameter values:
{
Param2: "new value"
}
then, this method will grab default value for Param1 and return the following result:
{
Param1: "default_value",
Param2: "new value"
}
:param dict sam_template: SAM template
:param dict parameter_values: Dictionary of parameter values provided by the user
:return dict: Merged parameter values
""" |
parameter_definition = sam_template.get("Parameters", None)
if not parameter_definition or not isinstance(parameter_definition, dict):
return self.parameter_values
for param_name, value in parameter_definition.items():
if param_name not in self.parameter_values and isinstance(value, dict) and "Default" in value:
self.parameter_values[param_name] = value["Default"] |
<SYSTEM_TASK:>
Add this deployment preference to the collection
<END_TASK>
<USER_TASK:>
Description:
def add(self, logical_id, deployment_preference_dict):
"""
Add this deployment preference to the collection
:raise ValueError if an existing logical id already exists in the _resource_preferences
:param logical_id: logical id of the resource where this deployment preference applies
:param deployment_preference_dict: the input SAM template deployment preference mapping
""" |
if logical_id in self._resource_preferences:
raise ValueError("logical_id {logical_id} previously added to this deployment_preference_collection".format(
logical_id=logical_id))
self._resource_preferences[logical_id] = DeploymentPreference.from_dict(logical_id, deployment_preference_dict) |
<SYSTEM_TASK:>
If we wanted to initialize the session to have some attributes we could
<END_TASK>
<USER_TASK:>
Description:
def get_welcome_response():
""" If we wanted to initialize the session to have some attributes we could
add those here
""" |
session_attributes = {}
card_title = "Welcome"
speech_output = "Welcome to the Alexa Skills Kit sample. " \
"Please tell me your favorite color by saying, " \
"my favorite color is red"
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = "Please tell me your favorite color by saying, " \
"my favorite color is red."
should_end_session = False
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session)) |
<SYSTEM_TASK:>
Sets the color in the session and prepares the speech to reply to the
<END_TASK>
<USER_TASK:>
Description:
def set_color_in_session(intent, session):
""" Sets the color in the session and prepares the speech to reply to the
user.
""" |
card_title = intent['name']
session_attributes = {}
should_end_session = False
if 'Color' in intent['slots']:
favorite_color = intent['slots']['Color']['value']
session_attributes = create_favorite_color_attributes(favorite_color)
speech_output = "I now know your favorite color is " + \
favorite_color + \
". You can ask me your favorite color by saying, " \
"what's my favorite color?"
reprompt_text = "You can ask me your favorite color by saying, " \
"what's my favorite color?"
else:
speech_output = "I'm not sure what your favorite color is. " \
"Please try again."
reprompt_text = "I'm not sure what your favorite color is. " \
"You can tell me your favorite color by saying, " \
"my favorite color is red."
return build_response(session_attributes, build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session)) |
<SYSTEM_TASK:>
Called when the user specifies an intent for this skill
<END_TASK>
<USER_TASK:>
Description:
def on_intent(intent_request, session):
""" Called when the user specifies an intent for this skill """ |
print("on_intent requestId=" + intent_request['requestId'] +
", sessionId=" + session['sessionId'])
intent = intent_request['intent']
intent_name = intent_request['intent']['name']
# Dispatch to your skill's intent handlers
if intent_name == "MyColorIsIntent":
return set_color_in_session(intent, session)
elif intent_name == "WhatsMyColorIntent":
return get_color_from_session(intent, session)
elif intent_name == "AMAZON.HelpIntent":
return get_welcome_response()
elif intent_name == "AMAZON.CancelIntent" or intent_name == "AMAZON.StopIntent":
return handle_session_end_request()
else:
raise ValueError("Invalid intent") |
<SYSTEM_TASK:>
Generate and return a hash of data that can be used as suffix of logicalId
<END_TASK>
<USER_TASK:>
Description:
def get_hash(self, length=HASH_LENGTH):
"""
Generate and return a hash of data that can be used as suffix of logicalId
:return: Hash of data if it was present
:rtype string
""" |
data_hash = ""
if not self.data_str:
return data_hash
encoded_data_str = self.data_str
if sys.version_info.major == 2:
# In Py2, only unicode needs to be encoded.
if isinstance(self.data_str, unicode):
encoded_data_str = self.data_str.encode('utf-8')
else:
# data_str should always be unicode on python 3
encoded_data_str = self.data_str.encode('utf-8')
data_hash = hashlib.sha1(encoded_data_str).hexdigest()
return data_hash[:length] |
<SYSTEM_TASK:>
Stable, platform & language-independent stringification of a data with basic Python type.
<END_TASK>
<USER_TASK:>
Description:
def _stringify(self, data):
"""
Stable, platform & language-independent stringification of a data with basic Python type.
We use JSON to dump a string instead of `str()` method in order to be language independent.
:param data: Data to be stringified. If this is one of JSON native types like string, dict, array etc, it will
be properly serialized. Otherwise this method will throw a TypeError for non-JSON serializable
objects
:return: string representation of the dictionary
:rtype string
""" |
if isinstance(data, string_types):
return data
# Get the most compact dictionary (separators) and sort the keys recursively to get a stable output
return json.dumps(data, separators=(',', ':'), sort_keys=True) |
<SYSTEM_TASK:>
Add the information that resource with given `logical_id` supports the given `property`, and that a reference
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Transforms the SAM defined Tags into the form CloudFormation is expecting.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Gets the name of the partition given the region name. If region name is not provided, this method will
<END_TASK>
<USER_TASK:>
Description:
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" |
<SYSTEM_TASK:>
Returns True if this Swagger has the given path and optional method
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Returns true if the given method contains a valid method definition.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Returns the swagger contents of the given method. This checks to see if a conditional block
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Adds aws_proxy APIGW integration to the given path+method.
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Add CORS configuration to this path. Specifically, we will add a OPTIONS response config to the Swagger that
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Returns a Swagger snippet containing configuration for OPTIONS HTTP Method to configure CORS.
<END_TASK>
<USER_TASK:>
Description:
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
}
}
} |
<SYSTEM_TASK:>
Add Authorizer definitions to the securityDefinitions part of Swagger.
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Add Gateway Response definitions to Swagger.
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Checks if the input data is a Swagger document
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Returns a lower case, normalized version of HTTP Method. It also know how to handle API Gateway specific methods
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Returns a validator function that succeeds only for inputs of the provided valid_type.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Returns a validator function that succeeds only if the input is a list, and each item in the list passes as input
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Returns a validator function that succeeds only if the input is a dict, and each key and value in the dict passes
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Returns a validator function that succeeds only if the input passes at least one of the provided validators.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
With the given values for each parameter, this method will return a policy statement that can be used
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Checks if the given input contains values for all parameters used by this template
<END_TASK>
<USER_TASK:>
Description:
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())) |
<SYSTEM_TASK:>
Parses the input and returns an instance of this class.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Register a plugin. New plugins are added to the end of the plugins list.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Translates the SAM manifest provided in the and returns the translation to CloudFormation.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Hook method that gets called before the SAM template is processed.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Method to return a dictionary of API Events on the function
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Get API logical id from API event properties.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Add top-level template condition that combines the given list of conditions.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Add conditions to implicit API paths if necessary.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Generate valid condition logical id from the given API logical id and swagger resource path.
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Sets up the resource such that it will triggers a re-deployment when Swagger changes
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Read at most amt bytes from the stream.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Determines whether or not the on_before_transform_template event can process this application
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Method that handles the get_application API call to the serverless application repo
<END_TASK>
<USER_TASK:>
Description:
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'} |
<SYSTEM_TASK:>
Method that handles the create_cloud_formation_template API call to the serverless application repo
<END_TASK>
<USER_TASK:>
Description:
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'])) |
<SYSTEM_TASK:>
Checks a dictionary to make sure it has a specific key. If it does not, an
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Hook method that gets called after the template is processed
<END_TASK>
<USER_TASK:>
Description:
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.") |
<SYSTEM_TASK:>
Handles the response from the SAR service call
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Handles service calls and exception management for service calls
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Iterate over all resources within the SAM template, optionally filtering by type
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Adds the resource to dictionary with given logical Id. It will overwrite, if the logicalId is already used.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Gets the resource at the given logicalId if present
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins,
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Loads the SAM resources from the given SAM manifest, replaces them with their corresponding
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Validates that the provided logical id is an alphanumeric string.
<END_TASK>
<USER_TASK:>
Description:
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.") |
<SYSTEM_TASK:>
Validates that the provided resource dict contains the correct Type string, and the required Properties dict.
<END_TASK>
<USER_TASK:>
Description:
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.") |
<SYSTEM_TASK:>
Generates the resource dict for this Resource, the value associated with the logical id in a CloudFormation
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Validates that the required properties for this Resource have been populated, and that all properties have
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Sets attributes on resource. Resource attributes are top-level entries of a CloudFormation resource
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Gets the resource attribute if available
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Returns a CloudFormation construct that provides value for this attribute. If the resource does not provide
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Returns the Resource class corresponding to the 'Type' key in the given resource dict.
<END_TASK>
<USER_TASK:>
Description:
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']] |
<SYSTEM_TASK:>
Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons.
<END_TASK>
<USER_TASK:>
Description:
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
}]
} |
<SYSTEM_TASK:>
Helper function which in a full implementation would feed into a backend API to provide query schedule availability.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Helper function to return the windows of availability of the given duration, when provided a set of 30 minute windows.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Build a string eliciting for a possible time slot among at least two availabilities.
<END_TASK>
<USER_TASK:>
Description:
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])) |
<SYSTEM_TASK:>
Build a list of potential options for a given slot, to be used in responseCard generation.
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single
<END_TASK>
<USER_TASK:>
Description:
def is_instrinsic(input):
"""
Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single
key that is the name of the intrinsics.
:param input: Input value to check if it is an intrinsic
:return: True, if yes
""" |
if input is not None \
and isinstance(input, dict) \
and len(input) == 1:
key = list(input.keys())[0]
return key == "Ref" or key == "Condition" or key.startswith("Fn::")
return False |
<SYSTEM_TASK:>
Validates that the input dictionary contains only one key and is of the given intrinsic_name
<END_TASK>
<USER_TASK:>
Description:
def can_handle(self, input_dict):
"""
Validates that the input dictionary contains only one key and is of the given intrinsic_name
:param input_dict: Input dictionary representing the intrinsic function
:return: True if it matches expected structure, False otherwise
""" |
return input_dict is not None \
and isinstance(input_dict, dict) \
and len(input_dict) == 1 \
and self.intrinsic_name in input_dict |
<SYSTEM_TASK:>
Splits a resource reference of structure "LogicalId.Property" and returns the "LogicalId" and "Property"
<END_TASK>
<USER_TASK:>
Description:
def _parse_resource_reference(cls, ref_value):
"""
Splits a resource reference of structure "LogicalId.Property" and returns the "LogicalId" and "Property"
separately.
:param string ref_value: Input reference value which *may* contain the structure "LogicalId.Property"
:return string, string: Returns two values - logical_id, property. If the input does not contain the structure,
then both `logical_id` and property will be None
""" |
no_result = (None, None)
if not isinstance(ref_value, string_types):
return no_result
splits = ref_value.split(cls._resource_ref_separator, 1)
# Either there is no 'dot' (or) one of the values is empty string (Ex: when you split "LogicalId.")
if len(splits) != 2 or not all(splits):
return no_result
return splits[0], splits[1] |
<SYSTEM_TASK:>
Resolves references that are present in the parameters and returns the value. If it is not in parameters,
<END_TASK>
<USER_TASK:>
Description:
def resolve_parameter_refs(self, input_dict, parameters):
"""
Resolves references that are present in the parameters and returns the value. If it is not in parameters,
this method simply returns the input unchanged.
:param input_dict: Dictionary representing the Ref function. Must contain only one key and it should be "Ref".
Ex: {Ref: "foo"}
:param parameters: Dictionary of parameter values for resolution
:return:
""" |
if not self.can_handle(input_dict):
return input_dict
param_name = input_dict[self.intrinsic_name]
if not isinstance(param_name, string_types):
return input_dict
if param_name in parameters:
return parameters[param_name]
else:
return input_dict |
<SYSTEM_TASK:>
Resolves references to some property of a resource. These are runtime properties which can't be converted
<END_TASK>
<USER_TASK:>
Description:
def resolve_resource_refs(self, input_dict, supported_resource_refs):
"""
Resolves references to some property of a resource. These are runtime properties which can't be converted
to a value here. Instead we output another reference that will more actually resolve to the value when
executed via CloudFormation
Example:
{"Ref": "LogicalId.Property"} => {"Ref": "SomeOtherLogicalId"}
:param dict input_dict: Dictionary representing the Ref function to be resolved.
:param samtranslator.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of
an `SupportedResourceReferences` object that contain value of the property.
:return dict: Dictionary with resource references resolved.
""" |
if not self.can_handle(input_dict):
return input_dict
ref_value = input_dict[self.intrinsic_name]
logical_id, property = self._parse_resource_reference(ref_value)
# ref_value could not be parsed
if not logical_id:
return input_dict
resolved_value = supported_resource_refs.get(logical_id, property)
if not resolved_value:
return input_dict
return {
self.intrinsic_name: resolved_value
} |
<SYSTEM_TASK:>
Handles resolving replacements in the Sub action based on the handler that is passed as an input.
<END_TASK>
<USER_TASK:>
Description:
def _handle_sub_action(self, input_dict, handler):
"""
Handles resolving replacements in the Sub action based on the handler that is passed as an input.
:param input_dict: Dictionary to be resolved
:param supported_values: One of several different objects that contain the supported values that
need to be changed. See each method above for specifics on these objects.
:param handler: handler that is specific to each implementation.
:return: Resolved value of the Sub dictionary
""" |
if not self.can_handle(input_dict):
return input_dict
key = self.intrinsic_name
sub_value = input_dict[key]
input_dict[key] = self._handle_sub_value(sub_value, handler)
return input_dict |
<SYSTEM_TASK:>
Resolves the function and returns the updated dictionary
<END_TASK>
<USER_TASK:>
Description:
def _get_resolved_dictionary(self, input_dict, key, resolved_value, remaining):
"""
Resolves the function and returns the updated dictionary
:param input_dict: Dictionary to be resolved
:param key: Name of this intrinsic.
:param resolved_value: Resolved or updated value for this action.
:param remaining: Remaining sections for the GetAtt action.
""" |
if resolved_value:
# We resolved to a new resource logicalId. Use this as the first element and keep remaining elements intact
# This is the new value of Fn::GetAtt
input_dict[key] = [resolved_value] + remaining
return input_dict |
<SYSTEM_TASK:>
Constructs and returns the ApiGateway RestApi.
<END_TASK>
<USER_TASK:>
Description:
def _construct_rest_api(self):
"""Constructs and returns the ApiGateway RestApi.
:returns: the RestApi to which this SAM Api corresponds
:rtype: model.apigateway.ApiGatewayRestApi
""" |
rest_api = ApiGatewayRestApi(self.logical_id, depends_on=self.depends_on, attributes=self.resource_attributes)
rest_api.BinaryMediaTypes = self.binary_media
rest_api.MinimumCompressionSize = self.minimum_compression_size
if self.endpoint_configuration:
self._set_endpoint_configuration(rest_api, self.endpoint_configuration)
elif not RegionConfiguration.is_apigw_edge_configuration_supported():
# Since this region does not support EDGE configuration, we explicitly set the endpoint type
# to Regional which is the only supported config.
self._set_endpoint_configuration(rest_api, "REGIONAL")
if self.definition_uri and self.definition_body:
raise InvalidResourceException(self.logical_id,
"Specify either 'DefinitionUri' or 'DefinitionBody' property and not both")
self._add_cors()
self._add_auth()
self._add_gateway_responses()
if self.definition_uri:
rest_api.BodyS3Location = self._construct_body_s3_dict()
elif self.definition_body:
rest_api.Body = self.definition_body
if self.name:
rest_api.Name = self.name
return rest_api |
<SYSTEM_TASK:>
Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property.
<END_TASK>
<USER_TASK:>
Description:
def _construct_body_s3_dict(self):
"""Constructs the RestApi's `BodyS3Location property`_, from the SAM Api's DefinitionUri property.
:returns: a BodyS3Location dict, containing the S3 Bucket, Key, and Version of the Swagger definition
:rtype: dict
""" |
if isinstance(self.definition_uri, dict):
if not self.definition_uri.get("Bucket", None) or not self.definition_uri.get("Key", None):
# DefinitionUri is a dictionary but does not contain Bucket or Key property
raise InvalidResourceException(self.logical_id,
"'DefinitionUri' requires Bucket and Key properties to be specified")
s3_pointer = self.definition_uri
else:
# DefinitionUri is a string
s3_pointer = parse_s3_uri(self.definition_uri)
if s3_pointer is None:
raise InvalidResourceException(self.logical_id,
'\'DefinitionUri\' is not a valid S3 Uri of the form '
'"s3://bucket/key" with optional versionId query parameter.')
body_s3 = {
'Bucket': s3_pointer['Bucket'],
'Key': s3_pointer['Key']
}
if 'Version' in s3_pointer:
body_s3['Version'] = s3_pointer['Version']
return body_s3 |
<SYSTEM_TASK:>
Constructs and returns the ApiGateway Deployment.
<END_TASK>
<USER_TASK:>
Description:
def _construct_deployment(self, rest_api):
"""Constructs and returns the ApiGateway Deployment.
:param model.apigateway.ApiGatewayRestApi rest_api: the RestApi for this Deployment
:returns: the Deployment to which this SAM Api corresponds
:rtype: model.apigateway.ApiGatewayDeployment
""" |
deployment = ApiGatewayDeployment(self.logical_id + 'Deployment',
attributes=self.passthrough_resource_attributes)
deployment.RestApiId = rest_api.get_runtime_attr('rest_api_id')
deployment.StageName = 'Stage'
return deployment |
<SYSTEM_TASK:>
Constructs and returns the ApiGateway Stage.
<END_TASK>
<USER_TASK:>
Description:
def _construct_stage(self, deployment, swagger):
"""Constructs and returns the ApiGateway Stage.
:param model.apigateway.ApiGatewayDeployment deployment: the Deployment for this Stage
:returns: the Stage to which this SAM Api corresponds
:rtype: model.apigateway.ApiGatewayStage
""" |
# If StageName is some intrinsic function, then don't prefix the Stage's logical ID
# This will NOT create duplicates because we allow only ONE stage per API resource
stage_name_prefix = self.stage_name if isinstance(self.stage_name, string_types) else ""
stage = ApiGatewayStage(self.logical_id + stage_name_prefix + 'Stage',
attributes=self.passthrough_resource_attributes)
stage.RestApiId = ref(self.logical_id)
stage.update_deployment_ref(deployment.logical_id)
stage.StageName = self.stage_name
stage.CacheClusterEnabled = self.cache_cluster_enabled
stage.CacheClusterSize = self.cache_cluster_size
stage.Variables = self.variables
stage.MethodSettings = self.method_settings
stage.AccessLogSetting = self.access_log_setting
stage.CanarySetting = self.canary_setting
stage.TracingEnabled = self.tracing_enabled
if swagger is not None:
deployment.make_auto_deployable(stage, swagger)
return stage |
<SYSTEM_TASK:>
Add Auth configuration to the Swagger file, if necessary
<END_TASK>
<USER_TASK:>
Description:
def _add_auth(self):
"""
Add Auth configuration to the Swagger file, if necessary
""" |
if not self.auth:
return
if self.auth and not self.definition_body:
raise InvalidResourceException(self.logical_id,
"Auth works only with inline Swagger specified in "
"'DefinitionBody' property")
# Make sure keys in the dict are recognized
if not all(key in AuthProperties._fields for key in self.auth.keys()):
raise InvalidResourceException(
self.logical_id, "Invalid value for 'Auth' property")
if not SwaggerEditor.is_valid(self.definition_body):
raise InvalidResourceException(self.logical_id, "Unable to add Auth configuration because "
"'DefinitionBody' does not contain a valid Swagger")
swagger_editor = SwaggerEditor(self.definition_body)
auth_properties = AuthProperties(**self.auth)
authorizers = self._get_authorizers(auth_properties.Authorizers, auth_properties.DefaultAuthorizer)
if authorizers:
swagger_editor.add_authorizers(authorizers)
self._set_default_authorizer(swagger_editor, authorizers, auth_properties.DefaultAuthorizer)
# Assign the Swagger back to template
self.definition_body = swagger_editor.swagger |
<SYSTEM_TASK:>
Add Gateway Response configuration to the Swagger file, if necessary
<END_TASK>
<USER_TASK:>
Description:
def _add_gateway_responses(self):
"""
Add Gateway Response configuration to the Swagger file, if necessary
""" |
if not self.gateway_responses:
return
if self.gateway_responses and not self.definition_body:
raise InvalidResourceException(
self.logical_id, "GatewayResponses works only with inline Swagger specified in "
"'DefinitionBody' property")
# Make sure keys in the dict are recognized
for responses_key, responses_value in self.gateway_responses.items():
for response_key in responses_value.keys():
if response_key not in GatewayResponseProperties:
raise InvalidResourceException(
self.logical_id,
"Invalid property '{}' in 'GatewayResponses' property '{}'".format(response_key, responses_key))
if not SwaggerEditor.is_valid(self.definition_body):
raise InvalidResourceException(
self.logical_id, "Unable to add Auth configuration because "
"'DefinitionBody' does not contain a valid Swagger")
swagger_editor = SwaggerEditor(self.definition_body)
gateway_responses = {}
for response_type, response in self.gateway_responses.items():
gateway_responses[response_type] = ApiGatewayResponse(
api_logical_id=self.logical_id,
response_parameters=response.get('ResponseParameters', {}),
response_templates=response.get('ResponseTemplates', {}),
status_code=response.get('StatusCode', None)
)
if gateway_responses:
swagger_editor.add_gateway_responses(gateway_responses)
# Assign the Swagger back to template
self.definition_body = swagger_editor.swagger |
<SYSTEM_TASK:>
Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function.
<END_TASK>
<USER_TASK:>
Description:
def _get_permission(self, authorizer_name, authorizer_lambda_function_arn):
"""Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function.
:returns: the permission resource
:rtype: model.lambda_.LambdaPermission
""" |
rest_api = ApiGatewayRestApi(self.logical_id, depends_on=self.depends_on, attributes=self.resource_attributes)
api_id = rest_api.get_runtime_attr('rest_api_id')
partition = ArnGenerator.get_partition_name()
resource = '${__ApiId__}/authorizers/*'
source_arn = fnSub(ArnGenerator.generate_arn(partition=partition, service='execute-api', resource=resource),
{"__ApiId__": api_id})
lambda_permission = LambdaPermission(self.logical_id + authorizer_name + 'AuthorizerPermission',
attributes=self.passthrough_resource_attributes)
lambda_permission.Action = 'lambda:invokeFunction'
lambda_permission.FunctionName = authorizer_lambda_function_arn
lambda_permission.Principal = 'apigateway.amazonaws.com'
lambda_permission.SourceArn = source_arn
return lambda_permission |
<SYSTEM_TASK:>
Returns the Lambda function, role, and event resources to which this SAM Function corresponds.
<END_TASK>
<USER_TASK:>
Description:
def to_cloudformation(self, **kwargs):
"""Returns the Lambda function, role, and event resources to which this SAM Function corresponds.
:param dict kwargs: already-converted resources that may need to be modified when converting this \
macro to pure CloudFormation
:returns: a list of vanilla CloudFormation Resources, to which this Function expands
:rtype: list
""" |
resources = []
intrinsics_resolver = kwargs["intrinsics_resolver"]
if self.DeadLetterQueue:
self._validate_dlq()
lambda_function = self._construct_lambda_function()
resources.append(lambda_function)
lambda_alias = None
if self.AutoPublishAlias:
alias_name = self._get_resolved_alias_name("AutoPublishAlias", self.AutoPublishAlias, intrinsics_resolver)
lambda_version = self._construct_version(lambda_function, intrinsics_resolver=intrinsics_resolver)
lambda_alias = self._construct_alias(alias_name, lambda_function, lambda_version)
resources.append(lambda_version)
resources.append(lambda_alias)
if self.DeploymentPreference:
self._validate_deployment_preference_and_add_update_policy(kwargs.get('deployment_preference_collection',
None),
lambda_alias, intrinsics_resolver)
managed_policy_map = kwargs.get('managed_policy_map', {})
if not managed_policy_map:
raise Exception('Managed policy map is empty, but should not be.')
execution_role = None
if lambda_function.Role is None:
execution_role = self._construct_role(managed_policy_map)
lambda_function.Role = execution_role.get_runtime_attr('arn')
resources.append(execution_role)
try:
resources += self._generate_event_resources(lambda_function, execution_role, kwargs['event_resources'],
lambda_alias=lambda_alias)
except InvalidEventException as e:
raise InvalidResourceException(self.logical_id, e.message)
return resources |
<SYSTEM_TASK:>
Constructs a Lambda execution role based on this SAM function's Policies property.
<END_TASK>
<USER_TASK:>
Description:
def _construct_role(self, managed_policy_map):
"""Constructs a Lambda execution role based on this SAM function's Policies property.
:returns: the generated IAM Role
:rtype: model.iam.IAMRole
""" |
execution_role = IAMRole(self.logical_id + 'Role', attributes=self.get_passthrough_resource_attributes())
execution_role.AssumeRolePolicyDocument = IAMRolePolicies.lambda_assume_role_policy()
managed_policy_arns = [ArnGenerator.generate_aws_managed_policy_arn('service-role/AWSLambdaBasicExecutionRole')]
if self.Tracing:
managed_policy_arns.append(ArnGenerator.generate_aws_managed_policy_arn('AWSXrayWriteOnlyAccess'))
function_policies = FunctionPolicies({"Policies": self.Policies},
# No support for policy templates in the "core"
policy_template_processor=None)
policy_documents = []
if self.DeadLetterQueue:
policy_documents.append(IAMRolePolicies.dead_letter_queue_policy(
self.dead_letter_queue_policy_actions[self.DeadLetterQueue['Type']],
self.DeadLetterQueue['TargetArn']))
for index, policy_entry in enumerate(function_policies.get()):
if policy_entry.type is PolicyTypes.POLICY_STATEMENT:
policy_documents.append({
'PolicyName': execution_role.logical_id + 'Policy' + str(index),
'PolicyDocument': policy_entry.data
})
elif policy_entry.type is PolicyTypes.MANAGED_POLICY:
# There are three options:
# Managed Policy Name (string): Try to convert to Managed Policy ARN
# Managed Policy Arn (string): Insert it directly into the list
# Intrinsic Function (dict): Insert it directly into the list
#
# When you insert into managed_policy_arns list, de-dupe to prevent same ARN from showing up twice
#
policy_arn = policy_entry.data
if isinstance(policy_entry.data, string_types) and policy_entry.data in managed_policy_map:
policy_arn = managed_policy_map[policy_entry.data]
# De-Duplicate managed policy arns before inserting. Mainly useful
# when customer specifies a managed policy which is already inserted
# by SAM, such as AWSLambdaBasicExecutionRole
if policy_arn not in managed_policy_arns:
managed_policy_arns.append(policy_arn)
else:
# Policy Templates are not supported here in the "core"
raise InvalidResourceException(
self.logical_id,
"Policy at index {} in the 'Policies' property is not valid".format(index))
execution_role.ManagedPolicyArns = list(managed_policy_arns)
execution_role.Policies = policy_documents or None
execution_role.PermissionsBoundary = self.PermissionsBoundary
return execution_role |
<SYSTEM_TASK:>
Generates and returns the resources associated with this function's events.
<END_TASK>
<USER_TASK:>
Description:
def _generate_event_resources(self, lambda_function, execution_role, event_resources, lambda_alias=None):
"""Generates and returns the resources associated with this function's events.
:param model.lambda_.LambdaFunction lambda_function: generated Lambda function
:param iam.IAMRole execution_role: generated Lambda execution role
:param implicit_api: Global Implicit API resource where the implicit APIs get attached to, if necessary
:param implicit_api_stage: Global implicit API stage resource where implicit APIs get attached to, if necessary
:param event_resources: All the event sources associated with this Lambda function
:param model.lambda_.LambdaAlias lambda_alias: Optional Lambda Alias resource if we want to connect the
event sources to this alias
:returns: a list containing the function's event resources
:rtype: list
""" |
resources = []
if self.Events:
for logical_id, event_dict in self.Events.items():
try:
eventsource = self.event_resolver.resolve_resource_type(event_dict).from_dict(
lambda_function.logical_id + logical_id, event_dict, logical_id)
except TypeError as e:
raise InvalidEventException(logical_id, "{}".format(e))
kwargs = {
# When Alias is provided, connect all event sources to the alias and *not* the function
'function': lambda_alias or lambda_function,
'role': execution_role,
}
for name, resource in event_resources[logical_id].items():
kwargs[name] = resource
resources += eventsource.to_cloudformation(**kwargs)
return resources |
<SYSTEM_TASK:>
Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes.
<END_TASK>
<USER_TASK:>
Description:
def _construct_version(self, function, intrinsics_resolver):
"""Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes.
Old versions will not be deleted without a direct reference from the CloudFormation template.
:param model.lambda_.LambdaFunction function: Lambda function object that is being connected to a version
:param model.intrinsics.resolver.IntrinsicsResolver intrinsics_resolver: Class that can help resolve
references to parameters present in CodeUri. It is a common usecase to set S3Key of Code to be a
template parameter. Need to resolve the values otherwise we will never detect a change in Code dict
:return: Lambda function Version resource
""" |
code_dict = function.Code
if not code_dict:
raise ValueError("Lambda function code must be a valid non-empty dictionary")
if not intrinsics_resolver:
raise ValueError("intrinsics_resolver is required for versions creation")
# Resolve references to template parameters before creating hash. This will *not* resolve all intrinsics
# because we cannot resolve runtime values like Arn of a resource. For purposes of detecting changes, this
# is good enough. Here is why:
#
# When using intrinsic functions there are two cases when has must change:
# - Value of the template parameter changes
# - (or) LogicalId of a referenced resource changes ie. !GetAtt NewResource.Arn
#
# Later case will already change the hash because some value in the Code dictionary changes. We handle the
# first case by resolving references to template parameters. It is okay even if these references are
# present inside another intrinsic such as !Join. The resolver will replace the reference with the parameter's
# value and keep all other parts of !Join identical. This will still trigger a change in the hash.
code_dict = intrinsics_resolver.resolve_parameter_refs(code_dict)
# Construct the LogicalID of Lambda version by appending 10 characters of SHA of CodeUri. This is necessary
# to trigger creation of a new version every time code location changes. Since logicalId changes, CloudFormation
# will drop the old version and create a new one for us. We set a DeletionPolicy on the version resource to
# prevent CloudFormation from actually deleting the underlying version resource
#
# SHA Collisions: For purposes of triggering a new update, we are concerned about just the difference previous
# and next hashes. The chances that two subsequent hashes collide is fairly low.
prefix = "{id}Version".format(id=self.logical_id)
logical_id = logical_id_generator.LogicalIdGenerator(prefix, code_dict).gen()
attributes = self.get_passthrough_resource_attributes()
if attributes is None:
attributes = {}
attributes["DeletionPolicy"] = "Retain"
lambda_version = LambdaVersion(logical_id=logical_id, attributes=attributes)
lambda_version.FunctionName = function.get_runtime_attr('name')
lambda_version.Description = self.VersionDescription
return lambda_version |
<SYSTEM_TASK:>
Constructs a Lambda Alias for the given function and pointing to the given version
<END_TASK>
<USER_TASK:>
Description:
def _construct_alias(self, name, function, version):
"""Constructs a Lambda Alias for the given function and pointing to the given version
:param string name: Name of the alias
:param model.lambda_.LambdaFunction function: Lambda function object to associate the alias with
:param model.lambda_.LambdaVersion version: Lambda version object to associate the alias with
:return: Lambda alias object
:rtype model.lambda_.LambdaAlias
""" |
if not name:
raise InvalidResourceException(self.logical_id, "Alias name is required to create an alias")
logical_id = "{id}Alias{suffix}".format(id=function.logical_id, suffix=name)
alias = LambdaAlias(logical_id=logical_id, attributes=self.get_passthrough_resource_attributes())
alias.Name = name
alias.FunctionName = function.get_runtime_attr('name')
alias.FunctionVersion = version.get_runtime_attr("version")
return alias |
<SYSTEM_TASK:>
Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds.
<END_TASK>
<USER_TASK:>
Description:
def to_cloudformation(self, **kwargs):
"""Returns the API Gateway RestApi, Deployment, and Stage to which this SAM Api corresponds.
:param dict kwargs: already-converted resources that may need to be modified when converting this \
macro to pure CloudFormation
:returns: a list of vanilla CloudFormation Resources, to which this Function expands
:rtype: list
""" |
resources = []
api_generator = ApiGenerator(self.logical_id,
self.CacheClusterEnabled,
self.CacheClusterSize,
self.Variables,
self.depends_on,
self.DefinitionBody,
self.DefinitionUri,
self.Name,
self.StageName,
endpoint_configuration=self.EndpointConfiguration,
method_settings=self.MethodSettings,
binary_media=self.BinaryMediaTypes,
minimum_compression_size=self.MinimumCompressionSize,
cors=self.Cors,
auth=self.Auth,
gateway_responses=self.GatewayResponses,
access_log_setting=self.AccessLogSetting,
canary_setting=self.CanarySetting,
tracing_enabled=self.TracingEnabled,
resource_attributes=self.resource_attributes,
passthrough_resource_attributes=self.get_passthrough_resource_attributes())
rest_api, deployment, stage, permissions = api_generator.to_cloudformation()
resources.extend([rest_api, deployment, stage])
resources.extend(permissions)
return resources |
<SYSTEM_TASK:>
Adds tags to the stack if this resource is using the serverless app repo
<END_TASK>
<USER_TASK:>
Description:
def _get_application_tags(self):
"""Adds tags to the stack if this resource is using the serverless app repo
""" |
application_tags = {}
if isinstance(self.Location, dict):
if (self.APPLICATION_ID_KEY in self.Location.keys() and
self.Location[self.APPLICATION_ID_KEY] is not None):
application_tags[self._SAR_APP_KEY] = self.Location[self.APPLICATION_ID_KEY]
if (self.SEMANTIC_VERSION_KEY in self.Location.keys() and
self.Location[self.SEMANTIC_VERSION_KEY] is not None):
application_tags[self._SAR_SEMVER_KEY] = self.Location[self.SEMANTIC_VERSION_KEY]
return application_tags |
<SYSTEM_TASK:>
Returns the Lambda layer to which this SAM Layer corresponds.
<END_TASK>
<USER_TASK:>
Description:
def to_cloudformation(self, **kwargs):
"""Returns the Lambda layer to which this SAM Layer corresponds.
:param dict kwargs: already-converted resources that may need to be modified when converting this \
macro to pure CloudFormation
:returns: a list of vanilla CloudFormation Resources, to which this Function expands
:rtype: list
""" |
resources = []
# Append any CFN resources:
intrinsics_resolver = kwargs["intrinsics_resolver"]
resources.append(self._construct_lambda_layer(intrinsics_resolver))
return resources |
<SYSTEM_TASK:>
Sets the deletion policy on this resource. The default is 'Retain'.
<END_TASK>
<USER_TASK:>
Description:
def _get_retention_policy_value(self):
"""
Sets the deletion policy on this resource. The default is 'Retain'.
:return: value for the DeletionPolicy attribute.
""" |
if self.RetentionPolicy is None or self.RetentionPolicy.lower() == self.RETAIN.lower():
return self.RETAIN
elif self.RetentionPolicy.lower() == self.DELETE.lower():
return self.DELETE
elif self.RetentionPolicy.lower() not in self.retention_policy_options:
raise InvalidResourceException(self.logical_id,
"'{}' must be one of the following options: {}."
.format('RetentionPolicy', [self.RETAIN, self.DELETE])) |
<SYSTEM_TASK:>
Performs dialog management and fulfillment for ordering flowers.
<END_TASK>
<USER_TASK:>
Description:
def order_flowers(intent_request):
"""
Performs dialog management and fulfillment for ordering flowers.
Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action
in slot validation and re-prompting.
""" |
flower_type = get_slots(intent_request)["FlowerType"]
date = get_slots(intent_request)["PickupDate"]
time = get_slots(intent_request)["PickupTime"]
source = intent_request['invocationSource']
if source == 'DialogCodeHook':
# Perform basic validation on the supplied input slots.
# Use the elicitSlot dialog action to re-prompt for the first violation detected.
slots = get_slots(intent_request)
validation_result = validate_order_flowers(flower_type, date, time)
if not validation_result['isValid']:
slots[validation_result['violatedSlot']] = None
return elicit_slot(intent_request['sessionAttributes'],
intent_request['currentIntent']['name'],
slots,
validation_result['violatedSlot'],
validation_result['message'])
# Pass the price of the flowers back through session attributes to be used in various prompts defined
# on the bot model.
output_session_attributes = intent_request['sessionAttributes']
if flower_type is not None:
output_session_attributes['Price'] = len(flower_type) * 5 # Elegant pricing model
return delegate(output_session_attributes, get_slots(intent_request))
# Order the flowers, and rely on the goodbye message of the bot to define the message to the end user.
# In a real bot, this would likely involve a call to a backend service.
return close(intent_request['sessionAttributes'],
'Fulfilled',
{'contentType': 'PlainText',
'content': 'Thanks, your order for {} has been placed and will be ready for pickup by {} on {}'.format(flower_type, time, date)}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.