INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset: SFrame Dataset of new observations. Must include columns with the same names as the feature and target columns used for model training. Additional columns are ignored. metric: str optional Name...
def evaluate(self, dataset, metric='auto', batch_size=None, verbose=True): """ Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset of new observations. Must inc...
Return top - k predictions for the dataset using the trained model. Predictions are returned as an SFrame with three columns: id class and probability or rank depending on the output_type parameter.
def predict_topk(self, dataset, output_type="probability", k=3, batch_size=None): """ Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability` or `rank`, depending on the ``ou...
Predict on an SFrame or SArray of drawings or on a single drawing.
def predict(self, data, output_type='class', batch_size=None, verbose=True): """ Predict on an SFrame or SArray of drawings, or on a single drawing. Parameters ---------- data : SFrame | SArray | tc.Image | list The drawing(s) on which to perform drawing classificati...
Parameters ---------- dataset: SFrame SFrame of images
def extract_features(self, dataset, feature, batch_size=64, verbose=False): """ Parameters ---------- dataset: SFrame SFrame of images """ from ._mxnet._mx_sframe_iter import SFrameImageIter as _SFrameImageIter from six.moves.queue import Queue as _Que...
Parameters ---------- mode: str ( classifier regressor or None ) Mode of the converted coreml model. When mode = classifier a NeuralNetworkClassifier spec will be constructed. When mode = regressor a NeuralNetworkRegressor spec will be constructed.
def get_coreml_model(self, mode = 'classifier'): """ Parameters ---------- mode: str ('classifier', 'regressor' or None) Mode of the converted coreml model. When mode = 'classifier', a NeuralNetworkClassifier spec will be constructed. When mode = 'regr...
Takes an mxnet parameter collect ( from Block. collect_params () ) and subsets it with the parameters available in this base network.
def available_parameters_subset(self, mx_params): """ Takes an mxnet parameter collect (from Block.collect_params()) and subsets it with the parameters available in this base network. """ from copy import copy from collections import OrderedDict subset_params = co...
Return an SFrame containing a bag of words representation of each column.
def _BOW_FEATURE_EXTRACTOR(sf, target=None): """ Return an SFrame containing a bag of words representation of each column. """ if isinstance(sf, dict): out = _tc.SArray([sf]).unpack('') elif isinstance(sf, _tc.SFrame): out = sf.__copy__() else: raise ValueError("Unrecogni...
Create a model that trains a classifier to classify text from a collection of documents. The model is a: class: ~turicreate. logistic_classifier. LogisticClassifier model trained using a bag - of - words representation of the text dataset.
def create(dataset, target, features = None, drop_stop_words = True, word_count_threshold = 2, method = 'auto', validation_set = 'auto', max_iterations = 10): """ Create a model that trains a classifier to classify text from a collection of documents. The model is a :class:`~turicr...
Returns a list of names of columns that are string type.
def _get_str_columns(sf): """ Returns a list of names of columns that are string type. """ return [name for name in sf.column_names() if sf[name].dtype == str]
Return predictions for dataset using the trained model.
def predict(self, dataset, output_type='class'): """ Return predictions for ``dataset``, using the trained model. Parameters ---------- dataset : SFrame dataset of new observations. Must include columns with the same names as the features used for model t...
Return a classification for each example in the dataset using the trained model. The output SFrame contains predictions as both class labels as well as probabilities that the predicted value is the associated label.
def classify(self, dataset): """ Return a classification, for each example in the ``dataset``, using the trained model. The output SFrame contains predictions as both class labels as well as probabilities that the predicted value is the associated label. Parameters ...
Evaluate the model by making predictions of target values and comparing these to actual values.
def evaluate(self, dataset, metric='auto', **kwargs): """ Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame An SFrame having the same feature columns as provided when creatin...
Takes an SVM regression model produces a starting spec using the parts. that are shared between all SVMs.
def _generate_base_svm_regression_spec(model): """ Takes an SVM regression model produces a starting spec using the parts. that are shared between all SVMs. """ if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') spec = _Model_pb...
Convert a Support Vector Regressor ( SVR ) model to the protobuf spec. Parameters ---------- model: SVR A trained SVR encoder model.
def convert(model, features, target): """Convert a Support Vector Regressor (SVR) model to the protobuf spec. Parameters ---------- model: SVR A trained SVR encoder model. feature_names: [str] Name of the input columns. target: str Name of the output column. Return...
Verify that the given extension handle is valid.
def _VerifyExtensionHandle(message, extension_handle): """Verify that the given extension handle is valid.""" if not isinstance(extension_handle, _FieldDescriptor): raise KeyError('HasExtension() expects an extension handle, got: %s' % extension_handle) if not extension_handle.is_extensio...
Sets class - level attributes for all enum fields defined in this message.
def _AddEnumValues(descriptor, cls): """Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can name enum values. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type. """ for enum...
Returns a function which returns a default value for a field.
def _DefaultValueConstructorForField(field): """Returns a function which returns a default value for a field. Args: field: FieldDescriptor object for this field. The returned function has one argument: message: Message instance containing this field, or a weakref proxy of same. That function in...
Re - raise the currently - handled TypeError with the field name added.
def _ReraiseTypeErrorWithFieldName(message_name, field_name): """Re-raise the currently-handled TypeError with the field name added.""" exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field name to exception message exc = TypeError('%s for field %s.%s' % (...
Adds an __init__ method to cls.
def _AddInitMethod(message_descriptor, cls): """Adds an __init__ method to cls.""" def _GetIntegerEnumValue(enum_type, value): """Convert a string or integer enum value to an integer. If the value is a string, it is converted to the enum value in enum_type with the same name. If the value is not a st...
Returns a field descriptor by field name.
def _GetFieldByName(message_descriptor, field_name): """Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name. """ try: retu...
Adds properties for all fields in this protocol message type.
def _AddPropertiesForFields(descriptor, cls): """Adds properties for all fields in this protocol message type.""" for field in descriptor.fields: _AddPropertiesForField(field, cls) if descriptor.is_extendable: # _ExtensionDict is just an adaptor with no state so we allocate a new one # every time it ...
Adds a public property for a protocol message field. Clients can use this property to get and ( in the case of non - repeated scalar fields ) directly set the value of a protocol message field.
def _AddPropertiesForField(field, cls): """Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field. Args: field: A FieldDescriptor for this field. cls: The class we're ...
Adds a public property for a repeated protocol message field. Clients can use this property to get the value of the field which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer ( see below ).
def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see below). Note that when clients add val...
Adds a public property for a nonrepeated scalar protocol message field. Clients can use this property to get and directly set the value of the field. Note that when the client sets the value of a field by using this property all necessary has bits are set as a side - effect and we also perform type - checking.
def _AddPropertiesForNonRepeatedScalarField(field, cls): """Adds a public property for a nonrepeated, scalar protocol message field. Clients can use this property to get and directly set the value of the field. Note that when the client sets the value of a field by using this property, all necessary "has" bits ...
Adds properties for all fields in this protocol message type.
def _AddPropertiesForExtensions(descriptor, cls): """Adds properties for all fields in this protocol message type.""" extension_dict = descriptor.extensions_by_name for extension_name, extension_field in extension_dict.items(): constant_name = extension_name.upper() + "_FIELD_NUMBER" setattr(cls, constant...
Given a ( FieldDescriptor value ) tuple from _fields return true if the value should be included in the list returned by ListFields ().
def _IsPresent(item): """Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().""" if item[0].label == _FieldDescriptor.LABEL_REPEATED: return bool(item[1]) elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: return ...
Helper for _AddMessageMethods ().
def _AddListFieldsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ListFields(self): all_fields = [item for item in self._fields.items() if _IsPresent(item)] all_fields.sort(key = lambda item: item[0].number) return all_fields cls.ListFields = ListFields
Helper for _AddMessageMethods ().
def _AddHasFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" is_proto3 = (message_descriptor.syntax == "proto3") error_msg = _Proto3HasError if is_proto3 else _Proto2HasError hassable_fields = {} for field in message_descriptor.fields: if field.label == _FieldDescriptor.LABEL_...
Helper for _AddMessageMethods ().
def _AddClearFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ClearField(self, field_name): try: field = message_descriptor.fields_by_name[field_name] except KeyError: try: field = message_descriptor.oneofs_by_name[field_name] if field in self._one...
Helper for _AddMessageMethods ().
def _AddClearExtensionMethod(cls): """Helper for _AddMessageMethods().""" def ClearExtension(self, extension_handle): _VerifyExtensionHandle(self, extension_handle) # Similar to ClearField(), above. if extension_handle in self._fields: del self._fields[extension_handle] self._Modified() cls...
Helper for _AddMessageMethods ().
def _AddHasExtensionMethod(cls): """Helper for _AddMessageMethods().""" def HasExtension(self, extension_handle): _VerifyExtensionHandle(self, extension_handle) if extension_handle.label == _FieldDescriptor.LABEL_REPEATED: raise KeyError('"%s" is repeated.' % extension_handle.full_name) if extens...
Unpacks Any message and returns the unpacked message.
def _InternalUnpackAny(msg): """Unpacks Any message and returns the unpacked message. This internal method is different from public Any Unpack method which takes the target message as argument. _InternalUnpackAny method does not have target message type and need to find the message type in descriptor pool. ...
Helper for _AddMessageMethods ().
def _AddEqualsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __eq__(self, other): if (not isinstance(other, message_mod.Message) or other.DESCRIPTOR != self.DESCRIPTOR): return False if self is other: return True if self.DESCRIPTOR.full_name == _AnyFull...
Helper for _AddMessageMethods ().
def _AddStrMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __str__(self): return text_format.MessageToString(self) cls.__str__ = __str__
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.
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.
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.
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 and yield the output as a nump...
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:
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
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.
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.
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.
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
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 ...