INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Takes the installed zappa and brings it into a fresh virtualenv - like folder. All dependencies are then downloaded.
def create_handler_venv(self): """ Takes the installed zappa and brings it into a fresh virtualenv-like folder. All dependencies are then downloaded. """ import subprocess # We will need the currenv venv to pull Zappa from current_venv = self.get_current_venv() ...
Returns the path to the current virtualenv
def get_current_venv(): """ Returns the path to the current virtualenv """ if 'VIRTUAL_ENV' in os.environ: venv = os.environ['VIRTUAL_ENV'] elif os.path.exists('.python-version'): # pragma: no cover try: subprocess.check_output(['pyenv', '...
Create a Lambda - ready zip file of the current virtualenvironment and working directory.
def create_lambda_zip( self, prefix='lambda_package', handler_file=None, slim_handler=False, minify=True, exclude=None, use_precompiled_packages=True, ...
Extracts the lambda package into a given path. Assumes the package exists in lambda packages.
def extract_lambda_package(self, package_name, path): """ Extracts the lambda package into a given path. Assumes the package exists in lambda packages. """ lambda_package = lambda_packages[package_name][self.runtime] # Trash the local version to help with package space saving ...
Returns a dict of installed packages that Zappa cares about.
def get_installed_packages(site_packages, site_packages_64): """ Returns a dict of installed packages that Zappa cares about. """ import pkg_resources package_to_keep = [] if os.path.isdir(site_packages): package_to_keep += os.listdir(site_packages) i...
Checks if a given package version binary should be copied over from lambda packages. package_name should be lower - cased version of package name.
def have_correct_lambda_package_version(self, package_name, package_version): """ Checks if a given package version binary should be copied over from lambda packages. package_name should be lower-cased version of package name. """ lambda_package_details = lambda_packages.get(pack...
Downloads a given url in chunks and writes to the provided stream ( can be any io stream ). Displays the progress bar for the download.
def download_url_with_progress(url, stream, disable_progress): """ Downloads a given url in chunks and writes to the provided stream (can be any io stream). Displays the progress bar for the download. """ resp = requests.get(url, timeout=float(os.environ.get('PIP_TIMEOUT', 2)), s...
Gets the locally stored version of a manylinux wheel. If one does not exist the function downloads it.
def get_cached_manylinux_wheel(self, package_name, package_version, disable_progress=False): """ Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it. """ cached_wheels_dir = os.path.join(tempfile.gettempdir(), 'cached_wheels') if...
For a given package name returns a link to the download URL else returns None.
def get_manylinux_wheel_url(self, package_name, package_version): """ For a given package name, returns a link to the download URL, else returns None. Related: https://github.com/Miserlou/Zappa/issues/398 Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b5688...
r Given a file upload it to S3. Credentials should be stored in environment variables or ~/. aws/ credentials ( %USERPROFILE% \. aws \ credentials on Windows ).
def upload_to_s3(self, source_path, bucket_name, disable_progress=False): r""" Given a file, upload it to S3. Credentials should be stored in environment variables or ~/.aws/credentials (%USERPROFILE%\.aws\credentials on Windows). Returns True on success, false on failure. """ ...
Copies src file to destination within a bucket.
def copy_on_s3(self, src_file_name, dst_file_name, bucket_name): """ Copies src file to destination within a bucket. """ try: self.s3_client.head_bucket(Bucket=bucket_name) except botocore.exceptions.ClientError as e: # pragma: no cover # If a client erro...
Given a file name and a bucket remove it from S3.
def remove_from_s3(self, file_name, bucket_name): """ Given a file name and a bucket, remove it from S3. There's no reason to keep the file hosted on S3 once its been made into a Lambda function, so we can delete it from S3. Returns True on success, False on failure. """ ...
Given a bucket and key ( or a local path ) of a valid Lambda - zip a function name and a handler register that Lambda function.
def create_lambda_function( self, bucket=None, function_name=None, handler=None, s3_key=None, description='Zappa Deployment', ti...
Given a bucket and key ( or a local path ) of a valid Lambda - zip a function name and a handler update that Lambda function s code. Optionally delete previous versions if they exceed the optional limit.
def update_lambda_function(self, bucket, function_name, s3_key=None, publish=True, local_zip=None, num_revisions=None): """ Given a bucket and key (or a local path) of a valid Lambda-zip, a function name and a handler, update that Lambda function's code. Optionally, delete previous versions if t...
Given an existing function ARN update the configuration variables.
def update_lambda_configuration( self, lambda_arn, function_name, handler, description='Zappa Deployment', timeout=30...
Directly invoke a named Lambda function with a payload. Returns the response.
def invoke_lambda_function( self, function_name, payload, invocation_type='Event', log_type='Tail', client_context=None, qualifi...
Rollback the lambda function code versions_back number of revisions.
def rollback_lambda_function_version(self, function_name, versions_back=1, publish=True): """ Rollback the lambda function code 'versions_back' number of revisions. Returns the Function ARN. """ response = self.lambda_client.list_versions_by_function(FunctionName=function_name) ...
Returns the lambda function ARN given a name
def get_lambda_function(self, function_name): """ Returns the lambda function ARN, given a name This requires the "lambda:GetFunction" role. """ response = self.lambda_client.get_function( FunctionName=function_name) return response['Configuration']['Func...
Simply returns the versions available for a Lambda function given a function name.
def get_lambda_function_versions(self, function_name): """ Simply returns the versions available for a Lambda function, given a function name. """ try: response = self.lambda_client.list_versions_by_function( FunctionName=function_name ) ...
The zappa deploy functionality for ALB infrastructure.
def deploy_lambda_alb( self, lambda_arn, lambda_name, alb_vpc_config, timeout ): """ The `zappa deploy` functionality for ALB infrastructure. """ if n...
The zappa undeploy functionality for ALB infrastructure.
def undeploy_lambda_alb(self, lambda_name): """ The `zappa undeploy` functionality for ALB infrastructure. """ print("Undeploying ALB infrastructure...") # Locate and delete alb/lambda permissions try: # https://boto3.amazonaws.com/v1/documentation/api/latest...
Create the API Gateway for this Zappa deployment.
def create_api_gateway_routes( self, lambda_arn, api_name=None, api_key_required=False, authorization_type='NONE', authorizer=None, ...
Create Authorizer for API gateway
def create_authorizer(self, restapi, uri, authorizer): """ Create Authorizer for API gateway """ authorizer_type = authorizer.get("type", "TOKEN").upper() identity_validation_expression = authorizer.get('validation_expression', None) authorizer_resource = troposphere.api...
Set up the methods integration responses and method responses for a given API Gateway resource.
def create_and_setup_methods( self, restapi, resource, api_key_required, uri, authorization_type, ...
Set up the methods integration responses and method responses for a given API Gateway resource.
def create_and_setup_cors(self, restapi, resource, uri, depth, config): """ Set up the methods, integration responses and method responses for a given API Gateway resource. """ if config is True: config = {} method_name = "OPTIONS" method = troposphere.apigate...
Deploy the API Gateway!
def deploy_api_gateway( self, api_id, stage_name, stage_description="", description="", cache_cluster_enabled=False, cache_cluster_size='0.5', ...
Remove binary support
def remove_binary_support(self, api_id, cors=False): """ Remove binary support """ response = self.apigateway_client.get_rest_api( restApiId=api_id ) if "binaryMediaTypes" in response and "*/*" in response["binaryMediaTypes"]: self.apigateway_clien...
Add Rest API compression
def add_api_compression(self, api_id, min_compression_size): """ Add Rest API compression """ self.apigateway_client.update_rest_api( restApiId=api_id, patchOperations=[ { 'op': 'replace', 'path': '/minimumCo...
Generator that allows to iterate per API keys associated to an api_id and a stage_name.
def get_api_keys(self, api_id, stage_name): """ Generator that allows to iterate per API keys associated to an api_id and a stage_name. """ response = self.apigateway_client.get_api_keys(limit=500) stage_key = '{}/{}'.format(api_id, stage_name) for api_key in response.get...
Create new API key and link it with an api_id and a stage_name
def create_api_key(self, api_id, stage_name): """ Create new API key and link it with an api_id and a stage_name """ response = self.apigateway_client.create_api_key( name='{}_{}'.format(stage_name, api_id), description='Api Key for {}'.format(api_id), ...
Remove a generated API key for api_id and stage_name
def remove_api_key(self, api_id, stage_name): """ Remove a generated API key for api_id and stage_name """ response = self.apigateway_client.get_api_keys( limit=1, nameQuery='{}_{}'.format(stage_name, api_id) ) for api_key in response.get('items'):...
Add api stage to Api key
def add_api_stage_to_api_key(self, api_key, api_id, stage_name): """ Add api stage to Api key """ self.apigateway_client.update_api_key( apiKey=api_key, patchOperations=[ { 'op': 'add', 'path': '/stages', ...
Return an object that describes a change of configuration on the given staging. Setting will be applied on all available HTTP methods.
def get_patch_op(self, keypath, value, op='replace'): """ Return an object that describes a change of configuration on the given staging. Setting will be applied on all available HTTP methods. """ if isinstance(value, bool): value = str(value).lower() return {...
Generator that allows to iterate per every available apis.
def get_rest_apis(self, project_name): """ Generator that allows to iterate per every available apis. """ all_apis = self.apigateway_client.get_rest_apis( limit=500 ) for api in all_apis['items']: if api['name'] != project_name: co...
Delete a deployed REST API Gateway.
def undeploy_api_gateway(self, lambda_name, domain_name=None, base_path=None): """ Delete a deployed REST API Gateway. """ print("Deleting API Gateway..") api_id = self.get_api_id(lambda_name) if domain_name: # XXX - Remove Route53 smartly here? ...
Update CloudWatch metrics configuration.
def update_stage_config( self, project_name, stage_name, cloudwatch_log_level, cloudwatch_data_trace, cloudwatch_metrics_enabled ...
Delete the CF stack managed by Zappa.
def delete_stack(self, name, wait=False): """ Delete the CF stack managed by Zappa. """ try: stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0] except: # pragma: no cover print('No Zappa stack named {0}'.format(name)) return Fa...
Build the entire CF stack. Just used for the API Gateway but could be expanded in the future.
def create_stack_template( self, lambda_arn, lambda_name, api_key_required, iam_authorization, authorizer, cors_options=None, ...
Update or create the CF stack managed by Zappa.
def update_stack(self, name, working_bucket, wait=False, update_only=False, disable_progress=False): """ Update or create the CF stack managed by Zappa. """ capabilities = [] template = name + '-template-' + str(int(time.time())) + '.json' with open(template, 'wb') as ou...
Given a name describes CloudFront stacks and returns dict of the stack Outputs else returns an empty dict.
def stack_outputs(self, name): """ Given a name, describes CloudFront stacks and returns dict of the stack Outputs , else returns an empty dict. """ try: stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0] return {x['OutputKey']: x['OutputV...
Given a lambda_name and stage_name return a valid API URL.
def get_api_url(self, lambda_name, stage_name): """ Given a lambda_name and stage_name, return a valid API URL. """ 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...
Given a lambda_name return the API id.
def get_api_id(self, lambda_name): """ Given a lambda_name, return the API id. """ try: response = self.cf_client.describe_stack_resource(StackName=lambda_name, LogicalResourceId='Api') return response[...
Creates the API GW domain and returns the resulting DNS name.
def create_domain_name(self, domain_name, certificate_name, certificate_body=None, certificate_private_key=None, certificate_chain=None, certificate_arn=None,...
Updates Route53 Records following GW domain creation
def update_route53_records(self, domain_name, dns_name): """ Updates Route53 Records following GW domain creation """ 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...
This updates your certificate information for an existing domain with similar arguments to boto s update_domain_name API Gateway api.
def update_domain_name(self, domain_name, certificate_name=None, certificate_body=None, certificate_private_key=None, certificate_chain=None, certificate_arn=...
Update domain base path mapping on API Gateway if it was changed
def update_domain_base_path_mapping(self, domain_name, lambda_name, stage, base_path): """ Update domain base path mapping on API Gateway if it was changed """ api_id = self.get_api_id(lambda_name) if not api_id: print("Warning! Can't update base path mapping!") ...
Same behaviour of list_host_zones but transparently handling pagination.
def get_all_zones(self): """Same behaviour of list_host_zones, but transparently handling pagination.""" zones = {'HostedZones': []} new_zones = self.route53.list_hosted_zones(MaxItems='100') while new_zones['IsTruncated']: zones['HostedZones'] += new_zones['HostedZones'] ...
Scan our hosted zones for the record of a given name.
def get_domain_name(self, domain_name, route53=True): """ Scan our hosted zones for the record of a given name. Returns the record entry, else None. """ # Make sure api gateway domain is present try: self.apigateway_client.get_domain_name(domainName=domain_n...
Given our role name get and set the credentials_arn.
def get_credentials_arn(self): """ Given our role name, get and set the credentials_arn. """ role = self.iam.Role(self.role_name) self.credentials_arn = role.arn return role, self.credentials_arn
Create and defines the IAM roles and policies necessary for Zappa.
def create_iam_roles(self): """ Create and defines the IAM roles and policies necessary for Zappa. If the IAM role already exists, it will be updated if necessary. """ attach_policy_obj = json.loads(self.attach_policy) assume_policy_obj = json.loads(self.assume_policy) ...
Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates.
def _clear_policy(self, lambda_name): """ Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates. """ try: policy_response = self.lambda_client.get_policy( FunctionName=lambda_name ) if p...
Create permissions to link to an event.
def create_event_permission(self, lambda_name, principal, source_arn): """ Create permissions to link to an event. Related: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html """ logger.debug('Adding new permission to invoke Lambda function: ...
Given a Lambda ARN name and a list of events schedule this as CloudWatch Events.
def schedule_events(self, lambda_arn, lambda_name, events, default=True): """ Given a Lambda ARN, name and a list of events, schedule this as CloudWatch Events. 'events' is a list of dictionaries, where the dict must contains the string of a 'function' and the string of the event 'expre...
Returns an AWS - valid Lambda event name.
def get_event_name(lambda_name, name): """ Returns an AWS-valid Lambda event name. """ return '{prefix:.{width}}-{postfix}'.format(prefix=lambda_name, width=max(0, 63 - len(name)), postfix=name)[:64]
Returns an AWS - valid CloudWatch rule name using a digest of the event name lambda name and function. This allows support for rule names that may be longer than the 64 char limit.
def get_hashed_rule_name(event, function, lambda_name): """ Returns an AWS-valid CloudWatch rule name using a digest of the event name, lambda name, and function. This allows support for rule names that may be longer than the 64 char limit. """ event_name = event.get('name', func...
Delete a CWE rule.
def delete_rule(self, rule_name): """ Delete a CWE rule. This deletes them, but they will still show up in the AWS console. Annoying. """ logger.debug('Deleting existing rule {}'.format(rule_name)) # All targets must be removed before # we can actually...
Get all of the rule names associated with a lambda function.
def get_event_rule_names_for_lambda(self, lambda_arn): """ Get all of the rule names associated with a lambda function. """ response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn) rule_names = response['RuleNames'] # Iterate when the results are pagi...
Get all of the rule details associated with this function.
def get_event_rules_for_lambda(self, lambda_arn): """ Get all of the rule details associated with this function. """ 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]
Given a list of events unschedule these CloudWatch Events.
def unschedule_events(self, events, lambda_arn=None, lambda_name=None, excluded_source_services=None): excluded_source_services = excluded_source_services or [] """ Given a list of events, unschedule these CloudWatch Events. 'events' is a list of dictionaries, where the dict must contai...
Create the SNS - based async topic.
def create_async_sns_topic(self, lambda_name, lambda_arn): """ Create the SNS-based async topic. """ topic_name = get_topic_name(lambda_name) # Create SNS topic topic_arn = self.sns_client.create_topic( Name=topic_name)['TopicArn'] # Create subscriptio...
Remove the async SNS topic.
def remove_async_sns_topic(self, lambda_name): """ Remove the async SNS topic. """ topic_name = get_topic_name(lambda_name) removed_arns = [] for sub in self.sns_client.list_subscriptions()['Subscriptions']: if topic_name in sub['TopicArn']: se...
Create the DynamoDB table for async task return values
def create_async_dynamodb_table(self, table_name, read_capacity, write_capacity): """ Create the DynamoDB table for async task return values """ try: dynamodb_table = self.dynamodb_client.describe_table(TableName=table_name) return False, dynamodb_table #...
Fetch the CloudWatch logs for a given Lambda name.
def fetch_logs(self, lambda_name, filter_pattern='', limit=10000, start_time=0): """ Fetch the CloudWatch logs for a given Lambda name. """ log_name = '/aws/lambda/' + lambda_name streams = self.logs_client.describe_log_streams( logGroupName=log_name, desc...
Filter all log groups that match the name given in log_filter.
def remove_log_group(self, group_name): """ Filter all log groups that match the name given in log_filter. """ print("Removing log group: {}".format(group_name)) try: self.logs_client.delete_log_group(logGroupName=group_name) except botocore.exceptions.ClientE...
Removed all logs that are assigned to a given rest api id.
def remove_api_gateway_logs(self, project_name): """ Removed all logs that are assigned to a given rest api id. """ 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_...
Get the Hosted Zone ID for a given domain.
def get_hosted_zone_id_for_domain(self, domain): """ Get the Hosted Zone ID for a given domain. """ all_zones = self.get_all_zones() return self.get_best_match_zone(all_zones, domain)
Return zone id which name is closer matched with domain name.
def get_best_match_zone(all_zones, domain): """Return zone id which name is closer matched with domain name.""" # 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'][...
Remove DNS challenge TXT.
def remove_dns_challenge_txt(self, zone_id, domain, txt_challenge): """ Remove DNS challenge TXT. """ print("Deleting DNS challenge..") resp = self.route53.change_resource_record_sets( HostedZoneId=zone_id, ChangeBatch=self.get_dns_challenge_change_batch('...
Load AWS credentials.
def load_credentials(self, boto_session=None, profile_name=None): """ Load AWS credentials. An optional boto_session can be provided, but that's usually for testing. An optional profile_name can be provided for config files that have multiple sets of credentials. """ ...
Main cert installer path.
def get_cert_and_update_domain( zappa_instance, lambda_name, api_stage, domain=None, manual=False, ): """ Main cert installe...
Parse account key to get public key
def parse_account_key(): """Parse account key to get public 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_output...
Parse certificate signing request for domains
def parse_csr(): """ Parse certificate signing request for domains """ LOGGER.info("Parsing CSR...") cmd = [ 'openssl', 'req', '-in', os.path.join(gettempdir(), 'domain.csr'), '-noout', '-text' ] devnull = open(os.devnull, 'wb') out = subprocess.check_outp...
Use regular expressions to find crypto values from parsed account key and return a header we can send to our Boulder instance.
def get_boulder_header(key_bytes): """ Use regular expressions to find crypto values from parsed account key, and return a header we can send to our Boulder instance. """ pub_hex, pub_exp = re.search( r"modulus:\n\s+00:([a-f0-9\:\s]+?)\npublicExponent: ([0-9]+)", key_bytes.decode('ut...
Agree to LE TOS
def register_account(): """ Agree to LE TOS """ 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", }) if code == 201...
Call LE to get a new signed CA.
def get_cert(zappa_instance, log=LOGGER, CA=DEFAULT_CA): """ Call LE to get a new signed 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.enco...
Loop until our challenge is verified else fail.
def verify_challenge(uri): """ Loop until our challenge is verified, else fail. """ 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}"...
Get the new certificate. Returns the signed bytes.
def sign_certificate(): """ Get the new certificate. Returns the signed bytes. """ LOGGER.info("Signing certificate...") cmd = [ 'openssl', 'req', '-in', os.path.join(gettempdir(), 'domain.csr'), '-outform', 'DER' ] devnull = open(os.devnull, 'wb') csr_der = ...
Encode cert bytes to PEM encoded cert file.
def encode_certificate(result): """ Encode cert bytes to PEM encoded cert file. """ cert_body = """-----BEGIN CERTIFICATE-----\n{0}\n-----END CERTIFICATE-----\n""".format( "\n".join(textwrap.wrap(base64.b64encode(result).decode('utf8'), 64))) signed_crt = open("{}/signed.crt".format(gettempd...
Helper function to make signed requests to Boulder
def _send_signed_request(url, payload): """ Helper function to make signed requests to Boulder """ 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 +...
Shamelessly promote our little community.
def shamelessly_promote(): """ Shamelessly promote our little community. """ 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") ...
Main program execution handler.
def handle(): # pragma: no cover """ Main program execution handler. """ 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() ...
A shortcut property for settings of a stage.
def stage_config(self): """ A shortcut property for settings of a stage. """ def get_stage_setting(stage, extended_stages=None): if extended_stages is None: extended_stages = [] if stage in extended_stages: raise RuntimeError(stag...
Forcefully override a setting set by zappa_settings ( for the current stage only ): param key: settings key: param val: value
def override_stage_config_setting(self, key, val): """ Forcefully override a setting set by zappa_settings (for the current stage only) :param key: settings key :param val: value """ self._stage_config_overrides = getattr(self, '_stage_config_overrides', {}) self....
Main function.
def handle(self, argv=None): """ Main function. Parses command, load settings and dispatches accordingly. """ desc = ('Zappa - Deploy Python applications to AWS Lambda' ' and API Gateway.\n') parser = argparse.ArgumentParser(description=desc) pa...
Given a command to execute and stage execute that command.
def dispatch_command(self, command, stage): """ Given a command to execute and stage, execute that command. """ self.api_stage = stage if command not in ['status', 'manage']: if not self.vargs.get('json', None): click.echo("Calling " + click....
Only build the package
def package(self, output=None): """ Only build the package """ # 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.p...
Only build the template file.
def template(self, lambda_arn, role_arn, output=None, json=False): """ Only build the template file. """ if not lambda_arn: raise ClickException("Lambda ARN is required to template.") if not role_arn: raise ClickException("Role ARN is required to templat...
Package your project upload it to S3 register the Lambda function and create the API Gateway routes.
def deploy(self, source_zip=None): """ Package your project, upload it to S3, register the Lambda function and create the API Gateway routes. """ if not source_zip: # Make sure we're in a venv. self.check_venv() # Execute the prebuild script...
Repackage and update the function code.
def update(self, source_zip=None, no_upload=False): """ Repackage and update the function code. """ if not source_zip: # Make sure we're in a venv. self.check_venv() # Execute the prebuild script if self.prebuild_script: s...
Rollsback the currently deploy lambda code to a previous revision.
def rollback(self, revision): """ Rollsback the currently deploy lambda code to a previous revision. """ print("Rolling back..") self.zappa.rollback_lambda_function_version( self.lambda_name, versions_back=revision) print("Done!")
Tail this function s logs.
def tail(self, since, filter_pattern, limit=10000, keep_open=True, colorize=True, http=False, non_http=False, force_colorize=False): """ Tail this function's logs. if keep_open, do so repeatedly, printing any new logs """ try: since_stamp = string_to_timestamp(since...
Tear down an existing deployment.
def undeploy(self, no_confirm=False, remove_logs=False): """ Tear down an existing deployment. """ 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_al...
Update any cognito triggers
def update_cognito_triggers(self): """ Update any cognito triggers """ if self.cognito: user_pool = self.cognito.get('user_pool') triggers = self.cognito.get('triggers', []) lambda_configs = set() for trigger in triggers: la...
Given a a list of functions and a schedule to execute them setup up regular execution.
def schedule(self): """ Given a a list of functions and a schedule to execute them, setup up regular execution. """ events = self.stage_config.get('events', []) if events: if not isinstance(events, list): # pragma: no cover print("Events must...
Given a a list of scheduled functions tear down their regular execution.
def unschedule(self): """ Given a a list of scheduled functions, tear down their regular execution. """ # Run even if events are not defined to remove previously existing ones (thus default to []). events = self.stage_config.get('events', []) if not isinstance(...
Invoke a remote function.
def invoke(self, function_name, raw_python=False, command=None, no_color=False): """ Invoke a remote function. """ # 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...
Formats correctly the string output from the invoke () method replacing line breaks and tabs when necessary.
def format_invoke_command(self, string): """ Formats correctly the string output from the invoke() method, replacing line breaks and tabs when necessary. """ string = string.replace('\\n', '\n') formated_response = '' for line in string.splitlines(): ...
Apply various heuristics to return a colorized version the invoke command string. If these fail simply return the string in plaintext.
def colorize_invoke_command(self, string): """ Apply various heuristics to return a colorized version the invoke command string. If these fail, simply return the string in plaintext. Inspired by colorize_log_entry(). """ final_string = string try: ...
Describe the status of the current deployment.
def status(self, return_json=False): """ Describe the status of the current deployment. """ def tabular_print(title, value): """ Convenience function for priting formatted table items. """ click.echo('%-*s%s' % (32, click.style("\t" + titl...
Make sure the environment contains only strings
def check_environment(self, environment): """ Make sure the environment contains only strings (since putenv needs a string) """ non_strings = [] for (k,v) in environment.items(): if not isinstance(v, basestring): non_strings.append(k) ...