text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def debug(self, value): """ Turn on debug logging if necessary. :param value: Value of debug flag """
self._debug = value if self._debug: # Turn on debug logging logging.getLogger().setLevel(logging.DEBUG)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_project( location=None, runtime="nodejs", dependency_manager=None, output_dir=".", name='sam-sample-app', no_input=False): """Generates project usin...
template = None for mapping in list(itertools.chain(*(RUNTIME_DEP_TEMPLATE_MAPPING.values()))): if runtime in mapping['runtimes'] or any([r.startswith(runtime) for r in mapping['runtimes']]): if not dependency_manager: template = mapping['init_location'] br...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_utc(some_time): """ Convert the given date to UTC, if the date contains a timezone. Parameters some_time : datetime.datetime datetime object to convert to...
# Convert timezone aware objects to UTC if some_time.tzinfo and some_time.utcoffset(): some_time = some_time.astimezone(tzutc()) # Now that time is UTC, simply remove the timezone component. return some_time.replace(tzinfo=None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_date(date_string): """ Parse the given string as datetime object. This parser supports in almost any string formats. For relative times, like `10min ag...
parser_settings = { # Relative times like '10m ago' must subtract from the current UTC time. Without this setting, dateparser # will use current local time as the base for subtraction, but falsely assume it is a UTC time. Therefore # the time that dateparser returns will be a `datetime` ob...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def function_name(self): """ Returns name of the function to invoke. If no function identifier is provided, this method will return name of the only function fro...
if self._function_identifier: return self._function_identifier # Function Identifier is *not* provided. If there is only one function in the template, # default to it. all_functions = [f for f in self._function_provider.get_all()] if len(all_functions) == 1: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def local_lambda_runner(self): """ Returns an instance of the runner capable of running Lambda functions locally :return samcli.commands.local.lib.local_lambda.L...
layer_downloader = LayerDownloader(self._layer_cache_basedir, self.get_cwd()) image_builder = LambdaImage(layer_downloader, self._skip_pull_image, self._force_image_build) lambda_runtime = LambdaRuntime(self._container_ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stdout(self): """ Returns stream writer for stdout to output Lambda function logs to Returns ------- samcli.lib.utils.stream_writer.StreamWriter Stream write...
stream = self._log_file_handle if self._log_file_handle else osutils.stdout() return StreamWriter(stream, self._is_debugging)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stderr(self): """ Returns stream writer for stderr to output Lambda function errors to Returns ------- samcli.lib.utils.stream_writer.StreamWriter Stream wri...
stream = self._log_file_handle if self._log_file_handle else osutils.stderr() return StreamWriter(stream, self._is_debugging)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_cwd(self): """ Get the working directory. This is usually relative to the directory that contains the template. If a Docker volume location is specified,...
cwd = os.path.dirname(os.path.abspath(self._template_file)) if self._docker_volume_basedir: cwd = self._docker_volume_basedir return cwd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_env_vars_value(filename): """ If the user provided a file containing values of environment variables, this method will read the file and return its valu...
if not filename: return None # Try to read the file and parse it as JSON try: with open(filename, 'r') as fp: return json.load(fp) except Exception as ex: raise InvokeContextException("Could not read environment variables overrides ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_debug_context(debug_port, debug_args, debugger_path): """ Creates a DebugContext if the InvokeContext is in a debugging mode Parameters debug_port int P...
if debug_port and debugger_path: try: debugger = Path(debugger_path).resolve(strict=True) except OSError as error: if error.errno == errno.ENOENT: raise DebugContextException("'{}' could not be found.".format(debugger_path)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_payload(socket, payload_size): """ From the given socket, reads and yields payload of the given size. With sockets, we don't receive all data at once. ...
remaining = payload_size while remaining > 0: # Try and read as much as possible data = read(socket, remaining) if data is None: # ``read`` will terminate with an empty string. This is just a transient state where we didn't get any data continue if len...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_not_found(function_name): """ Creates a Lambda Service ResourceNotFound Response Parameters function_name str Name of the function that was requeste...
exception_tuple = LambdaErrorResponses.ResourceNotFoundException return BaseLocalService.service_response( LambdaErrorResponses._construct_error_response_body( LambdaErrorResponses.USER_ERROR, "Function not found: arn:aws:lambda:us-west-2:012345678901:functi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invalid_request_content(message): """ Creates a Lambda Service InvalidRequestContent Response Parameters message str Message to be added to the body of the r...
exception_tuple = LambdaErrorResponses.InvalidRequestContentException return BaseLocalService.service_response( LambdaErrorResponses._construct_error_response_body(LambdaErrorResponses.USER_ERROR, message), LambdaErrorResponses._construct_headers(exception_tuple[0]), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsupported_media_type(content_type): """ Creates a Lambda Service UnsupportedMediaType Response Parameters content_type str Content Type of the request that...
exception_tuple = LambdaErrorResponses.UnsupportedMediaTypeException return BaseLocalService.service_response( LambdaErrorResponses._construct_error_response_body(LambdaErrorResponses.USER_ERROR, "Unsupported content type: {}"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generic_service_exception(*args): """ Creates a Lambda Service Generic ServiceException Response Parameters args list List of arguments Flask passes to the m...
exception_tuple = LambdaErrorResponses.ServiceException return BaseLocalService.service_response( LambdaErrorResponses._construct_error_response_body(LambdaErrorResponses.SERVICE_ERROR, "ServiceException"), LambdaErrorResponses._construct_headers(exception_tuple[0]), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generic_path_not_found(*args): """ Creates a Lambda Service Generic PathNotFound Response Parameters args list List of arguments Flask passes to the method R...
exception_tuple = LambdaErrorResponses.PathNotFoundException return BaseLocalService.service_response( LambdaErrorResponses._construct_error_response_body( LambdaErrorResponses.LOCAL_SERVICE_ERROR, "PathNotFoundException"), LambdaErrorResponses._construct_header...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generic_method_not_allowed(*args): """ Creates a Lambda Service Generic MethodNotAllowed Response Parameters args list List of arguments Flask passes to the ...
exception_tuple = LambdaErrorResponses.MethodNotAllowedException return BaseLocalService.service_response( LambdaErrorResponses._construct_error_response_body(LambdaErrorResponses.LOCAL_SERVICE_ERROR, "MethodNotAllowedExceptio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_code_path(cwd, codeuri): """ Returns path to the function code resolved based on current working directory. Parameters cwd str Current working direct...
LOG.debug("Resolving code path. Cwd=%s, CodeUri=%s", cwd, codeuri) # First, let us figure out the current working directory. # If current working directory is not provided, then default to the directory where the CLI is running from if not cwd or cwd == PRESENT_DIR: cwd = os.getcwd() # Ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_path_to_flask(path): """ Converts a Path from an Api Gateway defined path to one that is accepted by Flask Examples: '/id/{id}' => '/id/<id>' '/{prox...
proxy_sub_path = APIGW_TO_FLASK_REGEX.sub(FLASK_CAPTURE_ALL_PATH, path) # Replace the '{' and '}' with '<' and '>' respectively return proxy_sub_path.replace(LEFT_BRACKET, LEFT_ANGLE_BRACKET).replace(RIGHT_BRACKET, RIGHT_ANGLE_BRACKET)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_path_to_api_gateway(path): """ Converts a Path from a Flask defined path to one that is accepted by Api Gateway Examples: '/id/<id>' => '/id/{id}' '/...
proxy_sub_path = FLASK_TO_APIGW_REGEX.sub(PROXY_PATH_PARAMS, path) # Replace the '<' and '>' with '{' and '}' respectively return proxy_sub_path.replace(LEFT_ANGLE_BRACKET, LEFT_BRACKET).replace(RIGHT_ANGLE_BRACKET, RIGHT_BRACKET)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_function_name(integration_uri): """ Gets the name of the function from the Integration URI ARN. This is a best effort service which returns None if funct...
arn = LambdaUri._get_function_arn(integration_uri) LOG.debug("Extracted Function ARN: %s", arn) return LambdaUri._get_function_name_from_arn(arn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_function_name_from_arn(function_arn): """ Given the integration ARN, extract the Lambda function name from the ARN. If there are stage variables, or oth...
if not function_arn: return None matches = re.match(LambdaUri._REGEX_GET_FUNCTION_NAME, function_arn) if not matches or not matches.groups(): LOG.debug("No Lambda function ARN defined for integration containing ARN %s", function_arn) return None gr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_event(event_file_name): """ Read the event JSON data from the given file. If no file is provided, read the event from stdin. :param string event_file_na...
if event_file_name == STDIN_FILE_NAME: # If event is empty, listen to stdin for event data until EOF LOG.info("Reading invoke payload from stdin (you can also pass it from file with --event)") # click.open_file knows to open stdin when filename is '-'. This is safer than manually opening stre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalize(template_dict): """ Normalize all Resources in the template with the Metadata Key on the resource. This method will mutate the template Parameters ...
resources = template_dict.get(RESOURCES_KEY, {}) for logical_id, resource in resources.items(): resource_metadata = resource.get(METADATA_KEY, {}) asset_path = resource_metadata.get(ASSET_PATH_METADATA_KEY) asset_property = resource_metadata.get(ASSET_PROPERTY_METAD...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _replace_property(property_key, property_value, resource, logical_id): """ Replace a property with an asset on a given resource This method will mutate the t...
if property_key and property_value: resource.get(PROPERTIES_KEY, {})[property_key] = property_value elif property_key or property_value: LOG.info("WARNING: Ignoring Metadata for Resource %s. Metadata contains only aws:asset:path or " "aws:assert:property but...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_commands(package_names): """ Extract the command name from package name. Last part of the module path is the command ie. if path is foo.bar.baz, then "b...
commands = {} for pkg_name in package_names: cmd_name = pkg_name.split('.')[-1] commands[cmd_name] = pkg_name return commands
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_command(self, ctx, cmd_name): """ Overrides method from ``click.MultiCommand`` that returns Click CLI object for given command name, if found. :param ctx...
if cmd_name not in self._commands: logger.error("Command %s not available", cmd_name) return pkg_name = self._commands[cmd_name] try: mod = importlib.import_module(pkg_name) except ImportError: logger.exception("Command '%s' is not confi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, output): """ Writes specified text to the underlying stream Parameters output bytes-like object Bytes to write """
self._stream.write(output) if self._auto_flush: self._stream.flush()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_workflow_config(runtime, code_dir, project_dir): """ Get a workflow config that corresponds to the runtime provided. This method examines contents of the...
selectors_by_runtime = { "python2.7": BasicWorkflowSelector(PYTHON_PIP_CONFIG), "python3.6": BasicWorkflowSelector(PYTHON_PIP_CONFIG), "python3.7": BasicWorkflowSelector(PYTHON_PIP_CONFIG), "nodejs4.3": BasicWorkflowSelector(NODEJS_NPM_CONFIG), "nodejs6.10": BasicWorkflowSe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def supports_build_in_container(config): """ Given a workflow config, this method provides a boolean on whether the workflow can run within a container or not. P...
def _key(c): return str(c.language) + str(c.dependency_manager) + str(c.application_framework) # This information could have beeen bundled inside the Workflow Config object. But we this way because # ultimately the workflow's implementation dictates whether it can run within a container or not. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_config(self, code_dir, project_dir): """ Finds a configuration by looking for a manifest in the given directories. Returns ------- samcli.lib.build.workf...
# Search for manifest first in code directory and then in the project directory. # Search order is important here because we want to prefer the manifest present within the code directory over # a manifest present in project directory. search_dirs = [code_dir, project_dir] LOG.d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intrinsics_multi_constructor(loader, tag_prefix, node): """ YAML constructor to parse CloudFormation intrinsics. This will return a dictionary with key being...
# Get the actual tag name excluding the first exclamation tag = node.tag[1:] # Some intrinsic functions doesn't support prefix "Fn::" prefix = "Fn::" if tag in ["Ref", "Condition"]: prefix = "" cfntag = prefix + tag if tag == "GetAtt" and isinstance(node.value, six.string_types)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def yaml_parse(yamlstr): """Parse a yaml string"""
try: # PyYAML doesn't support json as well as it should, so if the input # is actually just json it is better to parse it with the standard # json parser. return json.loads(yamlstr) except ValueError: yaml.SafeLoader.add_multi_constructor("!", intrinsics_multi_constructo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode(self, tags, encoding, values_to_sub): """ reads the encoding type from the event-mapping.json and determines whether a value needs encoding Parameters...
for tag in tags: if tags[tag].get(encoding) != "None": if tags[tag].get(encoding) == "url": values_to_sub[tag] = self.url_encode(values_to_sub[tag]) if tags[tag].get(encoding) == "base64": values_to_sub[tag] = self.base64_utf_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_event(self, service_name, event_type, values_to_sub): """ opens the event json, substitutes the values in, and returns the customized event json Par...
# set variables for easy calling tags = self.event_mapping[service_name][event_type]['tags'] values_to_sub = self.encode(tags, 'encoding', values_to_sub) # construct the path to the Events json file this_folder = os.path.dirname(os.path.abspath(__file__)) file_name = s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def underline(self, msg): """Underline the input"""
return click.style(msg, underline=True) if self.colorize else msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _color(self, msg, color): """Internal helper method to add colors to input"""
kwargs = {'fg': color} return click.style(msg, **kwargs) if self.colorize else msg
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_layer_version(is_defined_within_template, arn): """ Parses out the Layer version from the arn Parameters is_defined_within_template bool True if the...
if is_defined_within_template: return None try: _, layer_version = arn.rsplit(':', 1) layer_version = int(layer_version) except ValueError: raise InvalidLayerVersionArn(arn + " is an Invalid Layer Arn.") return layer_version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_layer_name(is_defined_within_template, arn): """ Computes a unique name based on the LayerVersion Arn Format: <Name of the LayerVersion>-<Version of...
# If the Layer is defined in the template, the arn will represent the LogicalId of the LayerVersion Resource, # which does not require creating a name based on the arn. if is_defined_within_template: return arn try: _, layer_name, layer_version = arn.rsplit(':'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mkdir_temp(mode=0o755): """ Context manager that makes a temporary directory and yields it name. Directory is deleted after the context exits Parameters mode...
temp_dir = None try: temp_dir = tempfile.mkdtemp() os.chmod(temp_dir, mode) yield temp_dir finally: if temp_dir: shutil.rmtree(temp_dir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_all(self, layers, force=False): """ Download a list of layers to the cache Parameters layers list(samcli.commands.local.lib.provider.Layer) List of ...
layer_dirs = [] for layer in layers: layer_dirs.append(self.download(layer, force)) return layer_dirs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download(self, layer, force=False): """ Download a given layer to the local cache. Parameters layer samcli.commands.local.lib.provider.Layer Layer representi...
if layer.is_defined_within_template: LOG.info("%s is a local Layer in the template", layer.name) layer.codeuri = resolve_code_path(self.cwd, layer.codeuri) return layer # disabling no-member due to https://github.com/PyCQA/pylint/issues/1660 layer_path = Pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fetch_layer_uri(self, layer): """ Fetch the Layer Uri based on the LayerVersion Arn Parameters layer samcli.commands.local.lib.provider.LayerVersion LayerVe...
try: layer_version_response = self.lambda_client.get_layer_version(LayerName=layer.layer_arn, VersionNumber=layer.version) except NoCredentialsError: raise CredentialsRequired("Layers require credentials t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _create_cache(layer_cache): """ Create the Cache directory if it does not exist. Parameters layer_cache Directory to where the layers should be cached Return...
Path(layer_cache).mkdir(mode=0o700, parents=True, exist_ok=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_valid(self): """ Runs the SAM Translator to determine if the template provided is valid. This is similar to running a ChangeSet in CloudFormation for a SA...
managed_policy_map = self.managed_policy_loader.load() sam_translator = Translator(managed_policy_map=managed_policy_map, sam_parser=self.sam_parser, plugins=[]) self._replace_local_codeuri() try: tem...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_to_s3_uri(property_key, resource_property_dict, s3_uri_value="s3://bucket/value"): """ Updates the 'property_key' in the 'resource_property_dict' to ...
uri_property = resource_property_dict.get(property_key, ".") # ignore if dict or already an S3 Uri if isinstance(uri_property, dict) or SamTemplateValidator.is_s3_uri(uri_property): return resource_property_dict[property_key] = s3_uri_value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formatter(self): """ Creates and returns a Formatter capable of nicely formatting Lambda function logs Returns ------- LogsFormatter """
formatter_chain = [ LambdaLogMsgFormatters.colorize_errors, # Format JSON "before" highlighting the keywords. Otherwise, JSON will be invalid from all the # ANSI color codes and fail to pretty print JSONMsgFormatter.format_json, KeywordHighlighter(s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_group_name(self): """ Name of the AWS CloudWatch Log Group that we will be querying. It generates the name based on the Lambda Function name and stack na...
function_id = self._function_name if self._stack_name: function_id = self._get_resource_id_from_stack(self._cfn_client, self._stack_name, self._function_name) LOG.debug("Function with LogicalId '%s' in stack '%s' resolves to actual physical ID '%s'", self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_time(time_str, property_name): """ Parse the time from the given string, convert to UTC, and return the datetime object Parameters time_str : str The ...
if not time_str: return parsed = parse_date(time_str) if not parsed: raise UserException("Unable to parse the time provided by '{}'".format(property_name)) return to_utc(parsed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_resource_id_from_stack(cfn_client, stack_name, logical_id): """ Given the LogicalID of a resource, call AWS CloudFormation to get physical ID of the res...
LOG.debug("Getting resource's PhysicalId from AWS CloudFormation stack. StackName=%s, LogicalId=%s", stack_name, logical_id) try: response = cfn_client.describe_stack_resource(StackName=stack_name, LogicalResourceId=logical_id) LOG.debug("Response from AWS C...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_template(template_dict, parameter_overrides=None): """ Given a SAM template dictionary, return a cleaned copy of the template where SAM plugins have been...
template_dict = template_dict or {} if template_dict: template_dict = SamTranslatorWrapper(template_dict).run_plugins() template_dict = SamBaseProvider._resolve_parameters(template_dict, parameter_overrides) ResourceMetadataNormalizer.normalize(template_dict) retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_parameters(template_dict, parameter_overrides): """ In the given template, apply parameter values to resolve intrinsic functions Parameters template...
parameter_values = SamBaseProvider._get_parameter_values(template_dict, parameter_overrides) supported_intrinsics = {action.intrinsic_name: action() for action in SamBaseProvider._SUPPORTED_INTRINSICS} # Intrinsics resolver will mutate the original template return IntrinsicsResolver(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_parameter_values(template_dict, parameter_overrides): """ Construct a final list of values for CloudFormation template parameters based on user-supplied...
default_values = SamBaseProvider._get_default_parameter_values(template_dict) # NOTE: Ordering of following statements is important. It makes sure that any user-supplied values # override the defaults parameter_values = {} parameter_values.update(SamBaseProvider._DEFAULT_PSEUD...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_posix_path(code_path): """ Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path. Parameters code_pat...
return re.sub("^([A-Za-z])+:", lambda match: posixpath.sep + match.group().replace(":", "").lower(), pathlib.PureWindowsPath(code_path).as_posix()) if os.name == "nt" else code_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_entry_point(runtime, debug_options=None): # pylint: disable=too-many-branches """ Returns the entry point for the container. The default value for the e...
if not debug_options: return None if runtime not in LambdaContainer._supported_runtimes(): raise DebuggingNotSupported( "Debugging is not currently supported for {}".format(runtime)) debug_port = debug_options.debug_port debug_args_list = [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_apis(self, resources): """ Extract all Implicit Apis (Apis defined through Serverless Function with an Api Event :param dict resources: Dictionary o...
# Some properties like BinaryMediaTypes, Cors are set once on the resource but need to be applied to each API. # For Implicit APIs, which are defined on the Function resource, these properties # are defined on a AWS::Serverless::Api resource with logical ID "ServerlessRestApi". Therefore, no m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _merge_apis(collector): """ Quite often, an API is defined both in Implicit and Explicit API definitions. In such cases, Implicit API definition wins because...
implicit_apis = [] explicit_apis = [] # Store implicit and explicit APIs separately in order to merge them later in the correct order # Implicit APIs are defined on a resource with logicalID ServerlessRestApi for logical_id, apis in collector: if logical_id == SamA...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _normalize_apis(apis): """ Normalize the APIs to use standard method name Parameters apis : list of samcli.commands.local.lib.provider.Api List of APIs to re...
result = list() for api in apis: for normalized_method in SamApiProvider._normalize_http_methods(api.method): # _replace returns a copy of the namedtuple. This is the official way of creating copies of namedtuple result.append(api._replace(method=normalized_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_apis_from_function(logical_id, function_resource, collector): """ Fetches a list of APIs configured for this SAM Function resource. Parameters logic...
resource_properties = function_resource.get("Properties", {}) serverless_function_events = resource_properties.get(SamApiProvider._FUNCTION_EVENT, {}) SamApiProvider._extract_apis_from_events(logical_id, serverless_function_events, collector)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _normalize_http_methods(http_method): """ Normalizes Http Methods. Api Gateway allows a Http Methods of ANY. This is a special verb to denote all supported H...
if http_method.upper() == 'ANY': for method in SamApiProvider._ANY_HTTP_METHODS: yield method.upper() else: yield http_method.upper()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_apis(self, logical_id, apis): """ Stores the given APIs tagged under the given logicalId Parameters logical_id : str LogicalId of the AWS::Serverless::Ap...
properties = self._get_properties(logical_id) properties.apis.extend(apis)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_binary_media_types(self, logical_id, binary_media_types): """ Stores the binary media type configuration for the API with given logical ID Parameters log...
properties = self._get_properties(logical_id) binary_media_types = binary_media_types or [] for value in binary_media_types: normalized_value = self._normalize_binary_media_type(value) # If the value is not supported, then just skip it. if normalized_value:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_apis_with_config(self, logical_id): """ Returns the list of APIs in this resource along with other extra configuration such as binary media types, cors ...
properties = self._get_properties(logical_id) # These configs need to be applied to each API binary_media = sorted(list(properties.binary_media_types)) # Also sort the list to keep the ordering stable cors = properties.cors result = [] for api in properties.apis: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_properties(self, logical_id): """ Returns the properties of resource with given logical ID. If a resource is not found, then it returns an empty data. P...
if logical_id not in self.by_resource: self.by_resource[logical_id] = self.Properties(apis=[], # Use a set() to be able to easily de-dupe binary_media_types=set(), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unzip_file(filepath): """ Helper method to unzip a file to a temporary directory :param string filepath: Absolute path to this file :return string: Path to ...
temp_dir = tempfile.mkdtemp() if os.name == 'posix': os.chmod(temp_dir, 0o755) LOG.info("Decompressing %s", filepath) unzip(filepath, temp_dir) # The directory that Python returns might have symlinks. The Docker File sharing settings will not resolve # symlinks. Hence get the real ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invoke(self, function_config, event, debug_context=None, stdout=None, stderr=None): """ Invoke the given Lambda function locally. ##### NOTE: THIS IS A LONG ...
timer = None # Update with event input environ = function_config.env_vars environ.add_lambda_event_body(event) # Generate a dictionary of environment variable key:values env_vars = environ.resolve() with self._get_code_dir(function_config.code_abs_path) as code...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _configure_interrupt(self, function_name, timeout, container, is_debugging): """ When a Lambda function is executing, we setup certain interrupt handlers to ...
def timer_handler(): # NOTE: This handler runs in a separate thread. So don't try to mutate any non-thread-safe data structures LOG.info("Function '%s' timed out after %d seconds", function_name, timeout) self._container_manager.stop(container) def signal_handler(s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_code_dir(self, code_path): """ Method to get a path to a directory where the Lambda function code is available. This directory will be mounted directly ...
decompressed_dir = None try: if os.path.isfile(code_path) and code_path.endswith(self.SUPPORTED_ARCHIVE_EXTENSIONS): decompressed_dir = _unzip_file(code_path) yield decompressed_dir else: LOG.debug("Code %s is not a zip/jar fil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build(self, runtime, layers): """ Build the image if one is not already on the system that matches the runtime and layers Parameters runtime str Name of the ...
base_image = "{}:{}".format(self._DOCKER_LAMBDA_REPO_NAME, runtime) # Don't build the image if there are no layers. if not layers: LOG.debug("Skipping building an image since no layers were defined") return base_image downloaded_layers = self.layer_downloader.d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_docker_image_version(layers, runtime): """ Generate the Docker TAG that will be used to create the image Parameters layers list(samcli.commands.loc...
# Docker has a concept of a TAG on an image. This is plus the REPOSITORY is a way to determine # a version of the image. We will produced a TAG for a combination of the runtime with the layers # specified in the template. This will allow reuse of the runtime and layers across different ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _build_image(self, base_image, docker_tag, layers): """ Builds the image Parameters base_image str Base Image to use for the new image docker_tag Docker tag ...
dockerfile_content = self._generate_dockerfile(base_image, layers) # Create dockerfile in the same directory of the layer cache dockerfile_name = "dockerfile_" + str(uuid.uuid4()) full_dockerfile_path = Path(self.layer_downloader.layer_cache, dockerfile_name) try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_dockerfile(base_image, layers): """ Generate the Dockerfile contents A generated Dockerfile will look like the following: ``` FROM lambci/lambda:py...
dockerfile_content = "FROM {}\n".format(base_image) for layer in layers: dockerfile_content = dockerfile_content + \ "ADD --chown=sbx_user1051:495 {} {}\n".format(layer.name, LambdaImage._LAYERS_DIR) return dockerfile_content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Creates and starts the local API Gateway service. This method will block until the service is stopped manually using an interrupt. After the...
routing_list = self._make_routing_list(self.api_provider) if not routing_list: raise NoApisDefined("No APIs available in SAM template") static_dir_path = self._make_static_dir_path(self.cwd, self.static_dir) # We care about passing only stderr to the Service and not stdo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_routing_list(api_provider): """ Returns a list of routes to configure the Local API Service based on the APIs configured in the template. Parameters ap...
routes = [] for api in api_provider.get_all(): route = Route(methods=[api.method], function_name=api.function_name, path=api.path, binary_types=api.binary_media_types) routes.append(route) return routes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _print_routes(api_provider, host, port): """ Helper method to print the APIs that will be mounted. This method is purely for printing purposes. This method t...
grouped_api_configs = {} for api in api_provider.get_all(): key = "{}-{}".format(api.function_name, api.path) config = grouped_api_configs.get(key, {}) config.setdefault("methods", []) config["function_name"] = api.function_name config["pat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_static_dir_path(cwd, static_dir): """ This method returns the path to the directory where static files are to be served from. If static_dir is a relati...
if not static_dir: return None static_dir_path = os.path.join(cwd, static_dir) if os.path.exists(static_dir_path): LOG.info("Mounting static files from %s at /", static_dir_path) return static_dir_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_request(): """ Validates the incoming request The following are invalid 1. The Request data is not json serializable 2. Query Parameters are sent to...
flask_request = request request_data = flask_request.get_data() if not request_data: request_data = b'{}' request_data = request_data.decode('utf-8') try: json.loads(request_data) except ValueError as json_error: LOG.debug("Request ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _invoke_request_handler(self, function_name): """ Request Handler for the Local Lambda Invoke path. This method is responsible for understanding the incoming...
flask_request = request request_data = flask_request.get_data() if not request_data: request_data = b'{}' request_data = request_data.decode('utf-8') stdout_stream = io.BytesIO() stdout_stream_writer = StreamWriter(stdout_stream, self.is_debugging) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unzip(zip_file_path, output_dir, permission=None): """ Unzip the given file into the given directory while preserving file permissions in the process. Parame...
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref: # For each item in the zip file, extract the file and set permissions if available for file_info in zip_ref.infolist(): name = file_info.filename extracted_path = os.path.join(output_dir, name) zip_ref.extra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_permissions(zip_file_info, extracted_path): """ Sets permissions on the extracted file by reading the ``external_attr`` property of given file info. Par...
# Permission information is stored in first two bytes. permission = zip_file_info.external_attr >> 16 if not permission: # Zips created on certain Windows machines, however, might not have any permission information on them. # Skip setting a permission on these files. LOG.debug("Fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unzip_from_uri(uri, layer_zip_path, unzip_output_dir, progressbar_label): """ Download the LayerVersion Zip to the Layer Pkg Cache Parameters uri str Uri to ...
try: get_request = requests.get(uri, stream=True, verify=os.environ.get('AWS_CA_BUNDLE', True)) with open(layer_zip_path, 'wb') as local_layer_file: file_length = int(get_request.headers['Content-length']) with progressbar(file_length, progressbar_label) as p_bar: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generate_route_keys(self, methods, path): """ Generates the key to the _dict_of_routes based on the list of methods and path supplied :param list(str) metho...
for method in methods: yield self._route_key(method, path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parse_lambda_output(lambda_output, binary_types, flask_request): """ Parses the output from the Lambda Container :param str lambda_output: Output from Lambd...
json_output = json.loads(lambda_output) if not isinstance(json_output, dict): raise TypeError("Lambda returned %{s} instead of dict", type(json_output)) status_code = json_output.get("statusCode") or 200 headers = CaseInsensitiveDict(json_output.get("headers") or {}) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _should_base64_decode_body(binary_types, flask_request, lamba_response_headers, is_base_64_encoded): """ Whether or not the body should be decoded from Base6...
best_match_mimetype = flask_request.accept_mimetypes.best_match([lamba_response_headers["Content-Type"]]) is_best_match_in_binary_types = best_match_mimetype in binary_types or '*/*' in binary_types return best_match_mimetype and is_best_match_in_binary_types and is_base_64_encoded
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _construct_event(flask_request, port, binary_types): """ Helper method that constructs the Event to be passed to Lambda :param request flask_request: Flask R...
identity = ContextIdentity(source_ip=flask_request.remote_addr) endpoint = PathConverter.convert_path_to_api_gateway(flask_request.endpoint) method = flask_request.method request_data = flask_request.get_data() request_mimetype = flask_request.mimetype is_base_64 = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _query_string_params(flask_request): """ Constructs an APIGW equivalent query string dictionary Parameters flask_request request Request from Flask Returns d...
query_string_dict = {} # Flask returns an ImmutableMultiDict so convert to a dictionary that becomes # a dict(str: list) then iterate over for query_string_key, query_string_list in flask_request.args.lists(): query_string_value_length = len(query_string_list) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invoke(self, function_name, event, stdout=None, stderr=None): """ Find the Lambda function with given name and invoke it. Pass the given event to the functio...
# Generate the correct configuration based on given inputs function = self.provider.get(function_name) if not function: all_functions = [f.name for f in self.provider.get_all()] available_function_message = "{} not found. Possible options in your template: {}"\ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_invoke_config(self, function): """ Returns invoke configuration to pass to Lambda Runtime to invoke the given function :param samcli.commands.local.lib....
env_vars = self._make_env_vars(function) code_abs_path = resolve_code_path(self.cwd, function.codeuri) LOG.debug("Resolved absolute path to code is %s", code_abs_path) function_timeout = function.timeout # The Runtime container handles timeout inside the container. When debu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _make_env_vars(self, function): """Returns the environment variables configuration for this function Parameters function : samcli.commands.local.lib.provider...
name = function.name variables = None if function.environment and isinstance(function.environment, dict) and "Variables" in function.environment: variables = function.environment["Variables"] else: LOG.debug("No environment variables found for function '%s'", n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_aws_creds(self): """ Returns AWS credentials obtained from the shell environment or given profile :return dict: A dictionary containing credentials. This...
result = {} # to pass command line arguments for region & profile to setup boto3 default session if boto3.DEFAULT_SESSION: session = boto3.DEFAULT_SESSION else: session = boto3.session.Session() profile_name = session.profile_name if session else None ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """ Constructs an dictionary representation of the Identity Object to be used in serializing to JSON :return: dict representing the object """
json_dict = {"apiKey": self.api_key, "userArn": self.user_arn, "cognitoAuthenticationType": self.cognito_authentication_type, "caller": self.caller, "userAgent": self.user_agent, "user": self.user, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """ Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON :return: dict representing the obje...
identity_dict = {} if self.identity: identity_dict = self.identity.to_dict() json_dict = {"resourceId": self.resource_id, "apiId": self.api_id, "resourcePath": self.resource_path, "httpMethod": self.http_method, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """ Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON :return: dict representing t...
request_context_dict = {} if self.request_context: request_context_dict = self.request_context.to_dict() json_dict = {"httpMethod": self.http_method, "body": self.body if self.body else None, "resource": self.resource, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_docker_reachable(self): """ Checks if Docker daemon is running. This is required for us to invoke the function locally Returns ------- bool True, if Docke...
try: self.docker_client.ping() return True # When Docker is not installed, a request.exceptions.ConnectionError is thrown. except (docker.errors.APIError, requests.exceptions.ConnectionError): LOG.debug("Docker is not reachable", exc_info=True) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self, container, input_data=None, warm=False): """ Create and run a Docker container based on the given configuration. :param samcli.local.docker.contain...
if warm: raise ValueError("The facility to invoke warm container does not exist") image_name = container.image is_image_local = self.has_image(image_name) # Skip Pulling a new image if: a) Image name is samcli/lambda OR b) Image is available AND # c) We are asked...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pull_image(self, image_name, stream=None): """ Ask Docker to pull the container image with given name. Parameters image_name str Name of the image stream sam...
stream_writer = stream or StreamWriter(sys.stderr) try: result_itr = self.docker_client.api.pull(image_name, stream=True, decode=True) except docker.errors.APIError as ex: LOG.debug("Failed to download image with name %s", image_name) raise DockerImagePullFa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_image(self, image_name): """ Is the container image with given name available? :param string image_name: Name of the image :return bool: True, if image i...
try: self.docker_client.images.get(image_name) return True except docker.errors.ImageNotFound: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_cli(ctx, template, semantic_version): """Publish the application based on command line inputs."""
try: template_data = get_template_data(template) except ValueError as ex: click.secho("Publish Failed", fg='red') raise UserException(str(ex)) # Override SemanticVersion in template metadata when provided in command input if semantic_version and SERVERLESS_REPO_APPLICATION in t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gen_success_message(publish_output): """ Generate detailed success message for published applications. Parameters publish_output : dict Output from serverle...
application_id = publish_output.get('application_id') details = json.dumps(publish_output.get('details'), indent=2) if CREATE_APPLICATION in publish_output.get('actions'): return "Created new application with the following metadata:\n{}".format(details) return 'The following metadata of appli...