desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create the API Gateway for this Zappa deployment. Returns the new RestAPI CF resource.'
def create_api_gateway_routes(self, lambda_arn, api_name=None, api_key_required=False, authorization_type='NONE', authorizer=None, cors_options=None, description=None):
restapi = troposphere.apigateway.RestApi('Api') restapi.Name = (api_name or lambda_arn.split(':')[(-1)]) if (not description): description = 'Created automatically by Zappa.' restapi.Description = description self.cf_template.add_resource(restapi) root_id = troposphere.GetAtt(re...
'Create Authorizer for API gateway'
def create_authorizer(self, restapi, uri, authorizer):
authorizer_type = authorizer.get('type', 'TOKEN').upper() identity_validation_expression = authorizer.get('validation_expression', None) authorizer_resource = troposphere.apigateway.Authorizer('Authorizer') authorizer_resource.RestApiId = troposphere.Ref(restapi) authorizer_resource.Name = authorize...
'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, authorizer_resource, depth):
for method_name in self.http_methods: method = troposphere.apigateway.Method((method_name + str(depth))) method.RestApiId = troposphere.Ref(restapi) if (type(resource) is troposphere.apigateway.Resource): method.ResourceId = troposphere.Ref(resource) else: met...
'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):
if (config is True): config = {} method_name = 'OPTIONS' method = troposphere.apigateway.Method((method_name + str(depth))) method.RestApiId = troposphere.Ref(restapi) if (type(resource) is troposphere.apigateway.Resource): method.ResourceId = troposphere.Ref(resource) else: ...
'Deploy the API Gateway! Return the deployed API URL.'
def deploy_api_gateway(self, api_id, stage_name, stage_description='', description='', cache_cluster_enabled=False, cache_cluster_size='0.5', variables=None, cloudwatch_log_level='OFF', cloudwatch_data_trace=False, cloudwatch_metrics_enabled=False, cache_cluster_ttl=300, cache_cluster_encrypted=False):
print('Deploying API Gateway..') self.apigateway_client.create_deployment(restApiId=api_id, stageName=stage_name, stageDescription=stage_description, description=description, cacheClusterEnabled=cache_cluster_enabled, cacheClusterSize=cache_cluster_size, variables=(variables or {})) if (cloudwatch_log...
'Add binary support'
def add_binary_support(self, api_id, cors=False):
response = self.apigateway_client.get_rest_api(restApiId=api_id) if (('binaryMediaTypes' not in response) or ('*/*' not in response['binaryMediaTypes'])): self.apigateway_client.update_rest_api(restApiId=api_id, patchOperations=[{'op': 'add', 'path': '/binaryMediaTypes/*~1*'}]) if cors: resp...
'Remove binary support'
def remove_binary_support(self, api_id, cors=False):
response = self.apigateway_client.get_rest_api(restApiId=api_id) if (('binaryMediaTypes' in response) and ('*/*' in response['binaryMediaTypes'])): self.apigateway_client.update_rest_api(restApiId=api_id, patchOperations=[{'op': 'remove', 'path': '/binaryMediaTypes/*~1*'}]) if cors: response...
'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):
response = self.apigateway_client.get_api_keys(limit=500) stage_key = '{}/{}'.format(api_id, stage_name) for api_key in response.get('items'): if (stage_key in api_key.get('stageKeys')): (yield api_key.get('id'))
'Create new API key and link it with an api_id and a stage_name'
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=[{'restApiId': '{}'.format(api_id), 'stageName': '{}'.format(stage_name)}]) print('Created a new x-api-key: {}'.format(response['id'...
'Remove a generated API key for api_id and stage_name'
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_client.delete_api_key(apiKey='{}'.format(api_key['id']))
'Add api stage to Api key'
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', 'value': '{}/{}'.format(api_id, stage_name)}])
'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'):
if isinstance(value, bool): value = str(value).lower() return {'op': op, 'path': '/*/*/{}'.format(keypath), 'value': value}
'Generator that allows to iterate per every available apis.'
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)
'Delete a deployed REST API Gateway.'
def undeploy_api_gateway(self, lambda_name, domain_name=None):
print('Deleting API Gateway..') api_id = self.get_api_id(lambda_name) if domain_name: try: self.apigateway_client.delete_base_path_mapping(domainName=domain_name, basePath='(none)') except Exception as e: pass was_deleted = self.delete_stack(lambda_name, wai...
'Update CloudWatch metrics configuration.'
def update_stage_config(self, project_name, stage_name, cloudwatch_log_level, cloudwatch_data_trace, cloudwatch_metrics_enabled):
if (cloudwatch_log_level not in self.cloudwatch_log_levels): cloudwatch_log_level = 'OFF' for api in self.get_rest_apis(project_name): self.apigateway_client.update_stage(restApiId=api['id'], stageName=stage_name, patchOperations=[self.get_patch_op('logging/loglevel', cloudwatch_log_level), self...
'Delete the CF stack managed by Zappa.'
def delete_stack(self, name, wait=False):
try: stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0] except: print('No Zappa stack named {0}'.format(name)) return False tags = {x['Key']: x['Value'] for x in stack['Tags']} if (tags.get('ZappaProject') == name): self.cf_client.delete_stack...
'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, description=None):
auth_type = 'NONE' if (iam_authorization and authorizer): logger.warn('Both IAM Authorization and Authorizer are specified, this is not possible. Setting Auth method to IAM Authorization') authorizer = None auth_type = 'AWS_IAM' elif ia...
'Update or create the CF stack managed by Zappa.'
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(bytes(self.cf_template.to_json(indent=None, separators=(',', ':')), 'utf-8')) self.upload_to_s3(template, working_bucket, disable_progress=disable_progress) ur...
'Given a name, describes CloudFront stacks and returns dict of the stack Outputs , else returns an empty dict.'
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 {}
'Given a lambda_name and stage_name, return a valid API URL.'
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: return None
'Given a lambda_name, return the API id.'
def get_api_id(self, lambda_name):
try: response = self.cf_client.describe_stack_resource(StackName=lambda_name, LogicalResourceId='Api') return response['StackResourceDetail'].get('PhysicalResourceId', None) except: try: response = self.apigateway_client.get_rest_apis(limit=500) for item in respon...
'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, lambda_name=None, stage=None):
if (not certificate_arn): agw_response = self.apigateway_client.create_domain_name(domainName=domain_name, certificateName=certificate_name, certificateBody=certificate_body, certificatePrivateKey=certificate_private_key, certificateChain=certificate_chain) else: agw_response = self.apigateway_c...
'Updates Route53 Records following GW domain creation'
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_set = {'Name': domain_name, 'Type': 'A', 'AliasTarget': {'HostedZoneId': 'Z2FDTNDATAQYW2', 'DNSName': dns_name, 'EvaluateTarge...
'This updates your certificate information for an existing domain, with similar arguments to boto\'s update_domain_name API Gateway api. It returns the resulting new domain information including the new certificate\'s ARN if created during this process. Previously, this method involved downtime that could take up to 40...
def update_domain_name(self, domain_name, certificate_name=None, certificate_body=None, certificate_private_key=None, certificate_chain=None, certificate_arn=None, lambda_name=None, stage=None, route53=True):
print('Updating domain name!') certificate_name = (certificate_name + str(time.time())) api_gateway_domain = self.apigateway_client.get_domain_name(domainName=domain_name) if ((not certificate_arn) and certificate_body and certificate_private_key and certificate_chain): acm_certificate = s...
'Scan our hosted zones for the record of a given name. Returns the record entry, else None.'
def get_domain_name(self, domain_name):
try: self.apigateway_client.get_domain_name(domainName=domain_name) except Exception: return None try: zones = self.route53.list_hosted_zones() for zone in zones['HostedZones']: records = self.route53.list_resource_record_sets(HostedZoneId=zone['Id']) ...
'Given our role name, get and set the credentials_arn.'
def get_credentials_arn(self):
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. If the IAM role already exists, it will be updated if necessary.'
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_obj['Statement'].append(dict(permission)) self.attach_policy = json.dumps(attach_policy_obj) ...
'Remove obsolete policy statements to prevent policy from bloating over the limit after repeated updates.'
def _clear_policy(self, lambda_name):
try: policy_response = self.lambda_client.get_policy(FunctionName=lambda_name) if (policy_response['ResponseMetadata']['HTTPStatusCode'] == 200): statement = json.loads(policy_response['Policy'])['Statement'] for s in statement: delete_response = self.lambda_c...
'Create permissions to link to an event. Related: http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-configure-event-source.html'
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_name, StatementId=''.join((random.choice((string.ascii_uppercase + string.digits)) for _ in range(8))), Action='lambda:InvokeFu...
'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 \'expression\', and an optional \'name\' and \'description\'. Expressions can be in rate or cron format: http://...
def schedule_events(self, lambda_arn, lambda_name, events, default=True):
pull_services = ['dynamodb', 'kinesis'] self.unschedule_events(lambda_name=lambda_name, lambda_arn=lambda_arn, events=events, excluded_source_services=pull_services) for event in events: function = event['function'] expression = event.get('expression', None) expressions = event.get('...
'Returns an AWS-valid Lambda event name.'
@staticmethod def get_event_name(lambda_name, 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.'
@staticmethod 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)
'Delete a CWE rule. This deletes them, but they will still show up in the AWS console. Annoying.'
def delete_rule(self, rule_name):
logger.debug('Deleting existing rule {}'.format(rule_name)) try: targets = self.events_client.list_targets_by_rule(Rule=rule_name) except botocore.exceptions.ClientError as e: error_code = e.response['Error']['Code'] if (error_code == 'AccessDeniedException'): ra...
'Get all of the rule names associated with a lambda 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'] while ('NextToken' in response): response = self.events_client.list_rule_names_by_target(TargetArn=lambda_arn, NextToken=response['NextToken']) rule_names.extend(response['RuleNam...
'Get all of the rule details associated with this 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]
'Create the SNS-based async topic.'
def create_async_sns_topic(self, lambda_name, lambda_arn):
topic_name = get_topic_name(lambda_name) topic_arn = self.sns_client.create_topic(Name=topic_name)['TopicArn'] self.sns_client.subscribe(TopicArn=topic_arn, Protocol='lambda', Endpoint=lambda_arn) self.create_event_permission(lambda_name=lambda_name, principal='sns.amazonaws.com', source_arn=topic_arn) ...
'Remove the async SNS topic.'
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_client.delete_topic(TopicArn=sub['TopicArn']) removed_arns.append(sub['TopicArn']) return removed_arns...
'Fetch the CloudWatch logs for a given Lambda name.'
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, orderBy='LastEventTime') all_streams = streams['logStreams'] all_names = [stream['logStreamName'] for stream in all_streams] events = [] response = {} while ((not...
'Filter all log groups that match the name given in log_filter.'
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 remove '{}' because of: {}".format(group_name, e))
'Remove all logs that are assigned to a given lambda function id.'
def remove_lambda_function_logs(self, lambda_function_name):
self.remove_log_group('/aws/lambda/{}'.format(lambda_function_name))
'Removed all logs that are assigned to a given rest api id.'
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_{}/{}'.format(rest_api['id'], stage['stageName']))
'Get the Hosted Zone ID for a given domain.'
def get_hosted_zone_id_for_domain(self, domain):
all_zones = self.route53.list_hosted_zones() return self.get_best_match_zone(all_zones, domain)
'Return zone id which name is closer matched with domain name.'
@staticmethod def get_best_match_zone(all_zones, domain):
public_zones = [zone for zone in all_zones['HostedZones'] if (not zone['Config']['PrivateZone'])] zones = {zone['Name'][:(-1)]: zone['Id'] for zone in public_zones if (zone['Name'][:(-1)] in domain)} if zones: keys = max(zones.keys(), key=(lambda a: len(a))) return zones[keys] else: ...
'Set DNS challenge TXT.'
def set_dns_challenge_txt(self, zone_id, domain, txt_challenge):
print('Setting DNS challenge..') resp = self.route53.change_resource_record_sets(HostedZoneId=zone_id, ChangeBatch=self.get_dns_challenge_change_batch('UPSERT', domain, txt_challenge)) return resp
'Remove DNS challenge TXT.'
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('DELETE', domain, txt_challenge)) return resp
'Given action, domain and challege, return a change batch to use with route53 call. :param action: DELETE | UPSERT :param domain: domain name :param txt_challenge: challenge :return: change set for a given action, domain and TXT challenge.'
@staticmethod def get_dns_challenge_change_batch(action, domain, txt_challenge):
return {'Changes': [{'Action': action, 'ResourceRecordSet': {'Name': '_acme-challenge.{0}'.format(domain), 'Type': 'TXT', 'TTL': 60, 'ResourceRecords': [{'Value': '"{0}"'.format(txt_challenge)}]}}]}
'Spawn a PDB shell.'
def shell(self):
import pdb pdb.set_trace()
'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.'
def load_credentials(self, boto_session=None, profile_name=None):
if (not boto_session): if profile_name: self.boto_session = boto3.Session(profile_name=profile_name, region_name=self.aws_region) elif (os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY')): region_name = (os.environ.get('AWS_DEFAULT_REGION') or sel...
''
def __init__(self, lambda_function_name=None, aws_region=None, **kwargs):
if kwargs.get('boto_session'): self.client = kwargs.get('boto_session').client('lambda') else: self.client = LAMBDA_CLIENT self.lambda_function_name = lambda_function_name self.aws_region = aws_region
'Create the message object and pass it to the actual sender.'
def send(self, task_path, args, kwargs):
message = {'task_path': task_path, 'args': args, 'kwargs': kwargs} self._send(message) return self
'Given a message, directly invoke the lamdba function for this task.'
def _send(self, message):
message['command'] = 'zappa.async.route_lambda_task' payload = json.dumps(message).encode('utf-8') if (len(payload) > 128000): raise AsyncException('Payload too large for async Lambda call') self.response = self.client.invoke(FunctionName=self.lambda_function_name, InvocationTy...
'Given a message, publish to this topic.'
def _send(self, message):
message['command'] = 'zappa.async.route_sns_task' payload = json.dumps(message).encode('utf-8') if (len(payload) > 256000): raise AsyncException('Payload too large for SNS') self.response = self.client.publish(TargetArn=self.arn, Message=payload) self.sent = self.response.get('Me...
'A shortcut property for settings of a stage.'
@property 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 + u' has already been extended to these settings. There is a circular extends ...
'Returns zappa_settings we forcefully override for the current stage set by `self.override_stage_config_setting(key, value)`'
@property def stage_config_overrides(self):
return getattr(self, u'_stage_config_overrides', {}).get(self.api_stage, {})
'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):
self._stage_config_overrides = getattr(self, u'_stage_config_overrides', {}) self._stage_config_overrides.setdefault(self.api_stage, {})[key] = val
'Main function. Parses command, load settings and dispatches accordingly.'
def handle(self, argv=None):
desc = u'Zappa - Deploy Python applications to AWS Lambda and API Gateway.\n' parser = argparse.ArgumentParser(description=desc) parser.add_argument(u'-v', u'--version', action=u'version', version=pkg_resources.get_distribution(u'zappa').version, help=u'Print the zappa ...
'Given a command to execute and stage, execute that command.'
def dispatch_command(self, command, stage):
self.api_stage = stage if (command not in [u'status', u'manage']): if (not self.vargs[u'json']): click.echo(((((u'Calling ' + click.style(command, fg=u'green', bold=True)) + u' for stage ') + click.style(self.api_stage, bold=True)) + u'..')) if self.vargs.get(u'app_function',...
'Only build the package'
def package(self, output=None):
self.check_venv() self.override_stage_config_setting(u'delete_local_zip', False) if self.prebuild_script: self.execute_prebuild_script() self.create_package(output) self.callback(u'zip') size = human_size(os.path.getsize(self.zip_path)) click.echo((((((click.style(u'Package create...
'Only build the template file.'
def template(self, lambda_arn, role_arn, output=None, json=False):
if (not lambda_arn): raise ClickException(u'Lambda ARN is required to template.') if (not role_arn): raise ClickException(u'Role ARN is required to template.') self.zappa.credentials_arn = role_arn template = self.zappa.create_stack_template(lambda_arn=lambd...
'Package your project, upload it to S3, register the Lambda function and create the API Gateway routes.'
def deploy(self):
self.check_venv() if self.prebuild_script: self.execute_prebuild_script() deployed_versions = self.zappa.get_lambda_function_versions(self.lambda_name) if (len(deployed_versions) > 0): raise ClickException(((((u'This application is ' + click.style(u'already deployed', fg=u're...
'Repackage and update the function code.'
def update(self):
self.check_venv() if self.prebuild_script: self.execute_prebuild_script() try: updated_time = 1472581018 function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name) conf = function_response[u'Configuration'] last_updated = parser.parse(con...
'Rollsback the currently deploy lambda code to a previous revision.'
def rollback(self, revision):
print u'Rolling back..' self.zappa.rollback_lambda_function_version(self.lambda_name, versions_back=revision) print u'Done!'
'Tail this function\'s logs. if keep_open, do so repeatedly, printing any new logs'
def tail(self, since, filter_pattern, limit=10000, keep_open=True, colorize=True, http=False, non_http=False):
try: since_stamp = string_to_timestamp(since) last_since = since_stamp while True: new_logs = self.zappa.fetch_logs(self.lambda_name, start_time=since_stamp, limit=limit, filter_pattern=filter_pattern) new_logs = [e for e in new_logs if (e[u'timestamp'] > last_since)]...
'Tear down an exiting deployment.'
def undeploy(self, no_confirm=False, remove_logs=False):
if (not no_confirm): confirm = input(u'Are you sure you want to undeploy? [y/n] ') if (confirm != u'y'): return if self.use_apigateway: if remove_logs: self.zappa.remove_api_gateway_logs(self.lambda_name) domain_name = self.stage_co...
'Given a a list of functions and a schedule to execute them, setup up regular execution.'
def schedule(self):
events = self.stage_config.get(u'events', []) if events: if (not isinstance(events, list)): print u'Events must be supplied as a list.' return for event in events: self.collision_warning(event.get(u'function')) if self.stage_config.get(u'keep_war...
'Given a a list of scheduled functions, tear down their regular execution.'
def unschedule(self):
events = self.stage_config.get(u'events', []) if (not isinstance(events, list)): print u'Events must be supplied as a list.' return function_arn = None try: function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name) function...
'Invoke a remote function.'
def invoke(self, function_name, raw_python=False, command=None, no_color=False):
key = (command if (command is not None) else u'command') if raw_python: command = {u'raw_command': function_name} else: command = {key: function_name} import json as json response = self.zappa.invoke_lambda_function(self.lambda_name, json.dumps(command), invocation_type=u'RequestResp...
'Formats correctly the string ouput from the invoke() method, replacing line breaks and tabs when necessary.'
def format_invoke_command(self, string):
string = string.replace(u'\\n', u'\n') formated_response = u'' for line in string.splitlines(): if line.startswith(u'REPORT'): line = line.replace(u' DCTB ', u'\n') if line.startswith(u'[DEBUG]'): line = line.replace(u' DCTB ', u' ') formated_response += (l...
'Apply various heuristics to return a colorized version the invoke comman string. If these fail, simply return the string in plaintext. Inspired by colorize_log_entry().'
def colorize_invoke_command(self, string):
final_string = string try: try: for token in [u'START', u'END', u'REPORT', u'[DEBUG]']: if (token in final_string): format_string = (u'{}' if (token == u'[DEBUG]') else u'[{}]') final_string = final_string.replace(token, click.style(for...
'Describe the status of the current deployment.'
def status(self, return_json=False):
def tabular_print(title, value): u'\n Convience function for priting formatted table items.\n ' click.echo((u'%-*s%s' % (32, (click.style((u' DCTB ' + title), fg=u'green') + u':'), str(val...
'Make sure the stage name matches the AWS-allowed pattern (calls to apigateway_client.create_deployment, will fail with error message "ClientError: An error occurred (BadRequestException) when calling the CreateDeployment operation: Stage name only allows a-zA-Z0-9_" if the pattern does not match)'
def check_stage_name(self, stage_name):
if self.stage_name_env_pattern.match(stage_name): return True raise ValueError(u'AWS requires stage name to match a-zA-Z0-9_')
'Make sure the environment contains only strings (since putenv needs a string)'
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(u'The following environment variables are not strings: {}'.format(u', '.join(non_strings))) else: ret...
'Initialize a new Zappa project by creating a new zappa_settings.json in a guided process. This should probably be broken up into few separate componants once it\'s stable. Testing these inputs requires monkeypatching with mock, which isn\'t pretty.'
def init(self, settings_file=u'zappa_settings.json'):
self.check_venv() if os.path.isfile(settings_file): raise ClickException(((u'This project already has a ' + click.style(u'{0!s} file'.format(settings_file), fg=u'red', bold=True)) + u'!')) click.echo(click.style(u'\n\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u...
'Register or update a domain certificate for this env.'
def certify(self, no_cleanup=False, no_confirm=True, manual=False):
if (not self.domain): raise ClickException(((u"Can't certify a domain without " + click.style(u'domain', fg=u'red', bold=True)) + u' configured!')) if (not no_confirm): confirm = input(u'Are you sure you want to certify? [y/n] ') if (confirm != u...
'Spawn a debug shell.'
def shell(self):
click.echo((((((click.style(u'NOTICE!', fg=u'yellow', bold=True) + u' This is a ') + click.style(u'local', fg=u'green', bold=True)) + u' shell, inside a ') + click.style(u'Zappa', bold=True)) + u' object!')) self.zappa.shell() return
'Allows the execution of custom code between creation of the zip file and deployment to AWS. :return: None'
def callback(self, position):
callbacks = self.stage_config.get(u'callbacks', {}) callback = callbacks.get(position) if callback: (mod_path, cb_func_name) = callback.rsplit(u'.', 1) try: if (mod_path.count(u'.') >= 1): (mod_folder_path, mod_name) = mod_path.rsplit(u'.', 1) mod_...
'Print a warning if there\'s a new Zappa version available.'
def check_for_update(self):
try: version = pkg_resources.require(u'zappa')[0].version updateable = check_new_version_available(version) if updateable: click.echo((((click.style(u'Important!', fg=u'yellow', bold=True) + u' A new version of ') + click.style(u'Zappa', bold=True)) + u' is a...
'Load the local zappa_settings file. An existing boto session can be supplied, though this is likely for testing purposes. Returns the loaded Zappa object.'
def load_settings(self, settings_file=None, session=None):
if (not settings_file): settings_file = self.get_json_or_yaml_settings() if (not os.path.isfile(settings_file)): raise ClickException(u'Please configure your zappa_settings file.') self.load_settings_file(settings_file) for stage_name in self.zappa_settings.keys(): tr...
'Return zappa_settings path as JSON or YAML (or TOML), as appropriate.'
def get_json_or_yaml_settings(self, settings_name=u'zappa_settings'):
zs_json = (settings_name + u'.json') zs_yaml = (settings_name + u'.yml') zs_toml = (settings_name + u'.toml') if ((not os.path.isfile(zs_json)) and (not os.path.isfile(zs_yaml)) and (not os.path.isfile(zs_toml))): raise ClickException(u'Please configure a zappa_settings file or ...
'Load our settings file.'
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(u'Please configure your zappa_settings file or call `zappa init`.') if (u'.yml' in settings_file): with open(settings_file) as...
'Ensure that the package can be properly configured, and then create it.'
def create_package(self, output=None):
current_file = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) handler_file = ((os.sep.join(current_file.split(os.sep)[0:]) + os.sep) + u'handler.py') if self.stage_config.get(u'slim_handler', False): self.zip_path = self.zappa.create_lambda_zip(prefix=self.lambda_name, use...
'Remove our local zip file.'
def remove_local_zip(self):
if self.stage_config.get(u'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.handler_path)): os.remove(self.handler_path) except Exception as e: s...
'Remove the local and S3 zip file after uploading and updating.'
def remove_uploaded_zip(self):
if self.stage_config.get(u'delete_s3_zip', True): self.zappa.remove_from_s3(self.zip_path, self.s3_bucket_name) if self.stage_config.get(u'slim_handler', False): self.zappa.remove_from_s3(self.handler_path, self.s3_bucket_name)
'Cleanup after the command finishes. Always called: SystemExit, KeyboardInterrupt and any other Exception that occurs.'
def on_exit(self):
if self.zip_path: if self.load_credentials: self.remove_uploaded_zip() self.remove_local_zip()
'Parse, filter and print logs to the console.'
def print_logs(self, logs, colorize=True, http=False, non_http=False):
for log in logs: timestamp = log[u'timestamp'] message = log[u'message'] if (u'START RequestId' in message): continue if (u'REPORT RequestId' in message): continue if (u'END RequestId' in message): continue if (not colorize...
'Determines if a log entry is an HTTP-formatted log string or not.'
def is_http_log_entry(self, string):
if (u'Zappa Event' in string): return False for token in string.replace(u' DCTB ', u' ').split(u' '): try: if ((token.count(u'.') is 3) and token.replace(u'.', u'').isnumeric()): return True except Exception: pass return False
'Apply various heuristics to return a colorized version of a string. If these fail, simply return the string in plaintext.'
def colorize_log_entry(self, string):
final_string = string try: inside_squares = re.findall(u'\\[([^]]*)\\]', string) for token in inside_squares: if (token in [u'CRITICAL', u'ERROR', u'WARNING', u'DEBUG', u'INFO', u'NOTSET']): final_string = final_string.replace(((u'[' + token) + u']'), ((click.style(u'...
'Parse and execute the prebuild_script from the zappa_settings.'
def execute_prebuild_script(self):
(pb_mod_path, pb_func) = self.prebuild_script.rsplit(u'.', 1) try: if (pb_mod_path.count(u'.') >= 1): (mod_folder_path, mod_name) = pb_mod_path.rsplit(u'.', 1) mod_folder_path_fragments = mod_folder_path.split(u'.') working_dir = os.path.join(os.getcwd(), *mod_folder_...
'Given a string, print a warning if this could collide with a Zappa core package module. Use for app functions and events.'
def collision_warning(self, item):
namespace_collisions = [u'zappa.', u'wsgi.', u'middleware.', u'handler.', u'util.', u'letsencrypt.', u'cli.'] for namespace_collision in namespace_collisions: if (namespace_collision in item): click.echo((((click.style(u'Warning!', fg=u'red', bold=True) + u' You may have a nam...
'Ensure we\'re inside a virtualenv.'
def check_venv(self):
if self.zappa: venv = self.zappa.get_current_venv() else: venv = Zappa.get_current_venv() if (not venv): raise ClickException((((((click.style(u'Zappa', bold=True) + u' requires an ') + click.style(u'active virtual environment', bold=True, fg=u'red')) + u'!\n') + u'Lea...
'Route all stdout to null.'
def silence(self):
sys.stdout = open(os.devnull, u'w') sys.stderr = open(os.devnull, u'w')
'We must case-mangle the Set-Cookie header name or AWS will use only a single one of these headers.'
def __call__(self, environ, start_response):
def encode_response(status, headers, exc_info=None): '\n Create an APIGW-acceptable version of our cookies.\n\n We have to use a bizarre hack that turns multiple Set-...
'Singleton instance to avoid repeat setup'
def __new__(cls, settings_name=u'zappa_settings', session=None):
if (LambdaHandler.__instance is None): if (sys.version_info[0] < 3): LambdaHandler.__instance = object.__new__(cls, settings_name, session) else: print u'Instancing..' LambdaHandler.__instance = object.__new__(cls) return LambdaHandler.__instance
'Puts the project files from S3 in /tmp and adds to path'
def load_remote_project_zip(self, project_zip_path):
project_folder = u'/tmp/{0!s}'.format(self.settings.PROJECT_NAME) if (not os.path.isdir(project_folder)): if (not self.session): boto_session = boto3.Session() else: boto_session = self.session (remote_bucket, remote_file) = parse_s3_url(project_zip_path) ...
'Attempt to read a file from s3 containing a flat json object. Adds each key->value pair as environment variables. Helpful for keeping sensitiZve or stage-specific configuration variables in s3 instead of version control.'
def load_remote_settings(self, remote_bucket, remote_file):
if (not self.session): boto_session = boto3.Session() else: boto_session = self.session s3 = boto_session.resource(u's3') try: remote_env_object = s3.Object(remote_bucket, remote_file).get() except Exception as e: print (u'Could not load remote settings ...
'Given a modular path to a function, import that module and return the function.'
@staticmethod def import_module_and_get_function(whole_function):
(module, function) = whole_function.rsplit(u'.', 1) app_module = importlib.import_module(module) app_function = getattr(app_module, function) return app_function
'Given a function and event context, detect signature and execute, returning any result.'
@staticmethod def run_function(app_function, event, context):
(args, varargs, keywords, defaults) = inspect.getargspec(app_function) num_args = len(args) if (num_args == 0): result = (app_function(event, context) if varargs else app_function()) elif (num_args == 1): result = (app_function(event, context) if varargs else app_function(event)) eli...
'Get the associated function to execute for a triggered AWS event Support S3, SNS, DynamoDB and kinesis events'
def get_function_for_aws_event(self, record):
if (u's3' in record): return record[u's3'][u'configurationId'].split(u':')[(-1)] arn = None if (u'Sns' in record): try: message = json.loads(record[u'Sns'][u'Message']) if message.get(u'command'): return message[u'command'] except ValueError: ...
'An AWS Lambda function which parses specific API Gateway input into a WSGI request, feeds it to our WSGI app, procceses the response, and returns that back to the API Gateway.'
def handler(self, event, context):
settings = self.settings if settings.DEBUG: logger.debug(u'Zappa Event: {}'.format(event)) if (event.get(u'detail-type') == u'Scheduled Event'): whole_function = event[u'resources'][0].split(u'/')[(-1)].split(u'-')[(-1)] if (u'.' in whole_function): app_function ...
'Adds a method to the internal lists of allowed or denied methods. Each object in the internal list contains a resource ARN and a condition statement. The condition statement can be null.'
def _addMethod(self, effect, verb, resource, conditions):
if ((verb != '*') and (not hasattr(HttpVerb, verb))): raise NameError((('Invalid HTTP verb ' + verb) + '. Allowed verbs in HttpVerb class')) resourcePattern = re.compile(self.pathRegex) if (not resourcePattern.match(resource)): raise NameError(((('Invalid resource ...