Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def create_api_key(self, api_id, stage_name): response = self.apigateway_client.create_api_key( name='{}_{}'.format(stage_name, api_id), description='Api Key for {}'.format(api_id), enabled=True, stageKeys=[ ...
[ "\n Create new API key and link it with an api_id and a stage_name\n " ]
Please provide a description of the function:def remove_api_key(self, api_id, stage_name): response = self.apigateway_client.get_api_keys( limit=1, nameQuery='{}_{}'.format(stage_name, api_id) ) for api_key in response.get('items'): self.apigateway_cl...
[ "\n Remove a generated API key for api_id and stage_name\n " ]
Please provide a description of the function:def add_api_stage_to_api_key(self, api_key, api_id, stage_name): self.apigateway_client.update_api_key( apiKey=api_key, patchOperations=[ { 'op': 'add', 'path': '/stages', ...
[ "\n Add api stage to Api key\n " ]
Please provide a description of the function:def get_patch_op(self, keypath, value, op='replace'): if isinstance(value, bool): value = str(value).lower() return {'op': op, 'path': '/*/*/{}'.format(keypath), 'value': value}
[ "\n Return an object that describes a change of configuration on the given staging.\n Setting will be applied on all available HTTP methods.\n " ]
Please provide a description of the function:def get_rest_apis(self, project_name): all_apis = self.apigateway_client.get_rest_apis( limit=500 ) for api in all_apis['items']: if api['name'] != project_name: continue yield api
[ "\n Generator that allows to iterate per every available apis.\n " ]
Please provide a description of the function:def undeploy_api_gateway(self, lambda_name, domain_name=None, base_path=None): print("Deleting API Gateway..") api_id = self.get_api_id(lambda_name) if domain_name: # XXX - Remove Route53 smartly here? # XXX - This ...
[ "\n Delete a deployed REST API Gateway.\n " ]
Please provide a description of the function:def update_stage_config( self, project_name, stage_name, cloudwatch_log_level, cloudwatch_data_trace, cloudwatch...
[ "\n Update CloudWatch metrics configuration.\n " ]
Please provide a description of the function:def delete_stack(self, name, wait=False): try: stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0] except: # pragma: no cover print('No Zappa stack named {0}'.format(name)) return False tag...
[ "\n Delete the CF stack managed by Zappa.\n " ]
Please provide a description of the function:def create_stack_template( self, lambda_arn, lambda_name, api_key_required, iam_authorization, authorizer, ...
[ "\n Build the entire CF stack.\n Just used for the API Gateway, but could be expanded in the future.\n " ]
Please provide a description of the function:def update_stack(self, name, working_bucket, wait=False, update_only=False, disable_progress=False): capabilities = [] template = name + '-template-' + str(int(time.time())) + '.json' with open(template, 'wb') as out: out.write(b...
[ "\n Update or create the CF stack managed by Zappa.\n " ]
Please provide a description of the function:def stack_outputs(self, name): try: stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0] return {x['OutputKey']: x['OutputValue'] for x in stack['Outputs']} except botocore.client.ClientError: return...
[ "\n Given a name, describes CloudFront stacks and returns dict of the stack Outputs\n , else returns an empty dict.\n " ]
Please provide a description of the function:def get_api_url(self, lambda_name, stage_name): api_id = self.get_api_id(lambda_name) if api_id: return "https://{}.execute-api.{}.amazonaws.com/{}".format(api_id, self.boto_session.region_name, stage_name) else: retur...
[ "\n Given a lambda_name and stage_name, return a valid API URL.\n " ]
Please provide a description of the function:def get_api_id(self, lambda_name): try: response = self.cf_client.describe_stack_resource(StackName=lambda_name, LogicalResourceId='Api') return response['StackResourceDeta...
[ "\n Given a lambda_name, return the API id.\n " ]
Please provide a description of the function:def create_domain_name(self, domain_name, certificate_name, certificate_body=None, certificate_private_key=None, certificate_chain=None, ...
[ "\n Creates the API GW domain and returns the resulting DNS name.\n " ]
Please provide a description of the function:def update_route53_records(self, domain_name, dns_name): zone_id = self.get_hosted_zone_id_for_domain(domain_name) is_apex = self.route53.get_hosted_zone(Id=zone_id)['HostedZone']['Name'][:-1] == domain_name if is_apex: record_se...
[ "\n Updates Route53 Records following GW domain creation\n " ]
Please provide a description of the function:def update_domain_name(self, domain_name, certificate_name=None, certificate_body=None, certificate_private_key=None, certificate_chain=None...
[ "\n This updates your certificate information for an existing domain,\n with similar arguments to boto's update_domain_name API Gateway api.\n\n It returns the resulting new domain information including the new certificate's ARN\n if created during this process.\n\n Previously, th...
Please provide a description of the function:def update_domain_base_path_mapping(self, domain_name, lambda_name, stage, base_path): api_id = self.get_api_id(lambda_name) if not api_id: print("Warning! Can't update base path mapping!") return base_path_mappings = ...
[ "\n Update domain base path mapping on API Gateway if it was changed\n " ]
Please provide a description of the function:def get_all_zones(self): zones = {'HostedZones': []} new_zones = self.route53.list_hosted_zones(MaxItems='100') while new_zones['IsTruncated']: zones['HostedZones'] += new_zones['HostedZones'] new_zones = self.route53...
[ "Same behaviour of list_host_zones, but transparently handling pagination." ]
Please provide a description of the function:def get_domain_name(self, domain_name, route53=True): # Make sure api gateway domain is present try: self.apigateway_client.get_domain_name(domainName=domain_name) except Exception: return None if not route53:...
[ "\n Scan our hosted zones for the record of a given name.\n\n Returns the record entry, else None.\n\n " ]
Please provide a description of the function:def get_credentials_arn(self): role = self.iam.Role(self.role_name) self.credentials_arn = role.arn return role, self.credentials_arn
[ "\n Given our role name, get and set the credentials_arn.\n\n " ]
Please provide a description of the function:def create_iam_roles(self): attach_policy_obj = json.loads(self.attach_policy) assume_policy_obj = json.loads(self.assume_policy) if self.extra_permissions: for permission in self.extra_permissions: attach_policy_...
[ "\n Create and defines the IAM roles and policies necessary for Zappa.\n\n If the IAM role already exists, it will be updated if necessary.\n " ]
Please provide a description of the function:def _clear_policy(self, lambda_name): try: policy_response = self.lambda_client.get_policy( FunctionName=lambda_name ) if policy_response['ResponseMetadata']['HTTPStatusCode'] == 200: statem...
[ "\n Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates.\n " ]
Please provide a description of the function:def create_event_permission(self, lambda_name, principal, source_arn): logger.debug('Adding new permission to invoke Lambda function: {}'.format(lambda_name)) permission_response = self.lambda_client.add_permission( FunctionName=lambda_na...
[ "\n Create permissions to link to an event.\n\n Related: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html\n " ]
Please provide a description of the function:def schedule_events(self, lambda_arn, lambda_name, events, default=True): # The stream sources - DynamoDB, Kinesis and SQS - are working differently than the other services (pull vs push) # and do not require event permissions. They do require addit...
[ "\n Given a Lambda ARN, name and a list of events, schedule this as CloudWatch Events.\n\n 'events' is a list of dictionaries, where the dict must contains the string\n of a 'function' and the string of the event 'expression', and an optional 'name' and 'description'.\n\n Expressions can...
Please provide a description of the function:def get_event_name(lambda_name, name): return '{prefix:.{width}}-{postfix}'.format(prefix=lambda_name, width=max(0, 63 - len(name)), postfix=name)[:64]
[ "\n Returns an AWS-valid Lambda event name.\n\n " ]
Please provide a description of the function:def get_hashed_rule_name(event, function, lambda_name): event_name = event.get('name', function) name_hash = hashlib.sha1('{}-{}'.format(lambda_name, event_name).encode('UTF-8')).hexdigest() return Zappa.get_event_name(name_hash, function)
[ "\n Returns an AWS-valid CloudWatch rule name using a digest of the event name, lambda name, and function.\n This allows support for rule names that may be longer than the 64 char limit.\n " ]
Please provide a description of the function:def delete_rule(self, rule_name): logger.debug('Deleting existing rule {}'.format(rule_name)) # All targets must be removed before # we can actually delete the rule. try: targets = self.events_client.list_targets_by_rule(...
[ "\n Delete a CWE rule.\n\n This deletes them, but they will still show up in the AWS console.\n Annoying.\n\n " ]
Please provide a description of the function:def get_event_rule_names_for_lambda(self, lambda_arn): response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn) rule_names = response['RuleNames'] # Iterate when the results are paginated while 'NextToken' in resp...
[ "\n Get all of the rule names associated with a lambda function.\n " ]
Please provide a description of the function:def get_event_rules_for_lambda(self, lambda_arn): rule_names = self.get_event_rule_names_for_lambda(lambda_arn=lambda_arn) return [self.events_client.describe_rule(Name=r) for r in rule_names]
[ "\n Get all of the rule details associated with this function.\n " ]
Please provide a description of the function:def unschedule_events(self, events, lambda_arn=None, lambda_name=None, excluded_source_services=None): excluded_source_services = excluded_source_services or [] self._clear_policy(lambda_name) rule_names = self.get_event_rule_names_for_lambd...
[ "\n Given a list of events, unschedule these CloudWatch Events.\n\n 'events' is a list of dictionaries, where the dict must contains the string\n of a 'function' and the string of the event 'expression', and an optional 'name' and 'description'.\n " ]
Please provide a description of the function:def create_async_sns_topic(self, lambda_name, lambda_arn): topic_name = get_topic_name(lambda_name) # Create SNS topic topic_arn = self.sns_client.create_topic( Name=topic_name)['TopicArn'] # Create subscription se...
[ "\n Create the SNS-based async topic.\n " ]
Please provide a description of the function:def remove_async_sns_topic(self, lambda_name): topic_name = get_topic_name(lambda_name) removed_arns = [] for sub in self.sns_client.list_subscriptions()['Subscriptions']: if topic_name in sub['TopicArn']: self.sns...
[ "\n Remove the async SNS topic.\n " ]
Please provide a description of the function:def create_async_dynamodb_table(self, table_name, read_capacity, write_capacity): try: dynamodb_table = self.dynamodb_client.describe_table(TableName=table_name) return False, dynamodb_table # catch this exception (triggered ...
[ "\n Create the DynamoDB table for async task return values\n " ]
Please provide a description of the function:def fetch_logs(self, lambda_name, filter_pattern='', limit=10000, start_time=0): log_name = '/aws/lambda/' + lambda_name streams = self.logs_client.describe_log_streams( logGroupName=log_name, descending=True, orde...
[ "\n Fetch the CloudWatch logs for a given Lambda name.\n " ]
Please provide a description of the function:def remove_log_group(self, group_name): print("Removing log group: {}".format(group_name)) try: self.logs_client.delete_log_group(logGroupName=group_name) except botocore.exceptions.ClientError as e: print("Couldn't re...
[ "\n Filter all log groups that match the name given in log_filter.\n " ]
Please provide a description of the function:def remove_api_gateway_logs(self, project_name): for rest_api in self.get_rest_apis(project_name): for stage in self.apigateway_client.get_stages(restApiId=rest_api['id'])['item']: self.remove_log_group('API-Gateway-Execution-Logs...
[ "\n Removed all logs that are assigned to a given rest api id.\n " ]
Please provide a description of the function:def get_hosted_zone_id_for_domain(self, domain): all_zones = self.get_all_zones() return self.get_best_match_zone(all_zones, domain)
[ "\n Get the Hosted Zone ID for a given domain.\n\n " ]
Please provide a description of the function:def get_best_match_zone(all_zones, domain): # Related: https://github.com/Miserlou/Zappa/issues/459 public_zones = [zone for zone in all_zones['HostedZones'] if not zone['Config']['PrivateZone']] zones = {zone['Name'][:-1]: zone['Id'] for z...
[ "Return zone id which name is closer matched with domain name." ]
Please provide a description of the function:def remove_dns_challenge_txt(self, zone_id, domain, txt_challenge): print("Deleting DNS challenge..") resp = self.route53.change_resource_record_sets( HostedZoneId=zone_id, ChangeBatch=self.get_dns_challenge_change_batch('DELE...
[ "\n Remove DNS challenge TXT.\n " ]
Please provide a description of the function:def load_credentials(self, boto_session=None, profile_name=None): # Automatically load credentials from config or environment if not boto_session: # If provided, use the supplied profile name. if profile_name: ...
[ "\n Load AWS credentials.\n\n An optional boto_session can be provided, but that's usually for testing.\n\n An optional profile_name can be provided for config files that have multiple sets\n of credentials.\n " ]
Please provide a description of the function:def get_cert_and_update_domain( zappa_instance, lambda_name, api_stage, domain=None, manual=False, ...
[ "\n Main cert installer path.\n " ]
Please provide a description of the function:def parse_account_key(): LOGGER.info("Parsing account key...") cmd = [ 'openssl', 'rsa', '-in', os.path.join(gettempdir(), 'account.key'), '-noout', '-text' ] devnull = open(os.devnull, 'wb') return subprocess.check_ou...
[ "Parse account key to get public key" ]
Please provide a description of the function:def parse_csr(): LOGGER.info("Parsing CSR...") cmd = [ 'openssl', 'req', '-in', os.path.join(gettempdir(), 'domain.csr'), '-noout', '-text' ] devnull = open(os.devnull, 'wb') out = subprocess.check_output(cmd, stderr=d...
[ "\n Parse certificate signing request for domains\n " ]
Please provide a description of the function:def get_boulder_header(key_bytes): pub_hex, pub_exp = re.search( r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)", key_bytes.decode('utf8'), re.MULTILINE | re.DOTALL).groups() pub_exp = "{0:x}".format(int(pub_exp)) pub_exp = "0{0...
[ "\n Use regular expressions to find crypto values from parsed account key,\n and return a header we can send to our Boulder instance.\n " ]
Please provide a description of the function:def register_account(): LOGGER.info("Registering account...") code, result = _send_signed_request(DEFAULT_CA + "/acme/new-reg", { "resource": "new-reg", "agreement": "https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf", }) ...
[ "\n Agree to LE TOS\n " ]
Please provide a description of the function:def get_cert(zappa_instance, log=LOGGER, CA=DEFAULT_CA): out = parse_account_key() header = get_boulder_header(out) accountkey_json = json.dumps(header['jwk'], sort_keys=True, separators=(',', ':')) thumbprint = _b64(hashlib.sha256(accountkey_json.encode...
[ "\n Call LE to get a new signed CA.\n " ]
Please provide a description of the function:def verify_challenge(uri): while True: try: resp = urlopen(uri) challenge_status = json.loads(resp.read().decode('utf8')) except IOError as e: raise ValueError("Error checking challenge: {0} {1}".format( ...
[ "\n Loop until our challenge is verified, else fail.\n " ]
Please provide a description of the function:def sign_certificate(): LOGGER.info("Signing certificate...") cmd = [ 'openssl', 'req', '-in', os.path.join(gettempdir(), 'domain.csr'), '-outform', 'DER' ] devnull = open(os.devnull, 'wb') csr_der = subprocess.check_output(cm...
[ "\n Get the new certificate.\n Returns the signed bytes.\n\n " ]
Please provide a description of the function:def encode_certificate(result): cert_body = .format( "\n".join(textwrap.wrap(base64.b64encode(result).decode('utf8'), 64))) signed_crt = open("{}/signed.crt".format(gettempdir()), "w") signed_crt.write(cert_body) signed_crt.close() return Tr...
[ "\n Encode cert bytes to PEM encoded cert file.\n ", "-----BEGIN CERTIFICATE-----\\n{0}\\n-----END CERTIFICATE-----\\n" ]
Please provide a description of the function:def _send_signed_request(url, payload): payload64 = _b64(json.dumps(payload).encode('utf8')) out = parse_account_key() header = get_boulder_header(out) protected = copy.deepcopy(header) protected["nonce"] = urlopen(DEFAULT_CA + "/directory").header...
[ "\n Helper function to make signed requests to Boulder\n " ]
Please provide a description of the function:def shamelessly_promote(): click.echo("Need " + click.style("help", fg='green', bold=True) + "? Found a " + click.style("bug", fg='green', bold=True) + "? Let us " + click.style("know", fg='green', bold=True) + "! :D") click.echo("...
[ "\n Shamelessly promote our little community.\n " ]
Please provide a description of the function:def handle(): # pragma: no cover try: cli = ZappaCLI() sys.exit(cli.handle()) except SystemExit as e: # pragma: no cover cli.on_exit() sys.exit(e.code) except KeyboardInterrupt: # pragma: no cover cli.on_exit() ...
[ "\n Main program execution handler.\n " ]
Please provide a description of the function:def stage_config(self): def get_stage_setting(stage, extended_stages=None): if extended_stages is None: extended_stages = [] if stage in extended_stages: raise RuntimeError(stage + " has already been ...
[ "\n A shortcut property for settings of a stage.\n " ]
Please provide a description of the function:def override_stage_config_setting(self, key, val): self._stage_config_overrides = getattr(self, '_stage_config_overrides', {}) self._stage_config_overrides.setdefault(self.api_stage, {})[key] = val
[ "\n Forcefully override a setting set by zappa_settings (for the current stage only)\n :param key: settings key\n :param val: value\n " ]
Please provide a description of the function:def handle(self, argv=None): desc = ('Zappa - Deploy Python applications to AWS Lambda' ' and API Gateway.\n') parser = argparse.ArgumentParser(description=desc) parser.add_argument( '-v', '--version', action='ver...
[ "\n Main function.\n\n Parses command, load settings and dispatches accordingly.\n\n ", " Ensure an arg is positive " ]
Please provide a description of the function:def dispatch_command(self, command, stage): self.api_stage = stage if command not in ['status', 'manage']: if not self.vargs.get('json', None): click.echo("Calling " + click.style(command, fg="green", bold=True) + " for ...
[ "\n Given a command to execute and stage,\n execute that command.\n " ]
Please provide a description of the function:def package(self, output=None): # Make sure we're in a venv. self.check_venv() # force not to delete the local zip self.override_stage_config_setting('delete_local_zip', False) # Execute the prebuild script if self.pr...
[ "\n Only build the package\n " ]
Please provide a description of the function:def template(self, lambda_arn, role_arn, output=None, json=False): if not lambda_arn: raise ClickException("Lambda ARN is required to template.") if not role_arn: raise ClickException("Role ARN is required to template.") ...
[ "\n Only build the template file.\n " ]
Please provide a description of the function:def deploy(self, source_zip=None): if not source_zip: # Make sure we're in a venv. self.check_venv() # Execute the prebuild script if self.prebuild_script: self.execute_prebuild_script() ...
[ "\n Package your project, upload it to S3, register the Lambda function\n and create the API Gateway routes.\n\n " ]
Please provide a description of the function:def update(self, source_zip=None, no_upload=False): if not source_zip: # Make sure we're in a venv. self.check_venv() # Execute the prebuild script if self.prebuild_script: self.execute_prebui...
[ "\n Repackage and update the function code.\n " ]
Please provide a description of the function:def rollback(self, revision): print("Rolling back..") self.zappa.rollback_lambda_function_version( self.lambda_name, versions_back=revision) print("Done!")
[ "\n Rollsback the currently deploy lambda code to a previous revision.\n " ]
Please provide a description of the function:def tail(self, since, filter_pattern, limit=10000, keep_open=True, colorize=True, http=False, non_http=False, force_colorize=False): try: since_stamp = string_to_timestamp(since) last_since = since_stamp while True: ...
[ "\n Tail this function's logs.\n\n if keep_open, do so repeatedly, printing any new logs\n " ]
Please provide a description of the function:def undeploy(self, no_confirm=False, remove_logs=False): if not no_confirm: # pragma: no cover confirm = input("Are you sure you want to undeploy? [y/n] ") if confirm != 'y': return if self.use_alb: ...
[ "\n Tear down an existing deployment.\n " ]
Please provide a description of the function:def update_cognito_triggers(self): if self.cognito: user_pool = self.cognito.get('user_pool') triggers = self.cognito.get('triggers', []) lambda_configs = set() for trigger in triggers: lambda_c...
[ "\n Update any cognito triggers\n " ]
Please provide a description of the function:def schedule(self): events = self.stage_config.get('events', []) if events: if not isinstance(events, list): # pragma: no cover print("Events must be supplied as a list.") return for event in even...
[ "\n Given a a list of functions and a schedule to execute them,\n setup up regular execution.\n\n " ]
Please provide a description of the function:def unschedule(self): # Run even if events are not defined to remove previously existing ones (thus default to []). events = self.stage_config.get('events', []) if not isinstance(events, list): # pragma: no cover print("Events m...
[ "\n Given a a list of scheduled functions,\n tear down their regular execution.\n\n " ]
Please provide a description of the function:def invoke(self, function_name, raw_python=False, command=None, no_color=False): # There are three likely scenarios for 'command' here: # command, which is a modular function path # raw_command, which is a string of python to execute dir...
[ "\n Invoke a remote function.\n " ]
Please provide a description of the function:def format_invoke_command(self, string): string = string.replace('\\n', '\n') formated_response = '' for line in string.splitlines(): if line.startswith('REPORT'): line = line.replace('\t', '\n') if l...
[ "\n Formats correctly the string output from the invoke() method,\n replacing line breaks and tabs when necessary.\n " ]
Please provide a description of the function:def colorize_invoke_command(self, string): final_string = string try: # Line headers try: for token in ['START', 'END', 'REPORT', '[DEBUG]']: if token in final_string: ...
[ "\n Apply various heuristics to return a colorized version the invoke\n command string. If these fail, simply return the string in plaintext.\n\n Inspired by colorize_log_entry().\n " ]
Please provide a description of the function:def status(self, return_json=False): def tabular_print(title, value): click.echo('%-*s%s' % (32, click.style("\t" + title, fg='green') + ':', str(value))) return # Lambda Env Details lambda_versions = se...
[ "\n Describe the status of the current deployment.\n ", "\n Convenience function for priting formatted table items.\n " ]
Please provide a description of the function:def check_environment(self, environment): non_strings = [] for (k,v) in environment.items(): if not isinstance(v, basestring): non_strings.append(k) if non_strings: raise ValueError("The following envi...
[ "\n Make sure the environment contains only strings\n\n (since putenv needs a string)\n " ]
Please provide a description of the function:def init(self, settings_file="zappa_settings.json"): # Make sure we're in a venv. self.check_venv() # Ensure that we don't already have a zappa_settings file. if os.path.isfile(settings_file): raise ClickException("This ...
[ "\n Initialize a new Zappa project by creating a new zappa_settings.json in a guided process.\n\n This should probably be broken up into few separate componants once it's stable.\n Testing these inputs requires monkeypatching with mock, which isn't pretty.\n\n ", "\\n███████╗ █████╗ ██...
Please provide a description of the function:def certify(self, no_confirm=True, manual=False): if not self.domain: raise ClickException("Can't certify a domain without " + click.style("domain", fg="red", bold=True) + " configured!") if not no_confirm: # pragma: no cover ...
[ "\n Register or update a domain certificate for this env.\n " ]
Please provide a description of the function:def shell(self): click.echo(click.style("NOTICE!", fg="yellow", bold=True) + " This is a " + click.style("local", fg="green", bold=True) + " shell, inside a " + click.style("Zappa", bold=True) + " object!") self.zappa.shell() return
[ "\n Spawn a debug shell.\n " ]
Please provide a description of the function:def callback(self, position): callbacks = self.stage_config.get('callbacks', {}) callback = callbacks.get(position) if callback: (mod_path, cb_func_name) = callback.rsplit('.', 1) try: # Prefer callback in working ...
[ "\n Allows the execution of custom code between creation of the zip file and deployment to AWS.\n\n :return: None\n " ]
Please provide a description of the function:def check_for_update(self): try: version = pkg_resources.require("zappa")[0].version updateable = check_new_version_available(version) if updateable: click.echo(click.style("Important!", fg="yellow", bold=T...
[ "\n Print a warning if there's a new Zappa version available.\n " ]
Please provide a description of the function:def load_settings(self, settings_file=None, session=None): # Ensure we're passed a valid settings file. if not settings_file: settings_file = self.get_json_or_yaml_settings() if not os.path.isfile(settings_file): rais...
[ "\n Load the local zappa_settings file.\n\n An existing boto session can be supplied, though this is likely for testing purposes.\n\n Returns the loaded Zappa object.\n " ]
Please provide a description of the function:def get_json_or_yaml_settings(self, settings_name="zappa_settings"): zs_json = settings_name + ".json" zs_yml = settings_name + ".yml" zs_yaml = settings_name + ".yaml" zs_toml = settings_name + ".toml" # Must have at least o...
[ "\n Return zappa_settings path as JSON or YAML (or TOML), as appropriate.\n " ]
Please provide a description of the function:def load_settings_file(self, settings_file=None): if not settings_file: settings_file = self.get_json_or_yaml_settings() if not os.path.isfile(settings_file): raise ClickException("Please configure your zappa_settings file or...
[ "\n Load our settings file.\n " ]
Please provide a description of the function:def create_package(self, output=None): # Create the Lambda zip package (includes project and virtualenvironment) # Also define the path the handler file so it can be copied to the zip # root for Lambda. current_file = os.path.dirname...
[ "\n Ensure that the package can be properly configured,\n and then create it.\n\n " ]
Please provide a description of the function:def remove_local_zip(self): if self.stage_config.get('delete_local_zip', True): try: if os.path.isfile(self.zip_path): os.remove(self.zip_path) if self.handler_path and os.path.isfile(self.hand...
[ "\n Remove our local zip file.\n " ]
Please provide a description of the function:def remove_uploaded_zip(self): # Remove the uploaded zip from S3, because it is now registered.. if self.stage_config.get('delete_s3_zip', True): self.zappa.remove_from_s3(self.zip_path, self.s3_bucket_name) if self.stage_con...
[ "\n Remove the local and S3 zip file after uploading and updating.\n " ]
Please provide a description of the function:def on_exit(self): if self.zip_path: # Only try to remove uploaded zip if we're running a command that has loaded credentials if self.load_credentials: self.remove_uploaded_zip() self.remove_local_zip()
[ "\n Cleanup after the command finishes.\n Always called: SystemExit, KeyboardInterrupt and any other Exception that occurs.\n " ]
Please provide a description of the function:def print_logs(self, logs, colorize=True, http=False, non_http=False, force_colorize=None): for log in logs: timestamp = log['timestamp'] message = log['message'] if "START RequestId" in message: continue ...
[ "\n Parse, filter and print logs to the console.\n\n " ]
Please provide a description of the function:def is_http_log_entry(self, string): # Debug event filter if 'Zappa Event' in string: return False # IP address filter for token in string.replace('\t', ' ').split(' '): try: if (token.count('....
[ "\n Determines if a log entry is an HTTP-formatted log string or not.\n " ]
Please provide a description of the function:def colorize_log_entry(self, string): final_string = string try: # First, do stuff in square brackets inside_squares = re.findall(r'\[([^]]*)\]', string) for token in inside_squares: if token in [...
[ "\n Apply various heuristics to return a colorized version of a string.\n If these fail, simply return the string in plaintext.\n " ]
Please provide a description of the function:def execute_prebuild_script(self): (pb_mod_path, pb_func) = self.prebuild_script.rsplit('.', 1) try: # Prefer prebuild script in working directory if pb_mod_path.count('.') >= 1: # Prebuild script func is nested in a folder ...
[ "\n Parse and execute the prebuild_script from the zappa_settings.\n\n " ]
Please provide a description of the function:def collision_warning(self, item): namespace_collisions = [ "zappa.", "wsgi.", "middleware.", "handler.", "util.", "letsencrypt.", "cli." ] for namespace_collision in namespace_collisions: if item.startswith(namespace...
[ "\n Given a string, print a warning if this could\n collide with a Zappa core package module.\n\n Use for app functions and events.\n " ]
Please provide a description of the function:def check_venv(self): if self.zappa: venv = self.zappa.get_current_venv() else: # Just for `init`, when we don't have settings yet. venv = Zappa.get_current_venv() if not venv: raise ClickExcept...
[ " Ensure we're inside a virtualenv. " ]
Please provide a description of the function:def silence(self): sys.stdout = open(os.devnull, 'w') sys.stderr = open(os.devnull, 'w')
[ "\n Route all stdout to null.\n " ]
Please provide a description of the function:def touch_endpoint(self, endpoint_url): # Private APIGW endpoints most likely can't be reached by a deployer # unless they're connected to the VPC by VPN. Instead of trying # connect to the service, print a warning and let the user know ...
[ "\n Test the deployed endpoint with a GET request.\n " ]
Please provide a description of the function:def all_casings(input_string): if not input_string: yield "" else: first = input_string[:1] if first.lower() == first.upper(): for sub_casing in all_casings(input_string[1:]): yield first + sub_casing e...
[ "\n Permute all casings of a given string.\n\n A pretty algorithm, via @Amber\n http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python\n " ]
Please provide a description of the function:def status_count(self, project): ''' return a dict ''' result = dict() if project not in self.projects: self._list_project() if project not in self.projects: return result tablename = self._table...
[]
Please provide a description of the function:def get_encoding(headers, content): encoding = None content_type = headers.get('content-type') if content_type: _, params = cgi.parse_header(content_type) if 'charset' in params: encoding = params['charset'].strip("'\"") if ...
[ "Get encoding from request headers or page head." ]
Please provide a description of the function:def encoding(self): if hasattr(self, '_encoding'): return self._encoding # content is unicode if isinstance(self.content, six.text_type): return 'unicode' # Try charset from content-type or content en...
[ "\n encoding of Response.content.\n\n if Response.encoding is None, encoding will be guessed\n by header or content or chardet if available.\n " ]
Please provide a description of the function:def text(self): if hasattr(self, '_text') and self._text: return self._text if not self.content: return u'' if isinstance(self.content, six.text_type): return self.content content = None en...
[ "\n Content of the response, in unicode.\n\n if Response.encoding is None and chardet module is available, encoding\n will be guessed.\n " ]
Please provide a description of the function:def json(self): if hasattr(self, '_json'): return self._json try: self._json = json.loads(self.text or self.content) except ValueError: self._json = None return self._json
[ "Returns the json-encoded content of the response, if any." ]
Please provide a description of the function:def doc(self): if hasattr(self, '_doc'): return self._doc elements = self.etree doc = self._doc = PyQuery(elements) doc.make_links_absolute(utils.text(self.url)) return doc
[ "Returns a PyQuery object of the response's content" ]
Please provide a description of the function:def etree(self): if not hasattr(self, '_elements'): try: parser = lxml.html.HTMLParser(encoding=self.encoding) self._elements = lxml.html.fromstring(self.content, parser=parser) except LookupError: ...
[ "Returns a lxml object of the response's content that can be selected by xpath" ]
Please provide a description of the function:def raise_for_status(self, allow_redirects=True): if self.status_code == 304: return elif self.error: if self.traceback: six.reraise(Exception, Exception(self.error), Traceback.from_string(self.traceback).as_t...
[ "Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred." ]