INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Helper for _AddMessageMethods().
def _AddReprMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __repr__(self): return text_format.MessageToString(self) cls.__repr__ = __repr__
Helper for _AddMessageMethods().
def _AddUnicodeMethod(unused_message_descriptor, cls): """Helper for _AddMessageMethods().""" def __unicode__(self): return text_format.MessageToString(self, as_utf8=True).decode('utf-8') cls.__unicode__ = __unicode__
Returns the number of bytes needed to serialize a non-repeated element. The returned byte count includes space for tag information and any other additional space associated with serializing value. Args: value: Value we're serializing. field_number: Field number of this value. (Since the field number ...
def _BytesForNonRepeatedElement(value, field_number, field_type): """Returns the number of bytes needed to serialize a non-repeated element. The returned byte count includes space for tag information and any other additional space associated with serializing value. Args: value: Value we're serializing. ...
Helper for _AddMessageMethods().
def _AddByteSizeMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ByteSize(self): if not self._cached_byte_size_dirty: return self._cached_byte_size size = 0 for field_descriptor, field_value in self.ListFields(): size += field_descriptor._sizer(field_value) ...
Helper for _AddMessageMethods().
def _AddSerializeToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializeToString(self): # Check if the message has all of its required fields set. errors = [] if not self.IsInitialized(): raise message_mod.EncodeError( 'Message %s is missing require...
Helper for _AddMessageMethods().
def _AddSerializePartialToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializePartialToString(self): out = BytesIO() self._InternalSerialize(out.write) return out.getvalue() cls.SerializePartialToString = SerializePartialToString def InternalSerialize(self, w...
Helper for _AddMessageMethods().
def _AddMergeFromStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def MergeFromString(self, serialized): length = len(serialized) try: if self._InternalParse(serialized, 0, length) != length: # The only reason _InternalParse would return early is if it # en...
Adds the IsInitialized and FindInitializationError methods to the protocol message class.
def _AddIsInitializedMethod(message_descriptor, cls): """Adds the IsInitialized and FindInitializationError methods to the protocol message class.""" required_fields = [field for field in message_descriptor.fields if field.label == _FieldDescriptor.LABEL_REQUIRED] def IsInitialized(...
Adds implementations of all Message methods to cls.
def _AddMessageMethods(message_descriptor, cls): """Adds implementations of all Message methods to cls.""" _AddListFieldsMethod(message_descriptor, cls) _AddHasFieldMethod(message_descriptor, cls) _AddClearFieldMethod(message_descriptor, cls) if message_descriptor.is_extendable: _AddClearExtensionMethod(c...
Adds implementation of private helper methods to cls.
def _AddPrivateHelperMethods(message_descriptor, cls): """Adds implementation of private helper methods to cls.""" def Modified(self): """Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change. """ # Note: Some callers check _cached_byte_size...
Also updates the state of the containing oneof in the parent message.
def Modified(self): """Also updates the state of the containing oneof in the parent message.""" try: self._parent_message_weakref._UpdateOneofState(self._field) super(_OneofListener, self).Modified() except ReferenceError: pass
Returns a string containing the name of an enum value.
def Name(self, number): """Returns a string containing the name of an enum value.""" if number in self._enum_type.values_by_number: return self._enum_type.values_by_number[number].name raise ValueError('Enum %s has no name defined for value %d' % ( self._enum_type.name, number))
Returns the value coresponding to the given enum name.
def Value(self, name): """Returns the value coresponding to the given enum name.""" if name in self._enum_type.values_by_name: return self._enum_type.values_by_name[name].number raise ValueError('Enum %s has no value defined for name %s' % ( self._enum_type.name, name))
Return a list of the (name, value) pairs of the enum. These are returned in the order they were defined in the .proto file.
def items(self): """Return a list of the (name, value) pairs of the enum. These are returned in the order they were defined in the .proto file. """ return [(value_descriptor.name, value_descriptor.number) for value_descriptor in self._enum_type.values]
Load global singleton of tcmps lib handler. This function is used not used at the top level, so that the shared library is loaded lazily only when needed.
def _load_tcmps_lib(): """ Load global singleton of tcmps lib handler. This function is used not used at the top level, so that the shared library is loaded lazily only when needed. """ global _g_TCMPS_LIB if _g_TCMPS_LIB is None: # This library requires macOS 10.14 or above ...
Returns True if the environment has MPS backend support and a high-power (fast) device is available.
def has_fast_mps_support(): """ Returns True if the environment has MPS backend support and a high-power (fast) device is available. """ lib = _load_tcmps_lib() if lib is None: return False c_bool = _ctypes.c_bool() ret = lib.TCMPSHasHighPowerMetalDevice(_ctypes.byref(c_bool)) ...
Returns name of MPS device that will be used, else None.
def mps_device_name(): """ Returns name of MPS device that will be used, else None. """ lib = _load_tcmps_lib() if lib is None: return None n = 256 c_name = (_ctypes.c_char * n)() ret = lib.TCMPSMetalDeviceName(_ctypes.byref(c_name), _ctypes.c_int32(n)) if ret == 0: ...
Returns the memory size in bytes that can be effectively allocated on the MPS device that will be used, or None if no suitable device is available.
def mps_device_memory_limit(): """ Returns the memory size in bytes that can be effectively allocated on the MPS device that will be used, or None if no suitable device is available. """ lib = _load_tcmps_lib() if lib is None: return None c_size = _ctypes.c_uint64() ret = lib.TC...
Copy the shape from TCMPS as a new numpy ndarray.
def shape(self): """Copy the shape from TCMPS as a new numpy ndarray.""" # Create C variables that will serve as out parameters for TCMPS. shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr dim = _ctypes.c_size_t() # size_t dim # Obtain...
Copy the data from TCMPS into a new numpy ndarray
def asnumpy(self): """Copy the data from TCMPS into a new numpy ndarray""" # Create C variables that will serve as out parameters for TCMPS. data_ptr = _ctypes.POINTER(_ctypes.c_float)() # float* data_ptr shape_ptr = _ctypes.POINTER(_ctypes.c_size_t)() # size_t* shape_ptr di...
Submits an input batch to the model. Returns a MpsFloatArray representing the batch loss. Calling asnumpy() on this value will wait for the batch to finish and yield the loss as a numpy array.
def train(self, input, label): """ Submits an input batch to the model. Returns a MpsFloatArray representing the batch loss. Calling asnumpy() on this value will wait for the batch to finish and yield the loss as a numpy array. """ assert self._mode == MpsGraphMode.Train...
Submits an input batch to the model. Returns a MpsFloatArray representing the model predictions. Calling asnumpy() on this value will wait for the batch to finish and yield the predictions as a numpy array.
def predict(self, input): """ Submits an input batch to the model. Returns a MpsFloatArray representing the model predictions. Calling asnumpy() on this value will wait for the batch to finish and yield the predictions as a numpy array. """ assert self._mode == MpsGraphM...
Performs a forward pass from the input batch, followed by a backward pass using the provided gradient (in place of a loss function). Returns a MpsFloatArray representing the output (final gradient) of the backward pass. Calling asnumpy() on this value will wait for the batch to finish an...
def train_return_grad(self, input, grad): """ Performs a forward pass from the input batch, followed by a backward pass using the provided gradient (in place of a loss function). Returns a MpsFloatArray representing the output (final gradient) of the backward pass. Calling asnump...
Gets SNS Message, deserialises the message, imports the function, calls the function with args
def route_sns_task(event, context): """ Gets SNS Message, deserialises the message, imports the function, calls the function with args """ record = event['Records'][0] message = json.loads( record['Sns']['Message'] ) return run_message(message)
Runs a function defined by a message object with keys: 'task_path', 'args', and 'kwargs' used by lambda routing and a 'command' in handler.py
def run_message(message): """ Runs a function defined by a message object with keys: 'task_path', 'args', and 'kwargs' used by lambda routing and a 'command' in handler.py """ if message.get('capture_response', False): DYNAMODB_CLIENT.put_item( TableName=ASYNC_RESPONSE_TABLE,...
Instead of decorating a function with @task, you can just run it directly. If you were going to do func(*args, **kwargs), then you will call this: import zappa.asynchronous.run zappa.asynchronous.run(func, args, kwargs) If you want to use SNS, then do: zappa.asynchronous.run(func, args, kwargs, s...
def run(func, args=[], kwargs={}, service='lambda', capture_response=False, remote_aws_lambda_function_name=None, remote_aws_region=None, **task_kwargs): """ Instead of decorating a function with @task, you can just run it directly. If you were going to do func(*args, **kwargs), then you will call t...
Async task decorator so that running Args: func (function): the function to be wrapped Further requirements: func must be an independent top-level function. i.e. not a class method or an anonymous function service (str): either 'lambda' or 'sns' remo...
def task(*args, **kwargs): """Async task decorator so that running Args: func (function): the function to be wrapped Further requirements: func must be an independent top-level function. i.e. not a class method or an anonymous function service (str): eit...
Given a modular path to a function, import that module and return the function.
def import_and_get_task(task_path): """ Given a modular path to a function, import that module and return the function. """ module, function = task_path.rsplit('.', 1) app_module = importlib.import_module(module) app_function = getattr(app_module, function) return app_function
Format the modular task path for a function via inspection.
def get_func_task_path(func): """ Format the modular task path for a function via inspection. """ module_path = inspect.getmodule(func).__name__ task_path = '{module_path}.{func_name}'.format( module_path=module_path, fu...
Get the response from the async table
def get_async_response(response_id): """ Get the response from the async table """ response = DYNAMODB_CLIENT.get_item( TableName=ASYNC_RESPONSE_TABLE, Key={'id': {'S': str(response_id)}} ) if 'Item' not in response: return None return { 'status': response['I...
Create the message object and pass it to the actual sender.
def send(self, task_path, args, kwargs): """ Create the message object and pass it to the actual sender. """ message = { 'task_path': task_path, 'capture_response': self.capture_response, 'response_id': self.response_id, 'ar...
Given a message, directly invoke the lamdba function for this task.
def _send(self, message): """ Given a message, directly invoke the lamdba function for this task. """ message['command'] = 'zappa.asynchronous.route_lambda_task' payload = json.dumps(message).encode('utf-8') if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover...
Given a message, publish to this topic.
def _send(self, message): """ Given a message, publish to this topic. """ message['command'] = 'zappa.asynchronous.route_sns_task' payload = json.dumps(message).encode('utf-8') if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover raise AsyncExcepti...
Parses S3 URL. Returns bucket (domain) and file (full path).
def parse_s3_url(url): """ Parses S3 URL. Returns bucket (domain) and file (full path). """ bucket = '' path = '' if url: result = urlparse(url) bucket = result.netloc path = result.path.strip('/') return bucket, path
Accepts a str, returns an int timestamp.
def string_to_timestamp(timestring): """ Accepts a str, returns an int timestamp. """ ts = None # Uses an extended version of Go's duration string. try: delta = durationpy.from_str(timestring); past = datetime.datetime.utcnow() - delta ts = calendar.timegm(past.timetupl...
Automatically try to discover Django settings files, return them as relative module paths.
def detect_django_settings(): """ Automatically try to discover Django settings files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, '*settings.py'): full = os.path.join...
Automatically try to discover Flask apps files, return them as relative module paths.
def detect_flask_apps(): """ Automatically try to discover Flask apps files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, '*.py'): full = os.path.join(root, filename) ...
Given an event_source dictionary, create the object and add the event source.
def add_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and add the event source. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) # TODO: ...
Given an event_source dictionary, create the object and remove the event source.
def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and remove the event source. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) #...
Given an event_source dictionary, create the object and get the event source status.
def get_event_source_status(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and get the event source status. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False...
Checks if a newer version of Zappa is available. Returns True is updateable, else False.
def check_new_version_available(this_version): """ Checks if a newer version of Zappa is available. Returns True is updateable, else False. """ import requests pypi_url = 'https://pypi.python.org/pypi/Zappa/json' resp = requests.get(pypi_url, timeout=1.5) top_version = resp.json()['in...
Validate name for AWS Lambda function. name: actual name (without `arn:aws:lambda:...:` prefix and without `:$LATEST`, alias or version suffix. maxlen: max allowed length for name without prefix and suffix. The value 80 was calculated from prefix with longest known region name and assuming that...
def validate_name(name, maxlen=80): """Validate name for AWS Lambda function. name: actual name (without `arn:aws:lambda:...:` prefix and without `:$LATEST`, alias or version suffix. maxlen: max allowed length for name without prefix and suffix. The value 80 was calculated from prefix with long...
Checks (recursively) if the directory contains .py or .pyc files
def contains_python_files_or_subdirs(folder): """ Checks (recursively) if the directory contains .py or .pyc files """ for root, dirs, files in os.walk(folder): if [filename for filename in files if filename.endswith('.py') or filename.endswith('.pyc')]: return True for d in...
Checks if a directory lies in the same directory as a .py file with the same name.
def conflicts_with_a_neighbouring_module(directory_path): """ Checks if a directory lies in the same directory as a .py file with the same name. """ parent_dir_path, current_dir_name = os.path.split(os.path.normpath(directory_path)) neighbours = os.listdir(parent_dir_path) conflicting_neighbour_...
Checks if an S3 bucket name is valid according to https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules
def is_valid_bucket_name(name): """ Checks if an S3 bucket name is valid according to https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules """ # Bucket names must be at least 3 and no more than 63 characters long. if (len(name) < 3 or len(name) > 63): ret...
Merge the values of headers and multiValueHeaders into a single dict. Opens up support for multivalue headers via API Gateway and ALB. See: https://github.com/Miserlou/Zappa/pull/1756
def merge_headers(event): """ Merge the values of headers and multiValueHeaders into a single dict. Opens up support for multivalue headers via API Gateway and ALB. See: https://github.com/Miserlou/Zappa/pull/1756 """ headers = event.get('headers') or {} multi_headers = (event.get('multiValu...
Given some event_info via API Gateway, create and return a valid WSGI request environ.
def create_wsgi_request(event_info, server_name='zappa', script_name=None, trailing_slash=True, binary_support=False, base_path=None, context_header_mappings={}, ...
Given the WSGI environ and the response, log this event in Common Log Format.
def common_log(environ, response, response_time=None): """ Given the WSGI environ and the response, log this event in Common Log Format. """ logger = logging.getLogger() if response_time: formatter = ApacheFormatter(with_response_time=True) try: log_entry = formatt...
Puts the project files from S3 in /tmp and adds to path
def load_remote_project_archive(self, project_zip_path): """ Puts the project files from S3 in /tmp and adds to path """ project_folder = '/tmp/{0!s}'.format(self.settings.PROJECT_NAME) if not os.path.isdir(project_folder): # The project folder doesn't exist in this c...
Attempt to read a file from s3 containing a flat json object. Adds each key->value pair as environment variables. Helpful for keeping sensitiZve or stage-specific configuration variables in s3 instead of version control.
def load_remote_settings(self, remote_bucket, remote_file): """ Attempt to read a file from s3 containing a flat json object. Adds each key->value pair as environment variables. Helpful for keeping sensitiZve or stage-specific configuration variables in s3 instead of version cont...
Given a modular path to a function, import that module and return the function.
def import_module_and_get_function(whole_function): """ Given a modular path to a function, import that module and return the function. """ module, function = whole_function.rsplit('.', 1) app_module = importlib.import_module(module) app_function = getattr(app_mod...
Given a function and event context, detect signature and execute, returning any result.
def run_function(app_function, event, context): """ Given a function and event context, detect signature and execute, returning any result. """ # getargspec does not support python 3 method with type hints # Related issue: https://github.com/Miserlou/Zappa/issues/1452 ...
Get the associated function to execute for a triggered AWS event Support S3, SNS, DynamoDB, kinesis and SQS events
def get_function_for_aws_event(self, record): """ Get the associated function to execute for a triggered AWS event Support S3, SNS, DynamoDB, kinesis and SQS events """ if 's3' in record: if ':' in record['s3']['configurationId']: return record['s3'][...
For the given event build ARN and return the configured function
def get_function_from_bot_intent_trigger(self, event): """ For the given event build ARN and return the configured function """ intent = event.get('currentIntent') if intent: intent = intent.get('name') if intent: return self.settings.AWS_B...
Get the associated function to execute for a cognito trigger
def get_function_for_cognito_trigger(self, trigger): """ Get the associated function to execute for a cognito trigger """ print("get_function_for_cognito_trigger", self.settings.COGNITO_TRIGGER_MAPPING, trigger, self.settings.COGNITO_TRIGGER_MAPPING.get(trigger)) return self.sett...
An AWS Lambda function which parses specific API Gateway input into a WSGI request, feeds it to our WSGI app, procceses the response, and returns that back to the API Gateway.
def handler(self, event, context): """ An AWS Lambda function which parses specific API Gateway input into a WSGI request, feeds it to our WSGI app, procceses the response, and returns that back to the API Gateway. """ settings = self.settings # If in DEBUG mode...
validate the incoming token
def lambda_handler(event, context): print("Client token: " + event['authorizationToken']) print("Method ARN: " + event['methodArn']) """validate the incoming token""" """and produce the principal user identifier associated with the token""" """this could be accomplished in a number of ways:""" ...
Adds a method to the internal lists of allowed or denied methods. Each object in the internal list contains a resource ARN and a condition statement. The condition statement can be null.
def _addMethod(self, effect, verb, resource, conditions): """Adds a method to the internal lists of allowed or denied methods. Each object in the internal list contains a resource ARN and a condition statement. The condition statement can be null.""" if verb != "*" and not hasattr(HttpVe...
Adds an API Gateway method (Http verb + Resource path) to the list of allowed methods and includes a condition for the policy statement. More on AWS policy conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition
def allowMethodWithConditions(self, verb, resource, conditions): """Adds an API Gateway method (Http verb + Resource path) to the list of allowed methods and includes a condition for the policy statement. More on AWS policy conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/referen...
Adds an API Gateway method (Http verb + Resource path) to the list of denied methods and includes a condition for the policy statement. More on AWS policy conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition
def denyMethodWithConditions(self, verb, resource, conditions): """Adds an API Gateway method (Http verb + Resource path) to the list of denied methods and includes a condition for the policy statement. More on AWS policy conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference...
Generates the policy document based on the internal lists of allowed and denied conditions. This will generate a policy with two main statements for the effect: one statement for Allow and one statement for Deny. Methods that includes conditions will have their own statement in the policy.
def build(self): """Generates the policy document based on the internal lists of allowed and denied conditions. This will generate a policy with two main statements for the effect: one statement for Allow and one statement for Deny. Methods that includes conditions will have their own st...
Allow for custom endpoint urls for non-AWS (testing and bootleg cloud) deployments
def configure_boto_session_method_kwargs(self, service, kw): """Allow for custom endpoint urls for non-AWS (testing and bootleg cloud) deployments""" if service in self.endpoint_urls and not 'endpoint_url' in kw: kw['endpoint_url'] = self.endpoint_urls[service] return kw
A wrapper to apply configuration options to boto clients
def boto_client(self, service, *args, **kwargs): """A wrapper to apply configuration options to boto clients""" return self.boto_session.client(service, *args, **self.configure_boto_session_method_kwargs(service, kwargs))
A wrapper to apply configuration options to boto resources
def boto_resource(self, service, *args, **kwargs): """A wrapper to apply configuration options to boto resources""" return self.boto_session.resource(service, *args, **self.configure_boto_session_method_kwargs(service, kwargs))
Returns a troposphere Ref to a value cached as a parameter.
def cache_param(self, value): '''Returns a troposphere Ref to a value cached as a parameter.''' if value not in self.cf_parameters: keyname = chr(ord('A') + len(self.cf_parameters)) param = self.cf_template.add_parameter(troposphere.Parameter( keyname, Type="Stri...
For a given package, returns a list of required packages. Recursive.
def get_deps_list(self, pkg_name, installed_distros=None): """ For a given package, returns a list of required packages. Recursive. """ # https://github.com/Miserlou/Zappa/issues/1478. Using `pkg_resources` # instead of `pip` is the recommended approach. The usage is nearly ...
Takes the installed zappa and brings it into a fresh virtualenv-like folder. All dependencies are then downloaded.
def create_handler_venv(self): """ Takes the installed zappa and brings it into a fresh virtualenv-like folder. All dependencies are then downloaded. """ import subprocess # We will need the currenv venv to pull Zappa from current_venv = self.get_current_venv() ...
Returns the path to the current virtualenv
def get_current_venv(): """ Returns the path to the current virtualenv """ if 'VIRTUAL_ENV' in os.environ: venv = os.environ['VIRTUAL_ENV'] elif os.path.exists('.python-version'): # pragma: no cover try: subprocess.check_output(['pyenv', '...
Extracts the lambda package into a given path. Assumes the package exists in lambda packages.
def extract_lambda_package(self, package_name, path): """ Extracts the lambda package into a given path. Assumes the package exists in lambda packages. """ lambda_package = lambda_packages[package_name][self.runtime] # Trash the local version to help with package space saving ...
Returns a dict of installed packages that Zappa cares about.
def get_installed_packages(site_packages, site_packages_64): """ Returns a dict of installed packages that Zappa cares about. """ import pkg_resources package_to_keep = [] if os.path.isdir(site_packages): package_to_keep += os.listdir(site_packages) i...
Checks if a given package version binary should be copied over from lambda packages. package_name should be lower-cased version of package name.
def have_correct_lambda_package_version(self, package_name, package_version): """ Checks if a given package version binary should be copied over from lambda packages. package_name should be lower-cased version of package name. """ lambda_package_details = lambda_packages.get(pack...
Downloads a given url in chunks and writes to the provided stream (can be any io stream). Displays the progress bar for the download.
def download_url_with_progress(url, stream, disable_progress): """ Downloads a given url in chunks and writes to the provided stream (can be any io stream). Displays the progress bar for the download. """ resp = requests.get(url, timeout=float(os.environ.get('PIP_TIMEOUT', 2)), s...
Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it.
def get_cached_manylinux_wheel(self, package_name, package_version, disable_progress=False): """ Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it. """ cached_wheels_dir = os.path.join(tempfile.gettempdir(), 'cached_wheels') if...
For a given package name, returns a link to the download URL, else returns None. Related: https://github.com/Miserlou/Zappa/issues/398 Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b56880adbae This function downloads metadata JSON of `package_name` from Pypi ...
def get_manylinux_wheel_url(self, package_name, package_version): """ For a given package name, returns a link to the download URL, else returns None. Related: https://github.com/Miserlou/Zappa/issues/398 Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b5688...
r""" Given a file, upload it to S3. Credentials should be stored in environment variables or ~/.aws/credentials (%USERPROFILE%\.aws\credentials on Windows). Returns True on success, false on failure.
def upload_to_s3(self, source_path, bucket_name, disable_progress=False): r""" Given a file, upload it to S3. Credentials should be stored in environment variables or ~/.aws/credentials (%USERPROFILE%\.aws\credentials on Windows). Returns True on success, false on failure. """ ...
Copies src file to destination within a bucket.
def copy_on_s3(self, src_file_name, dst_file_name, bucket_name): """ Copies src file to destination within a bucket. """ try: self.s3_client.head_bucket(Bucket=bucket_name) except botocore.exceptions.ClientError as e: # pragma: no cover # If a client erro...
Given a file name and a bucket, remove it from S3. There's no reason to keep the file hosted on S3 once its been made into a Lambda function, so we can delete it from S3. Returns True on success, False on failure.
def remove_from_s3(self, file_name, bucket_name): """ Given a file name and a bucket, remove it from S3. There's no reason to keep the file hosted on S3 once its been made into a Lambda function, so we can delete it from S3. Returns True on success, False on failure. """ ...
Given a bucket and key (or a local path) of a valid Lambda-zip, a function name and a handler, register that Lambda function.
def create_lambda_function( self, bucket=None, function_name=None, handler=None, s3_key=None, description='Zappa Deployment', ti...
Given a bucket and key (or a local path) of a valid Lambda-zip, a function name and a handler, update that Lambda function's code. Optionally, delete previous versions if they exceed the optional limit.
def update_lambda_function(self, bucket, function_name, s3_key=None, publish=True, local_zip=None, num_revisions=None): """ Given a bucket and key (or a local path) of a valid Lambda-zip, a function name and a handler, update that Lambda function's code. Optionally, delete previous versions if t...
Given an existing function ARN, update the configuration variables.
def update_lambda_configuration( self, lambda_arn, function_name, handler, description='Zappa Deployment', timeout=30...
Directly invoke a named Lambda function with a payload. Returns the response.
def invoke_lambda_function( self, function_name, payload, invocation_type='Event', log_type='Tail', client_context=None, qualifi...
Rollback the lambda function code 'versions_back' number of revisions. Returns the Function ARN.
def rollback_lambda_function_version(self, function_name, versions_back=1, publish=True): """ Rollback the lambda function code 'versions_back' number of revisions. Returns the Function ARN. """ response = self.lambda_client.list_versions_by_function(FunctionName=function_name) ...
Returns the lambda function ARN, given a name This requires the "lambda:GetFunction" role.
def get_lambda_function(self, function_name): """ Returns the lambda function ARN, given a name This requires the "lambda:GetFunction" role. """ response = self.lambda_client.get_function( FunctionName=function_name) return response['Configuration']['Func...
Simply returns the versions available for a Lambda function, given a function name.
def get_lambda_function_versions(self, function_name): """ Simply returns the versions available for a Lambda function, given a function name. """ try: response = self.lambda_client.list_versions_by_function( FunctionName=function_name ) ...
The `zappa deploy` functionality for ALB infrastructure.
def deploy_lambda_alb( self, lambda_arn, lambda_name, alb_vpc_config, timeout ): """ The `zappa deploy` functionality for ALB infrastructure. """ if n...
The `zappa undeploy` functionality for ALB infrastructure.
def undeploy_lambda_alb(self, lambda_name): """ The `zappa undeploy` functionality for ALB infrastructure. """ print("Undeploying ALB infrastructure...") # Locate and delete alb/lambda permissions try: # https://boto3.amazonaws.com/v1/documentation/api/latest...
Create the API Gateway for this Zappa deployment. Returns the new RestAPI CF resource.
def create_api_gateway_routes( self, lambda_arn, api_name=None, api_key_required=False, authorization_type='NONE', authorizer=None, ...
Create Authorizer for API gateway
def create_authorizer(self, restapi, uri, authorizer): """ Create Authorizer for API gateway """ authorizer_type = authorizer.get("type", "TOKEN").upper() identity_validation_expression = authorizer.get('validation_expression', None) authorizer_resource = troposphere.api...
Set up the methods, integration responses and method responses for a given API Gateway resource.
def create_and_setup_methods( self, restapi, resource, api_key_required, uri, authorization_type, ...
Set up the methods, integration responses and method responses for a given API Gateway resource.
def create_and_setup_cors(self, restapi, resource, uri, depth, config): """ Set up the methods, integration responses and method responses for a given API Gateway resource. """ if config is True: config = {} method_name = "OPTIONS" method = troposphere.apigate...
Deploy the API Gateway! Return the deployed API URL.
def deploy_api_gateway( self, api_id, stage_name, stage_description="", description="", cache_cluster_enabled=False, cache_cluster_size='0.5', ...
Add Rest API compression
def add_api_compression(self, api_id, min_compression_size): """ Add Rest API compression """ self.apigateway_client.update_rest_api( restApiId=api_id, patchOperations=[ { 'op': 'replace', 'path': '/minimumCo...
Remove binary support
def remove_binary_support(self, api_id, cors=False): """ Remove binary support """ response = self.apigateway_client.get_rest_api( restApiId=api_id ) if "binaryMediaTypes" in response and "*/*" in response["binaryMediaTypes"]: self.apigateway_clien...
Generator that allows to iterate per API keys associated to an api_id and a stage_name.
def get_api_keys(self, api_id, stage_name): """ Generator that allows to iterate per API keys associated to an api_id and a stage_name. """ response = self.apigateway_client.get_api_keys(limit=500) stage_key = '{}/{}'.format(api_id, stage_name) for api_key in response.get...
Remove a generated API key for api_id and stage_name
def remove_api_key(self, api_id, stage_name): """ Remove a generated API key for api_id and stage_name """ response = self.apigateway_client.get_api_keys( limit=1, nameQuery='{}_{}'.format(stage_name, api_id) ) for api_key in response.get('items'):...
Create new API key and link it with an api_id and a stage_name
def create_api_key(self, api_id, stage_name): """ Create new API key and link it with an api_id and a stage_name """ response = self.apigateway_client.create_api_key( name='{}_{}'.format(stage_name, api_id), description='Api Key for {}'.format(api_id), ...
Add api stage to Api key
def add_api_stage_to_api_key(self, api_key, api_id, stage_name): """ Add api stage to Api key """ self.apigateway_client.update_api_key( apiKey=api_key, patchOperations=[ { 'op': 'add', 'path': '/stages', ...
Return an object that describes a change of configuration on the given staging. Setting will be applied on all available HTTP methods.
def get_patch_op(self, keypath, value, op='replace'): """ Return an object that describes a change of configuration on the given staging. Setting will be applied on all available HTTP methods. """ if isinstance(value, bool): value = str(value).lower() return {...
Generator that allows to iterate per every available apis.
def get_rest_apis(self, project_name): """ Generator that allows to iterate per every available apis. """ all_apis = self.apigateway_client.get_rest_apis( limit=500 ) for api in all_apis['items']: if api['name'] != project_name: co...
Delete a deployed REST API Gateway.
def undeploy_api_gateway(self, lambda_name, domain_name=None, base_path=None): """ Delete a deployed REST API Gateway. """ print("Deleting API Gateway..") api_id = self.get_api_id(lambda_name) if domain_name: # XXX - Remove Route53 smartly here? ...