input
stringlengths
49
3.53k
target
stringclasses
19 values
def __init__(self, dict_): super(self.__class__, self).__init__(dict_)
def deploy( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc ) else: create_function(cfg, path_to_zip_file)
def __init__(self, dict_): super(self.__class__, self).__init__(dict_)
def deploy_s3( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function via AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) use_s3 = True s3_file = upload_s3(cfg, path_to_zip_file, use_s3) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, use_s3=use_s3, s3_file=s3_file, preserve_vpc=preserve_vpc, ) else: create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file)
def __init__(self, dict_): super(self.__class__, self).__init__(dict_)
def upload( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Uploads a new function to AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) upload_s3(cfg, path_to_zip_file)
def __init__(self, dict_): super(self.__class__, self).__init__(dict_)
def invoke( src, event_file="event.json", config_file="config.yaml", profile_name=None, verbose=False, ): """Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str alt_event: An optional argument to override which event file to use. :param bool verbose: Whether to print out verbose details. """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Set AWS_PROFILE environment variable based on `--profile` option. if profile_name: os.environ["AWS_PROFILE"] = profile_name # Load environment variables from the config file into the actual # environment. env_vars = cfg.get("environment_variables") if env_vars: for key, value in env_vars.items(): os.environ[key] = get_environment_variable_value(value) # Load and parse event file. path_to_event_file = os.path.join(src, event_file) event = read(path_to_event_file, loader=json.loads) # Tweak to allow module to import local modules try: sys.path.index(src) except ValueError: sys.path.append(src) handler = cfg.get("handler") # Inspect the handler string (<module>.<function name>) and translate it # into a function we can execute. fn = get_callable_handler_function(src, handler) timeout = cfg.get("timeout") if timeout: context = LambdaContext(cfg.get("function_name"), timeout) else: context = LambdaContext(cfg.get("function_name")) start = time.time() results = fn(event, context) end = time.time() print("{0}".format(results)) if verbose: print( "\nexecution time: {:.8f}s\nfunction execution " "timeout: {:2}s".format(end - start, cfg.get("timeout", 15)) )
def __init__(self, dict_): super(self.__class__, self).__init__(dict_)
def to_python(self, value): if not value: return []
def __init__(self, dict_): super(self.__class__, self).__init__(dict_)
def get_prep_value(self, value): return ','.join(value)
def __init__(self, dict_): super(self.__class__, self).__init__(dict_)
def get_concurrency(cfg): """Return the Reserved Concurrent Executions if present in the config""" concurrency = int(cfg.get("concurrency", 0)) return max(0, concurrency)
def __init__(self, dict_): super(self.__class__, self).__init__(dict_)
def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total)
def __init__(self, dict_): super(self.__class__, self).__init__(dict_)
def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out')
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure))
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def load_source(module_name, module_path): """Loads a python module from the path of the corresponding file.""" if sys.version_info[0] == 3 and sys.version_info[1] >= 5: import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info[0] == 3 and sys.version_info[1] < 5: import importlib.machinery loader = importlib.machinery.SourceFileLoader(module_name, module_path) module = loader.load_module() return module
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def __init__(self, field): self.field = field
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def __get__(self, instance, owner): if instance is None: raise AttributeError # ?
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value))
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None))
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def get_attname(self): return "%s_json" % self.name
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def init(src, minimal=False): """Copies template files to a given directory. :param str src: The path to output the template lambda project files. :param bool minimal: Minimal possible template files (excludes event.json). """ templates_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "project_templates", ) for filename in os.listdir(templates_path): if (minimal and filename == "event.json") or filename.endswith(".pyc"): continue dest_path = os.path.join(templates_path, filename) if not os.path.isdir(dest_path): copy(dest_path, src)
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def cleanup_old_versions( src, keep_last_versions, config_file="config.yaml", profile_name=None, ): """Deletes old deployed versions of the function in AWS Lambda. Won't delete $Latest and any aliased version :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param int keep_last_versions: The number of recent versions to keep and not delete """ if keep_last_versions <= 0: print("Won't delete all versions. Please do this manually") else: path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") client = get_client( "lambda", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) response = client.list_versions_by_function( FunctionName=cfg.get("function_name"), ) versions = response.get("Versions") if len(response.get("Versions")) < keep_last_versions: print("Nothing to delete. (Too few versions published)") else: version_numbers = [ elem.get("Version") for elem in versions[1:-keep_last_versions] ] for version_number in version_numbers: try: client.delete_function( FunctionName=cfg.get("function_name"), Qualifier=version_number, ) except botocore.exceptions.ClientError as e: print(f"Skipping Version {version_number}: {e}")
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def deploy( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc ) else: create_function(cfg, path_to_zip_file)
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def deploy_s3( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function via AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) use_s3 = True s3_file = upload_s3(cfg, path_to_zip_file, use_s3) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, use_s3=use_s3, s3_file=s3_file, preserve_vpc=preserve_vpc, ) else: create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file)
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def upload( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Uploads a new function to AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) upload_s3(cfg, path_to_zip_file)
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def invoke( src, event_file="event.json", config_file="config.yaml", profile_name=None, verbose=False, ): """Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str alt_event: An optional argument to override which event file to use. :param bool verbose: Whether to print out verbose details. """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Set AWS_PROFILE environment variable based on `--profile` option. if profile_name: os.environ["AWS_PROFILE"] = profile_name # Load environment variables from the config file into the actual # environment. env_vars = cfg.get("environment_variables") if env_vars: for key, value in env_vars.items(): os.environ[key] = get_environment_variable_value(value) # Load and parse event file. path_to_event_file = os.path.join(src, event_file) event = read(path_to_event_file, loader=json.loads) # Tweak to allow module to import local modules try: sys.path.index(src) except ValueError: sys.path.append(src) handler = cfg.get("handler") # Inspect the handler string (<module>.<function name>) and translate it # into a function we can execute. fn = get_callable_handler_function(src, handler) timeout = cfg.get("timeout") if timeout: context = LambdaContext(cfg.get("function_name"), timeout) else: context = LambdaContext(cfg.get("function_name")) start = time.time() results = fn(event, context) end = time.time() print("{0}".format(results)) if verbose: print( "\nexecution time: {:.8f}s\nfunction execution " "timeout: {:2}s".format(end - start, cfg.get("timeout", 15)) )
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def to_python(self, value): if not value: return []
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def get_prep_value(self, value): return ','.join(value)
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def get_concurrency(cfg): """Return the Reserved Concurrent Executions if present in the config""" concurrency = int(cfg.get("concurrency", 0)) return max(0, concurrency)
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total)
def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e
def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out')
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure))
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def load_source(module_name, module_path): """Loads a python module from the path of the corresponding file.""" if sys.version_info[0] == 3 and sys.version_info[1] >= 5: import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info[0] == 3 and sys.version_info[1] < 5: import importlib.machinery loader = importlib.machinery.SourceFileLoader(module_name, module_path) module = loader.load_module() return module
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def __init__(self, field): self.field = field
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def __get__(self, instance, owner): if instance is None: raise AttributeError # ?
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value))
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None))
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def get_attname(self): return "%s_json" % self.name
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def init(src, minimal=False): """Copies template files to a given directory. :param str src: The path to output the template lambda project files. :param bool minimal: Minimal possible template files (excludes event.json). """ templates_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "project_templates", ) for filename in os.listdir(templates_path): if (minimal and filename == "event.json") or filename.endswith(".pyc"): continue dest_path = os.path.join(templates_path, filename) if not os.path.isdir(dest_path): copy(dest_path, src)
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def cleanup_old_versions( src, keep_last_versions, config_file="config.yaml", profile_name=None, ): """Deletes old deployed versions of the function in AWS Lambda. Won't delete $Latest and any aliased version :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param int keep_last_versions: The number of recent versions to keep and not delete """ if keep_last_versions <= 0: print("Won't delete all versions. Please do this manually") else: path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") client = get_client( "lambda", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) response = client.list_versions_by_function( FunctionName=cfg.get("function_name"), ) versions = response.get("Versions") if len(response.get("Versions")) < keep_last_versions: print("Nothing to delete. (Too few versions published)") else: version_numbers = [ elem.get("Version") for elem in versions[1:-keep_last_versions] ] for version_number in version_numbers: try: client.delete_function( FunctionName=cfg.get("function_name"), Qualifier=version_number, ) except botocore.exceptions.ClientError as e: print(f"Skipping Version {version_number}: {e}")
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def deploy( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc ) else: create_function(cfg, path_to_zip_file)
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def deploy_s3( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function via AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) use_s3 = True s3_file = upload_s3(cfg, path_to_zip_file, use_s3) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, use_s3=use_s3, s3_file=s3_file, preserve_vpc=preserve_vpc, ) else: create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file)
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def upload( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Uploads a new function to AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) upload_s3(cfg, path_to_zip_file)
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def invoke( src, event_file="event.json", config_file="config.yaml", profile_name=None, verbose=False, ): """Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str alt_event: An optional argument to override which event file to use. :param bool verbose: Whether to print out verbose details. """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Set AWS_PROFILE environment variable based on `--profile` option. if profile_name: os.environ["AWS_PROFILE"] = profile_name # Load environment variables from the config file into the actual # environment. env_vars = cfg.get("environment_variables") if env_vars: for key, value in env_vars.items(): os.environ[key] = get_environment_variable_value(value) # Load and parse event file. path_to_event_file = os.path.join(src, event_file) event = read(path_to_event_file, loader=json.loads) # Tweak to allow module to import local modules try: sys.path.index(src) except ValueError: sys.path.append(src) handler = cfg.get("handler") # Inspect the handler string (<module>.<function name>) and translate it # into a function we can execute. fn = get_callable_handler_function(src, handler) timeout = cfg.get("timeout") if timeout: context = LambdaContext(cfg.get("function_name"), timeout) else: context = LambdaContext(cfg.get("function_name")) start = time.time() results = fn(event, context) end = time.time() print("{0}".format(results)) if verbose: print( "\nexecution time: {:.8f}s\nfunction execution " "timeout: {:2}s".format(end - start, cfg.get("timeout", 15)) )
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def to_python(self, value): if not value: return []
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def get_prep_value(self, value): return ','.join(value)
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def get_concurrency(cfg): """Return the Reserved Concurrent Executions if present in the config""" concurrency = int(cfg.get("concurrency", 0)) return max(0, concurrency)
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total)
def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale
def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out')
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure))
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def load_source(module_name, module_path): """Loads a python module from the path of the corresponding file.""" if sys.version_info[0] == 3 and sys.version_info[1] >= 5: import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info[0] == 3 and sys.version_info[1] < 5: import importlib.machinery loader = importlib.machinery.SourceFileLoader(module_name, module_path) module = loader.load_module() return module
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def __init__(self, field): self.field = field
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def __get__(self, instance, owner): if instance is None: raise AttributeError # ?
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value))
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None))
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def get_attname(self): return "%s_json" % self.name
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def init(src, minimal=False): """Copies template files to a given directory. :param str src: The path to output the template lambda project files. :param bool minimal: Minimal possible template files (excludes event.json). """ templates_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "project_templates", ) for filename in os.listdir(templates_path): if (minimal and filename == "event.json") or filename.endswith(".pyc"): continue dest_path = os.path.join(templates_path, filename) if not os.path.isdir(dest_path): copy(dest_path, src)
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def cleanup_old_versions( src, keep_last_versions, config_file="config.yaml", profile_name=None, ): """Deletes old deployed versions of the function in AWS Lambda. Won't delete $Latest and any aliased version :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param int keep_last_versions: The number of recent versions to keep and not delete """ if keep_last_versions <= 0: print("Won't delete all versions. Please do this manually") else: path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") client = get_client( "lambda", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) response = client.list_versions_by_function( FunctionName=cfg.get("function_name"), ) versions = response.get("Versions") if len(response.get("Versions")) < keep_last_versions: print("Nothing to delete. (Too few versions published)") else: version_numbers = [ elem.get("Version") for elem in versions[1:-keep_last_versions] ] for version_number in version_numbers: try: client.delete_function( FunctionName=cfg.get("function_name"), Qualifier=version_number, ) except botocore.exceptions.ClientError as e: print(f"Skipping Version {version_number}: {e}")
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def deploy( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc ) else: create_function(cfg, path_to_zip_file)
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def deploy_s3( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function via AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) use_s3 = True s3_file = upload_s3(cfg, path_to_zip_file, use_s3) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, use_s3=use_s3, s3_file=s3_file, preserve_vpc=preserve_vpc, ) else: create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file)
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def upload( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Uploads a new function to AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) upload_s3(cfg, path_to_zip_file)
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def invoke( src, event_file="event.json", config_file="config.yaml", profile_name=None, verbose=False, ): """Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str alt_event: An optional argument to override which event file to use. :param bool verbose: Whether to print out verbose details. """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Set AWS_PROFILE environment variable based on `--profile` option. if profile_name: os.environ["AWS_PROFILE"] = profile_name # Load environment variables from the config file into the actual # environment. env_vars = cfg.get("environment_variables") if env_vars: for key, value in env_vars.items(): os.environ[key] = get_environment_variable_value(value) # Load and parse event file. path_to_event_file = os.path.join(src, event_file) event = read(path_to_event_file, loader=json.loads) # Tweak to allow module to import local modules try: sys.path.index(src) except ValueError: sys.path.append(src) handler = cfg.get("handler") # Inspect the handler string (<module>.<function name>) and translate it # into a function we can execute. fn = get_callable_handler_function(src, handler) timeout = cfg.get("timeout") if timeout: context = LambdaContext(cfg.get("function_name"), timeout) else: context = LambdaContext(cfg.get("function_name")) start = time.time() results = fn(event, context) end = time.time() print("{0}".format(results)) if verbose: print( "\nexecution time: {:.8f}s\nfunction execution " "timeout: {:2}s".format(end - start, cfg.get("timeout", 15)) )
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def to_python(self, value): if not value: return []
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def get_prep_value(self, value): return ','.join(value)
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def get_concurrency(cfg): """Return the Reserved Concurrent Executions if present in the config""" concurrency = int(cfg.get("concurrency", 0)) return max(0, concurrency)
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total)
def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db
def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out')
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure))
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def load_source(module_name, module_path): """Loads a python module from the path of the corresponding file.""" if sys.version_info[0] == 3 and sys.version_info[1] >= 5: import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info[0] == 3 and sys.version_info[1] < 5: import importlib.machinery loader = importlib.machinery.SourceFileLoader(module_name, module_path) module = loader.load_module() return module
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def __init__(self, field): self.field = field
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def __get__(self, instance, owner): if instance is None: raise AttributeError # ?
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value))
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None))
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def get_attname(self): return "%s_json" % self.name
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def init(src, minimal=False): """Copies template files to a given directory. :param str src: The path to output the template lambda project files. :param bool minimal: Minimal possible template files (excludes event.json). """ templates_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "project_templates", ) for filename in os.listdir(templates_path): if (minimal and filename == "event.json") or filename.endswith(".pyc"): continue dest_path = os.path.join(templates_path, filename) if not os.path.isdir(dest_path): copy(dest_path, src)
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def cleanup_old_versions( src, keep_last_versions, config_file="config.yaml", profile_name=None, ): """Deletes old deployed versions of the function in AWS Lambda. Won't delete $Latest and any aliased version :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param int keep_last_versions: The number of recent versions to keep and not delete """ if keep_last_versions <= 0: print("Won't delete all versions. Please do this manually") else: path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") client = get_client( "lambda", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) response = client.list_versions_by_function( FunctionName=cfg.get("function_name"), ) versions = response.get("Versions") if len(response.get("Versions")) < keep_last_versions: print("Nothing to delete. (Too few versions published)") else: version_numbers = [ elem.get("Version") for elem in versions[1:-keep_last_versions] ] for version_number in version_numbers: try: client.delete_function( FunctionName=cfg.get("function_name"), Qualifier=version_number, ) except botocore.exceptions.ClientError as e: print(f"Skipping Version {version_number}: {e}")
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def deploy( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc ) else: create_function(cfg, path_to_zip_file)
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def deploy_s3( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function via AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) use_s3 = True s3_file = upload_s3(cfg, path_to_zip_file, use_s3) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, use_s3=use_s3, s3_file=s3_file, preserve_vpc=preserve_vpc, ) else: create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file)
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def upload( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Uploads a new function to AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) upload_s3(cfg, path_to_zip_file)
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def invoke( src, event_file="event.json", config_file="config.yaml", profile_name=None, verbose=False, ): """Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str alt_event: An optional argument to override which event file to use. :param bool verbose: Whether to print out verbose details. """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Set AWS_PROFILE environment variable based on `--profile` option. if profile_name: os.environ["AWS_PROFILE"] = profile_name # Load environment variables from the config file into the actual # environment. env_vars = cfg.get("environment_variables") if env_vars: for key, value in env_vars.items(): os.environ[key] = get_environment_variable_value(value) # Load and parse event file. path_to_event_file = os.path.join(src, event_file) event = read(path_to_event_file, loader=json.loads) # Tweak to allow module to import local modules try: sys.path.index(src) except ValueError: sys.path.append(src) handler = cfg.get("handler") # Inspect the handler string (<module>.<function name>) and translate it # into a function we can execute. fn = get_callable_handler_function(src, handler) timeout = cfg.get("timeout") if timeout: context = LambdaContext(cfg.get("function_name"), timeout) else: context = LambdaContext(cfg.get("function_name")) start = time.time() results = fn(event, context) end = time.time() print("{0}".format(results)) if verbose: print( "\nexecution time: {:.8f}s\nfunction execution " "timeout: {:2}s".format(end - start, cfg.get("timeout", 15)) )
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def to_python(self, value): if not value: return []
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def get_prep_value(self, value): return ','.join(value)
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def get_concurrency(cfg): """Return the Reserved Concurrent Executions if present in the config""" concurrency = int(cfg.get("concurrency", 0)) return max(0, concurrency)
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total)
def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file
def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out')
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure))
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def load_source(module_name, module_path): """Loads a python module from the path of the corresponding file.""" if sys.version_info[0] == 3 and sys.version_info[1] >= 5: import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info[0] == 3 and sys.version_info[1] < 5: import importlib.machinery loader = importlib.machinery.SourceFileLoader(module_name, module_path) module = loader.load_module() return module
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def __init__(self, field): self.field = field
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def __get__(self, instance, owner): if instance is None: raise AttributeError # ?
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value))
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None))
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def get_attname(self): return "%s_json" % self.name
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls)
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def init(src, minimal=False): """Copies template files to a given directory. :param str src: The path to output the template lambda project files. :param bool minimal: Minimal possible template files (excludes event.json). """ templates_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "project_templates", ) for filename in os.listdir(templates_path): if (minimal and filename == "event.json") or filename.endswith(".pyc"): continue dest_path = os.path.join(templates_path, filename) if not os.path.isdir(dest_path): copy(dest_path, src)
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def cleanup_old_versions( src, keep_last_versions, config_file="config.yaml", profile_name=None, ): """Deletes old deployed versions of the function in AWS Lambda. Won't delete $Latest and any aliased version :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param int keep_last_versions: The number of recent versions to keep and not delete """ if keep_last_versions <= 0: print("Won't delete all versions. Please do this manually") else: path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") client = get_client( "lambda", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) response = client.list_versions_by_function( FunctionName=cfg.get("function_name"), ) versions = response.get("Versions") if len(response.get("Versions")) < keep_last_versions: print("Nothing to delete. (Too few versions published)") else: version_numbers = [ elem.get("Version") for elem in versions[1:-keep_last_versions] ] for version_number in version_numbers: try: client.delete_function( FunctionName=cfg.get("function_name"), Qualifier=version_number, ) except botocore.exceptions.ClientError as e: print(f"Skipping Version {version_number}: {e}")
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def deploy( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc ) else: create_function(cfg, path_to_zip_file)
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def deploy_s3( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function via AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) use_s3 = True s3_file = upload_s3(cfg, path_to_zip_file, use_s3) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, use_s3=use_s3, s3_file=s3_file, preserve_vpc=preserve_vpc, ) else: create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file)
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def upload( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Uploads a new function to AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) upload_s3(cfg, path_to_zip_file)
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def invoke( src, event_file="event.json", config_file="config.yaml", profile_name=None, verbose=False, ): """Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str alt_event: An optional argument to override which event file to use. :param bool verbose: Whether to print out verbose details. """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Set AWS_PROFILE environment variable based on `--profile` option. if profile_name: os.environ["AWS_PROFILE"] = profile_name # Load environment variables from the config file into the actual # environment. env_vars = cfg.get("environment_variables") if env_vars: for key, value in env_vars.items(): os.environ[key] = get_environment_variable_value(value) # Load and parse event file. path_to_event_file = os.path.join(src, event_file) event = read(path_to_event_file, loader=json.loads) # Tweak to allow module to import local modules try: sys.path.index(src) except ValueError: sys.path.append(src) handler = cfg.get("handler") # Inspect the handler string (<module>.<function name>) and translate it # into a function we can execute. fn = get_callable_handler_function(src, handler) timeout = cfg.get("timeout") if timeout: context = LambdaContext(cfg.get("function_name"), timeout) else: context = LambdaContext(cfg.get("function_name")) start = time.time() results = fn(event, context) end = time.time() print("{0}".format(results)) if verbose: print( "\nexecution time: {:.8f}s\nfunction execution " "timeout: {:2}s".format(end - start, cfg.get("timeout", 15)) )
def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name)
def to_python(self, value): if not value: return []