Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _AddClearExtensionMethod(cls):
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(... | [
"Helper for _AddMessageMethods()."
] |
Please provide a description of the function:def _AddHasExtensionMethod(cls):
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... | [
"Helper for _AddMessageMethods()."
] |
Please provide a description of the function:def _InternalUnpackAny(msg):
# TODO(amauryfa): Don't use the factory of generated messages.
# To make Any work with custom factories, use the message factory of the
# parent message.
# pylint: disable=g-import-not-at-top
from google.protobuf import symbol_databa... | [
"Unpacks Any message and returns the unpacked message.\n\n This internal method is different from public Any Unpack method which takes\n the target message as argument. _InternalUnpackAny method does not have\n target message type and need to find the message type in descriptor pool.\n\n Args:\n msg: An Any ... |
Please provide a description of the function:def _AddEqualsMethod(message_descriptor, cls):
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 == _... | [
"Helper for _AddMessageMethods()."
] |
Please provide a description of the function:def _AddStrMethod(message_descriptor, cls):
def __str__(self):
return text_format.MessageToString(self)
cls.__str__ = __str__ | [
"Helper for _AddMessageMethods()."
] |
Please provide a description of the function:def _AddReprMethod(message_descriptor, cls):
def __repr__(self):
return text_format.MessageToString(self)
cls.__repr__ = __repr__ | [
"Helper for _AddMessageMethods()."
] |
Please provide a description of the function:def _AddUnicodeMethod(unused_message_descriptor, cls):
def __unicode__(self):
return text_format.MessageToString(self, as_utf8=True).decode('utf-8')
cls.__unicode__ = __unicode__ | [
"Helper for _AddMessageMethods()."
] |
Please provide a description of the function:def _BytesForNonRepeatedElement(value, field_number, field_type):
try:
fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type]
return fn(field_number, value)
except KeyError:
raise message_mod.EncodeError('Unrecognized field type: %d' % field_type) | [
"Returns the number of bytes needed to serialize a non-repeated element.\n The returned byte count includes space for tag information and any\n other additional space associated with serializing value.\n\n Args:\n value: Value we're serializing.\n field_number: Field number of this value. (Since the field... |
Please provide a description of the function:def _AddByteSizeMethod(message_descriptor, cls):
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()."
] |
Please provide a description of the function:def _AddSerializeToStringMethod(message_descriptor, cls):
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 ... | [
"Helper for _AddMessageMethods()."
] |
Please provide a description of the function:def _AddSerializePartialToStringMethod(message_descriptor, cls):
def SerializePartialToString(self):
out = BytesIO()
self._InternalSerialize(out.write)
return out.getvalue()
cls.SerializePartialToString = SerializePartialToString
def InternalSerialize(... | [
"Helper for _AddMessageMethods()."
] |
Please provide a description of the function:def _AddMergeFromStringMethod(message_descriptor, cls):
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
... | [
"Helper for _AddMessageMethods()."
] |
Please provide a description of the function:def _AddIsInitializedMethod(message_descriptor, cls):
required_fields = [field for field in message_descriptor.fields
if field.label == _FieldDescriptor.LABEL_REQUIRED]
def IsInitialized(self, errors=None):
# Performance is criti... | [
"Adds the IsInitialized and FindInitializationError methods to the\n protocol message class.",
"Checks if all required fields of a message are set.\n\n Args:\n errors: A list which, if provided, will be populated with the field\n paths of all missing required fields.\n\n Returns:\n ... |
Please provide a description of the function:def _AddMessageMethods(message_descriptor, cls):
_AddListFieldsMethod(message_descriptor, cls)
_AddHasFieldMethod(message_descriptor, cls)
_AddClearFieldMethod(message_descriptor, cls)
if message_descriptor.is_extendable:
_AddClearExtensionMethod(cls)
_Add... | [
"Adds implementations of all Message methods to cls."
] |
Please provide a description of the function:def _AddPrivateHelperMethods(message_descriptor, cls):
def Modified(self):
# Note: Some callers check _cached_byte_size_dirty before calling
# _Modified() as an extra optimization. So, if this method is ever
# changed such that it does stuff eve... | [
"Adds implementation of private helper methods to cls.",
"Sets the _cached_byte_size_dirty bit to true,\n and propagates this to our listener iff this was a state change.\n ",
"Sets field as the active field in its containing oneof.\n\n Will also delete currently active field in the oneof, if it is dif... |
Please provide a description of the function:def Modified(self):
try:
self._parent_message_weakref._UpdateOneofState(self._field)
super(_OneofListener, self).Modified()
except ReferenceError:
pass | [
"Also updates the state of the containing oneof in the parent message."
] |
Please provide a description of the function:def Name(self, number):
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 a string containing the name of an enum value."
] |
Please provide a description of the function:def Value(self, 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)) | [
"Returns the value coresponding to the given enum name."
] |
Please provide a description of the function:def items(self):
return [(value_descriptor.name, value_descriptor.number)
for value_descriptor in self._enum_type.values] | [
"Return a list of the (name, value) pairs of the enum.\n\n These are returned in the order they were defined in the .proto file.\n "
] |
Please provide a description of the function:def _load_tcmps_lib():
global _g_TCMPS_LIB
if _g_TCMPS_LIB is None:
# This library requires macOS 10.14 or above
if _mac_ver() < (10, 14):
return None
# The symbols defined in libtcmps are now exposed directly by
# li... | [
"\n Load global singleton of tcmps lib handler.\n\n This function is used not used at the top level, so\n that the shared library is loaded lazily only when needed.\n "
] |
Please provide a description of the function:def has_fast_mps_support():
lib = _load_tcmps_lib()
if lib is None:
return False
c_bool = _ctypes.c_bool()
ret = lib.TCMPSHasHighPowerMetalDevice(_ctypes.byref(c_bool))
return ret == 0 and c_bool.value | [
"\n Returns True if the environment has MPS backend support\n and a high-power (fast) device is available.\n "
] |
Please provide a description of the function:def mps_device_name():
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:
return _decode_bytes_to_nat... | [
"\n Returns name of MPS device that will be used, else None.\n "
] |
Please provide a description of the function:def mps_device_memory_limit():
lib = _load_tcmps_lib()
if lib is None:
return None
c_size = _ctypes.c_uint64()
ret = lib.TCMPSMetalDeviceMemoryLimit(_ctypes.byref(c_size))
return c_size.value if ret == 0 else None | [
"\n Returns the memory size in bytes that can be effectively allocated on the\n MPS device that will be used, or None if no suitable device is available.\n "
] |
Please provide a description of the function:def shape(self):
# 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 pointer i... | [
"Copy the shape from TCMPS as a new numpy ndarray."
] |
Please provide a description of the function:def asnumpy(self):
# 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
dim = _ctype... | [
"Copy the data from TCMPS into a new numpy ndarray"
] |
Please provide a description of the function:def train(self, input, label):
assert self._mode == MpsGraphMode.Train
assert input.shape == self._ishape
assert label.shape == self._oshape
input_array = MpsFloatArray(input)
label_array = MpsFloatArray(label)
resul... | [
"\n Submits an input batch to the model. Returns a MpsFloatArray\n representing the batch loss. Calling asnumpy() on this value will wait\n for the batch to finish and yield the loss as a numpy array.\n "
] |
Please provide a description of the function:def predict(self, input):
assert self._mode == MpsGraphMode.Inference
assert input.shape == self._ishape
input_array = MpsFloatArray(input)
result_handle = _ctypes.c_void_p()
status_code = self._LIB.TCMPSPredictGraph(
... | [
"\n Submits an input batch to the model. Returns a MpsFloatArray\n representing the model predictions. Calling asnumpy() on this value will\n wait for the batch to finish and yield the predictions as a numpy array.\n "
] |
Please provide a description of the function:def train_return_grad(self, input, grad):
assert self._mode == MpsGraphMode.TrainReturnGrad
assert input.shape == self._ishape
assert grad.shape == self._oshape
input_array = MpsFloatArray(input)
grad_array = MpsFloatArray(g... | [
"\n Performs a forward pass from the input batch, followed by a backward\n pass using the provided gradient (in place of a loss function). Returns\n a MpsFloatArray representing the output (final gradient) of the backward\n pass. Calling asnumpy() on this value will wait for the batch to... |
Please provide a description of the function:def route_sns_task(event, context):
record = event['Records'][0]
message = json.loads(
record['Sns']['Message']
)
return run_message(message) | [
"\n Gets SNS Message, deserialises the message,\n imports the function, calls the function with args\n "
] |
Please provide a description of the function:def run_message(message):
if message.get('capture_response', False):
DYNAMODB_CLIENT.put_item(
TableName=ASYNC_RESPONSE_TABLE,
Item={
'id': {'S': str(message['response_id'])},
'ttl': {'N': str(int(time.... | [
"\n Runs a function defined by a message object with keys:\n 'task_path', 'args', and 'kwargs' used by lambda routing\n and a 'command' in handler.py\n "
] |
Please provide a description of the function:def run(func, args=[], kwargs={}, service='lambda', capture_response=False,
remote_aws_lambda_function_name=None, remote_aws_region=None, **task_kwargs):
lambda_function_name = remote_aws_lambda_function_name or os.environ.get('AWS_LAMBDA_FUNCTION_NAME')
... | [
"\n Instead of decorating a function with @task, you can just run it directly.\n If you were going to do func(*args, **kwargs), then you will call this:\n\n import zappa.asynchronous.run\n zappa.asynchronous.run(func, args, kwargs)\n\n If you want to use SNS, then do:\n\n zappa.asynchronous.run(fu... |
Please provide a description of the function:def task(*args, **kwargs):
func = None
if len(args) == 1 and callable(args[0]):
func = args[0]
if not kwargs: # Default Values
service = 'lambda'
lambda_function_name_arg = None
aws_region_arg = None
else: # Arguments... | [
"Async task decorator so that running\n\n Args:\n func (function): the function to be wrapped\n Further requirements:\n func must be an independent top-level function.\n i.e. not a class method or an anonymous function\n service (str): either 'lambda' or 'sns'\... |
Please provide a description of the function:def import_and_get_task(task_path):
module, function = task_path.rsplit('.', 1)
app_module = importlib.import_module(module)
app_function = getattr(app_module, function)
return app_function | [
"\n Given a modular path to a function, import that module\n and return the function.\n "
] |
Please provide a description of the function:def get_func_task_path(func):
module_path = inspect.getmodule(func).__name__
task_path = '{module_path}.{func_name}'.format(
module_path=module_path,
func_name=func.__name__
... | [
"\n Format the modular task path for a function via inspection.\n "
] |
Please provide a description of the function:def get_async_response(response_id):
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['Item']['a... | [
"\n Get the response from the async table\n "
] |
Please provide a description of the function:def send(self, task_path, args, kwargs):
message = {
'task_path': task_path,
'capture_response': self.capture_response,
'response_id': self.response_id,
'args': args,
'kwargs': k... | [
"\n Create the message object and pass it to the actual sender.\n "
] |
Please provide a description of the function:def _send(self, message):
message['command'] = 'zappa.asynchronous.route_lambda_task'
payload = json.dumps(message).encode('utf-8')
if len(payload) > LAMBDA_ASYNC_PAYLOAD_LIMIT: # pragma: no cover
raise AsyncException("Payload too... | [
"\n Given a message, directly invoke the lamdba function for this task.\n "
] |
Please provide a description of the function:def _send(self, message):
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 AsyncException("Payload too la... | [
"\n Given a message, publish to this topic.\n "
] |
Please provide a description of the function:def parse_s3_url(url):
bucket = ''
path = ''
if url:
result = urlparse(url)
bucket = result.netloc
path = result.path.strip('/')
return bucket, path | [
"\n Parses S3 URL.\n\n Returns bucket (domain) and file (full path).\n "
] |
Please provide a description of the function:def string_to_timestamp(timestring):
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.timetuple())
... | [
"\n Accepts a str, returns an int timestamp.\n "
] |
Please provide a description of the function:def detect_django_settings():
matches = []
for root, dirnames, filenames in os.walk(os.getcwd()):
for filename in fnmatch.filter(filenames, '*settings.py'):
full = os.path.join(root, filename)
if 'site-packages' in full:
... | [
"\n Automatically try to discover Django settings files,\n return them as relative module paths.\n "
] |
Please provide a description of the function:def detect_flask_apps():
matches = []
for root, dirnames, filenames in os.walk(os.getcwd()):
for filename in fnmatch.filter(filenames, '*.py'):
full = os.path.join(root, filename)
if 'site-packages' in full:
conti... | [
"\n Automatically try to discover Flask apps files,\n return them as relative module paths.\n "
] |
Please provide a description of the function:def add_event_source(event_source, lambda_arn, target_function, boto_session, dry=False):
event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False)
# TODO: Detect changes in config and refine exists algor... | [
"\n Given an event_source dictionary, create the object and add the event source.\n "
] |
Please provide a description of the function:def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False):
event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False)
# This is slightly dirty, but necessary for using Ka... | [
"\n Given an event_source dictionary, create the object and remove the event source.\n "
] |
Please provide a description of the function:def get_event_source_status(event_source, lambda_arn, target_function, boto_session, dry=False):
event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False)
return event_source_obj.status(funk) | [
"\n Given an event_source dictionary, create the object and get the event source status.\n "
] |
Please provide a description of the function:def check_new_version_available(this_version):
import requests
pypi_url = 'https://pypi.python.org/pypi/Zappa/json'
resp = requests.get(pypi_url, timeout=1.5)
top_version = resp.json()['info']['version']
return this_version != top_version | [
"\n Checks if a newer version of Zappa is available.\n\n Returns True is updateable, else False.\n\n "
] |
Please provide a description of the function:def validate_name(name, maxlen=80):
if not isinstance(name, basestring):
msg = "Name must be of type string"
raise InvalidAwsLambdaName(msg)
if len(name) > maxlen:
msg = "Name is longer than {maxlen} characters."
raise InvalidAwsL... | [
"Validate name for AWS Lambda function.\n name: actual name (without `arn:aws:lambda:...:` prefix and without\n `:$LATEST`, alias or version suffix.\n maxlen: max allowed length for name without prefix and suffix.\n\n The value 80 was calculated from prefix with longest known region name\n and as... |
Please provide a description of the function:def contains_python_files_or_subdirs(folder):
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 dirs:
for _, subdirs, ... | [
"\n Checks (recursively) if the directory contains .py or .pyc files\n "
] |
Please provide a description of the function:def conflicts_with_a_neighbouring_module(directory_path):
parent_dir_path, current_dir_name = os.path.split(os.path.normpath(directory_path))
neighbours = os.listdir(parent_dir_path)
conflicting_neighbour_filename = current_dir_name+'.py'
return conflict... | [
"\n Checks if a directory lies in the same directory as a .py file with the same name.\n "
] |
Please provide a description of the function:def is_valid_bucket_name(name):
# Bucket names must be at least 3 and no more than 63 characters long.
if (len(name) < 3 or len(name) > 63):
return False
# Bucket names must not contain uppercase characters or underscores.
if (any(x.isupper() for... | [
"\n Checks if an S3 bucket name is valid according to https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules\n "
] |
Please provide a description of the function:def merge_headers(event):
headers = event.get('headers') or {}
multi_headers = (event.get('multiValueHeaders') or {}).copy()
for h in set(headers.keys()):
if h not in multi_headers:
multi_headers[h] = [headers[h]]
for h in multi_heade... | [
"\n Merge the values of headers and multiValueHeaders into a single dict.\n Opens up support for multivalue headers via API Gateway and ALB.\n See: https://github.com/Miserlou/Zappa/pull/1756\n "
] |
Please provide a description of the function:def create_wsgi_request(event_info,
server_name='zappa',
script_name=None,
trailing_slash=True,
binary_support=False,
base_path=None,
... | [
"\n Given some event_info via API Gateway,\n create and return a valid WSGI request environ.\n ",
"\n API Gateway and ALB both started allowing for multi-value querystring\n params in Nov. 2018. If there aren't multi-value params present, then\n it acts identically to 'qu... |
Please provide a description of the function:def common_log(environ, response, response_time=None):
logger = logging.getLogger()
if response_time:
formatter = ApacheFormatter(with_response_time=True)
try:
log_entry = formatter(response.status_code, environ,
... | [
"\n Given the WSGI environ and the response,\n log this event in Common Log Format.\n\n "
] |
Please provide a description of the function:def load_remote_project_archive(self, project_zip_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 cold lambda, get it from S3
... | [
"\n Puts the project files from S3 in /tmp and adds to path\n "
] |
Please provide a description of the function:def load_remote_settings(self, remote_bucket, remote_file):
if not self.session:
boto_session = boto3.Session()
else:
boto_session = self.session
s3 = boto_session.resource('s3')
try:
remote_env_ob... | [
"\n Attempt to read a file from s3 containing a flat json object. Adds each\n key->value pair as environment variables. Helpful for keeping\n sensitiZve or stage-specific configuration variables in s3 instead of\n version control.\n "
] |
Please provide a description of the function:def import_module_and_get_function(whole_function):
module, function = whole_function.rsplit('.', 1)
app_module = importlib.import_module(module)
app_function = getattr(app_module, function)
return app_function | [
"\n Given a modular path to a function, import that module\n and return the function.\n "
] |
Please provide a description of the function:def run_function(app_function, event, context):
# getargspec does not support python 3 method with type hints
# Related issue: https://github.com/Miserlou/Zappa/issues/1452
if hasattr(inspect, "getfullargspec"): # Python 3
args, ... | [
"\n Given a function and event context,\n detect signature and execute, returning any result.\n "
] |
Please provide a description of the function:def get_function_for_aws_event(self, record):
if 's3' in record:
if ':' in record['s3']['configurationId']:
return record['s3']['configurationId'].split(':')[-1]
arn = None
if 'Sns' in record:
try:
... | [
"\n Get the associated function to execute for a triggered AWS event\n\n Support S3, SNS, DynamoDB, kinesis and SQS events\n "
] |
Please provide a description of the function:def get_function_from_bot_intent_trigger(self, event):
intent = event.get('currentIntent')
if intent:
intent = intent.get('name')
if intent:
return self.settings.AWS_BOT_EVENT_MAPPING.get(
"... | [
"\n For the given event build ARN and return the configured function\n "
] |
Please provide a description of the function:def get_function_for_cognito_trigger(self, trigger):
print("get_function_for_cognito_trigger", self.settings.COGNITO_TRIGGER_MAPPING, trigger, self.settings.COGNITO_TRIGGER_MAPPING.get(trigger))
return self.settings.COGNITO_TRIGGER_MAPPING.get(trigge... | [
"\n Get the associated function to execute for a cognito trigger\n "
] |
Please provide a description of the function:def handler(self, event, context):
settings = self.settings
# If in DEBUG mode, log all raw incoming events.
if settings.DEBUG:
logger.debug('Zappa Event: {}'.format(event))
# Set any API Gateway defined Stage Variables
... | [
"\n An AWS Lambda function which parses specific API Gateway input into a\n WSGI request, feeds it to our WSGI app, procceses the response, and returns\n that back to the API Gateway.\n\n "
] |
Please provide a description of the function:def lambda_handler(event, context):
print("Client token: " + event['authorizationToken'])
print("Method ARN: " + event['methodArn'])
principalId = "user|a1b2c3d4"
tmp ... | [
"validate the incoming token",
"and produce the principal user identifier associated with the token",
"this could be accomplished in a number of ways:",
"1. Call out to OAuth provider",
"2. Decode a JWT token inline",
"3. Lookup in a self-managed DB",
"you can send a 401 Unauthorized response to the cli... |
Please provide a description of the function:def _addMethod(self, effect, verb, resource, conditions):
if verb != "*" and not hasattr(HttpVerb, verb):
raise NameError("Invalid HTTP verb " + verb + ". Allowed verbs in HttpVerb class")
resourcePattern = re.compile(self.pathRegex)
... | [
"Adds a method to the internal lists of allowed or denied methods. Each object in\n the internal list contains a resource ARN and a condition statement. The condition\n statement can be null."
] |
Please provide a description of the function:def allowMethodWithConditions(self, verb, resource, conditions):
self._addMethod("Allow", verb, resource, conditions) | [
"Adds an API Gateway method (Http verb + Resource path) to the list of allowed\n methods and includes a condition for the policy statement. More on AWS policy\n conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition"
] |
Please provide a description of the function:def denyMethodWithConditions(self, verb, resource, conditions):
self._addMethod("Deny", verb, resource, conditions) | [
"Adds an API Gateway method (Http verb + Resource path) to the list of denied\n methods and includes a condition for the policy statement. More on AWS policy\n conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition"
] |
Please provide a description of the function:def build(self):
if ((self.allowMethods is None or len(self.allowMethods) == 0) and
(self.denyMethods is None or len(self.denyMethods) == 0)):
raise NameError("No statements defined for the policy")
policy = {
'pr... | [
"Generates the policy document based on the internal lists of allowed and denied\n conditions. This will generate a policy with two main statements for the effect:\n one statement for Allow and one statement for Deny.\n Methods that includes conditions will have their own statement in the polic... |
Please provide a description of the function:def configure_boto_session_method_kwargs(self, service, kw):
if service in self.endpoint_urls and not 'endpoint_url' in kw:
kw['endpoint_url'] = self.endpoint_urls[service]
return kw | [
"Allow for custom endpoint urls for non-AWS (testing and bootleg cloud) deployments"
] |
Please provide a description of the function:def boto_client(self, service, *args, **kwargs):
return self.boto_session.client(service, *args, **self.configure_boto_session_method_kwargs(service, kwargs)) | [
"A wrapper to apply configuration options to boto clients"
] |
Please provide a description of the function:def boto_resource(self, service, *args, **kwargs):
return self.boto_session.resource(service, *args, **self.configure_boto_session_method_kwargs(service, kwargs)) | [
"A wrapper to apply configuration options to boto resources"
] |
Please provide a description of the function: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.P... | [] |
Please provide a description of the function:def get_deps_list(self, pkg_name, installed_distros=None):
# https://github.com/Miserlou/Zappa/issues/1478. Using `pkg_resources`
# instead of `pip` is the recommended approach. The usage is nearly
# identical.
import pkg_resources
... | [
"\n For a given package, returns a list of required packages. Recursive.\n "
] |
Please provide a description of the function:def create_handler_venv(self):
import subprocess
# We will need the currenv venv to pull Zappa from
current_venv = self.get_current_venv()
# Make a new folder for the handler packages
ve_path = os.path.join(os.getcwd(), 'han... | [
"\n Takes the installed zappa and brings it into a fresh virtualenv-like folder. All dependencies are then downloaded.\n "
] |
Please provide a description of the function:def get_current_venv():
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', 'help'], stderr=subpro... | [
"\n Returns the path to the current virtualenv\n "
] |
Please provide a description of the function:def create_lambda_zip( self,
prefix='lambda_package',
handler_file=None,
slim_handler=False,
minify=True,
exclude=None,
... | [
"\n Create a Lambda-ready zip file of the current virtualenvironment and working directory.\n\n Returns path to that file.\n\n "
] |
Please provide a description of the function:def extract_lambda_package(self, package_name, path):
lambda_package = lambda_packages[package_name][self.runtime]
# Trash the local version to help with package space saving
shutil.rmtree(os.path.join(path, package_name), ignore_errors=True... | [
"\n Extracts the lambda package into a given path. Assumes the package exists in lambda packages.\n "
] |
Please provide a description of the function:def get_installed_packages(site_packages, site_packages_64):
import pkg_resources
package_to_keep = []
if os.path.isdir(site_packages):
package_to_keep += os.listdir(site_packages)
if os.path.isdir(site_packages_64):
... | [
"\n Returns a dict of installed packages that Zappa cares about.\n "
] |
Please provide a description of the function:def have_correct_lambda_package_version(self, package_name, package_version):
lambda_package_details = lambda_packages.get(package_name, {}).get(self.runtime)
if lambda_package_details is None:
return False
# Binaries can be com... | [
"\n Checks if a given package version binary should be copied over from lambda packages.\n package_name should be lower-cased version of package name.\n "
] |
Please provide a description of the function:def download_url_with_progress(url, stream, disable_progress):
resp = requests.get(url, timeout=float(os.environ.get('PIP_TIMEOUT', 2)), stream=True)
resp.raw.decode_content = True
progress = tqdm(unit="B", unit_scale=True, total=int(resp.he... | [
"\n Downloads a given url in chunks and writes to the provided stream (can be any io stream).\n Displays the progress bar for the download.\n "
] |
Please provide a description of the function:def get_cached_manylinux_wheel(self, package_name, package_version, disable_progress=False):
cached_wheels_dir = os.path.join(tempfile.gettempdir(), 'cached_wheels')
if not os.path.isdir(cached_wheels_dir):
os.makedirs(cached_wheels_dir)
... | [
"\n Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it.\n "
] |
Please provide a description of the function:def get_manylinux_wheel_url(self, package_name, package_version):
cached_pypi_info_dir = os.path.join(tempfile.gettempdir(), 'cached_pypi_info')
if not os.path.isdir(cached_pypi_info_dir):
os.makedirs(cached_pypi_info_dir)
# Even ... | [
"\n For a given package name, returns a link to the download URL,\n else returns None.\n\n Related: https://github.com/Miserlou/Zappa/issues/398\n Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b56880adbae\n\n This function downloads metadata JSON of `package... |
Please provide a description of the function:def upload_to_s3(self, source_path, bucket_name, disable_progress=False):
r
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError:
# This is really stupid S3 quirk. Technically, us-east-1 on... | [
"\n Given a file, upload it to S3.\n Credentials should be stored in environment variables or ~/.aws/credentials (%USERPROFILE%\\.aws\\credentials on Windows).\n\n Returns True on success, false on failure.\n\n "
] |
Please provide a description of the function:def copy_on_s3(self, src_file_name, dst_file_name, bucket_name):
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e: # pragma: no cover
# If a client error is thrown, then check th... | [
"\n Copies src file to destination within a bucket.\n "
] |
Please provide a description of the function:def remove_from_s3(self, file_name, bucket_name):
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e: # pragma: no cover
# If a client error is thrown, then check that it was a 404... | [
"\n Given a file name and a bucket, remove it from S3.\n\n 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.\n\n Returns True on success, False on failure.\n\n "
] |
Please provide a description of the function:def create_lambda_function( self,
bucket=None,
function_name=None,
handler=None,
s3_key=None,
description='Zappa De... | [
"\n Given a bucket and key (or a local path) of a valid Lambda-zip, a function name and a handler, register that Lambda function.\n "
] |
Please provide a description of the function:def update_lambda_function(self, bucket, function_name, s3_key=None, publish=True, local_zip=None, num_revisions=None):
print("Updating Lambda function code..")
kwargs = dict(
FunctionName=function_name,
Publish=publish
... | [
"\n 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.\n Optionally, delete previous versions if they exceed the optional limit.\n "
] |
Please provide a description of the function:def update_lambda_configuration( self,
lambda_arn,
function_name,
handler,
description='Zappa Deployment',
... | [
"\n Given an existing function ARN, update the configuration variables.\n "
] |
Please provide a description of the function:def invoke_lambda_function( self,
function_name,
payload,
invocation_type='Event',
log_type='Tail',
client_context=... | [
"\n Directly invoke a named Lambda function with a payload.\n Returns the response.\n "
] |
Please provide a description of the function:def rollback_lambda_function_version(self, function_name, versions_back=1, publish=True):
response = self.lambda_client.list_versions_by_function(FunctionName=function_name)
# Take into account $LATEST
if len(response['Versions']) < versions... | [
"\n Rollback the lambda function code 'versions_back' number of revisions.\n\n Returns the Function ARN.\n "
] |
Please provide a description of the function:def get_lambda_function(self, function_name):
response = self.lambda_client.get_function(
FunctionName=function_name)
return response['Configuration']['FunctionArn'] | [
"\n Returns the lambda function ARN, given a name\n\n This requires the \"lambda:GetFunction\" role.\n "
] |
Please provide a description of the function:def get_lambda_function_versions(self, function_name):
try:
response = self.lambda_client.list_versions_by_function(
FunctionName=function_name
)
return response.get('Versions', [])
except Exception... | [
"\n Simply returns the versions available for a Lambda function, given a function name.\n\n "
] |
Please provide a description of the function:def deploy_lambda_alb( self,
lambda_arn,
lambda_name,
alb_vpc_config,
timeout
):
if not alb_vpc_config:
rais... | [
"\n The `zappa deploy` functionality for ALB infrastructure.\n "
] |
Please provide a description of the function:def undeploy_lambda_alb(self, lambda_name):
print("Undeploying ALB infrastructure...")
# Locate and delete alb/lambda permissions
try:
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#Lambd... | [
"\n The `zappa undeploy` functionality for ALB infrastructure.\n "
] |
Please provide a description of the function:def create_api_gateway_routes( self,
lambda_arn,
api_name=None,
api_key_required=False,
authorization_type='NONE',
... | [
"\n Create the API Gateway for this Zappa deployment.\n\n Returns the new RestAPI CF resource.\n "
] |
Please provide a description of the function:def create_authorizer(self, restapi, uri, authorizer):
authorizer_type = authorizer.get("type", "TOKEN").upper()
identity_validation_expression = authorizer.get('validation_expression', None)
authorizer_resource = troposphere.apigateway.Auth... | [
"\n Create Authorizer for API gateway\n "
] |
Please provide a description of the function:def create_and_setup_methods(
self,
restapi,
resource,
api_key_required,
uri,
... | [
"\n Set up the methods, integration responses and method responses for a given API Gateway resource.\n "
] |
Please provide a description of the function:def create_and_setup_cors(self, restapi, resource, uri, depth, config):
if config is True:
config = {}
method_name = "OPTIONS"
method = troposphere.apigateway.Method(method_name + str(depth))
method.RestApiId = troposphere... | [
"\n Set up the methods, integration responses and method responses for a given API Gateway resource.\n "
] |
Please provide a description of the function:def deploy_api_gateway( self,
api_id,
stage_name,
stage_description="",
description="",
cache_cluster_enabled=False,
... | [
"\n Deploy the API Gateway!\n\n Return the deployed API URL.\n "
] |
Please provide a description of the function:def remove_binary_support(self, api_id, cors=False):
response = self.apigateway_client.get_rest_api(
restApiId=api_id
)
if "binaryMediaTypes" in response and "*/*" in response["binaryMediaTypes"]:
self.apigateway_clien... | [
"\n Remove binary support\n "
] |
Please provide a description of the function:def add_api_compression(self, api_id, min_compression_size):
self.apigateway_client.update_rest_api(
restApiId=api_id,
patchOperations=[
{
'op': 'replace',
'path': '/minimumCompr... | [
"\n Add Rest API compression\n "
] |
Please provide a description of the function:def get_api_keys(self, api_id, stage_name):
response = self.apigateway_client.get_api_keys(limit=500)
stage_key = '{}/{}'.format(api_id, stage_name)
for api_key in response.get('items'):
if stage_key in api_key.get('stageKeys'):
... | [
"\n Generator that allows to iterate per API keys associated to an api_id and a stage_name.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.