desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Updates the width and height fields of the jpeg image.
Raises:
BadImageError if the image string is not a valid jpeg image.'
| def _update_jpeg_dimensions(self):
| size = len(self._image_data)
offset = 2
while (offset < size):
while ((offset < size) and (ord(self._image_data[offset]) != 255)):
offset += 1
while ((offset < size) and (ord(self._image_data[offset]) == 255)):
offset += 1
if ((offset < size) and ((ord(self._i... |
'Updates the width and height fields of the tiff image.
Raises:
BadImageError if the image string is not a valid tiff image.'
| def _update_tiff_dimensions(self):
| size = len(self._image_data)
if self._image_data.startswith('II'):
endianness = '<'
else:
endianness = '>'
ifd_offset = struct.unpack((endianness + 'I'), self._image_data[4:8])[0]
if ((ifd_offset + 14) <= size):
ifd_size = struct.unpack((endianness + 'H'), self._image_data[if... |
'Updates the width and height fields of the bmp image.
Raises:
BadImageError if the image string is not a valid bmp image.'
| def _update_bmp_dimensions(self):
| size = len(self._image_data)
if (size >= 18):
header_length = struct.unpack('<I', self._image_data[14:18])[0]
if (((header_length == 40) or (header_length == 108) or (header_length == 124) or (header_length == 64)) and (size >= 26)):
(self._width, self._height) = struct.unpack('<II',... |
'Updates the width and height fields of the ico image.
Raises:
BadImageError if the image string is not a valid ico image.'
| def _update_ico_dimensions(self):
| size = len(self._image_data)
if (size >= 8):
(self._width, self._height) = struct.unpack('<BB', self._image_data[6:8])
if (not self._width):
self._width = 256
if (not self._height):
self._height = 256
else:
raise BadImageError('Corrupt ICO format... |
'Set flag to correct image orientation based on image metadata.
EXIF metadata within the image may contain a parameter indicating its proper
orientation. This value can equal 1 through 8, inclusive. "1" means that the
image is in its "normal" orientation, i.e., it should be viewed as it is
stored. Normally, this "orien... | def set_correct_orientation(self, correct_orientation):
| if (correct_orientation not in ORIENTATION_CORRECTION_TYPE):
raise BadRequestError(('Orientation correction must be in %s' % ORIENTATION_CORRECTION_TYPE))
self._correct_orientation = correct_orientation
|
'Updates the width and height fields of the webp image.'
| def _update_webp_dimensions(self):
| size = len(self._image_data)
if (size < 30):
raise BadImageError('Corrupt WEBP format')
bits = ((ord(self._image_data[20]) | (ord(self._image_data[21]) << 8)) | (ord(self._image_data[22]) << 16))
key_frame = ((bits & 1) == 0)
if (not key_frame):
raise BadImageError('Corrupt ... |
'Updates the width and height fields of a webp image with vp8x chunk.'
| def _update_webp_vp8x_dimensions(self):
| size = len(self._image_data)
if (size < 30):
raise BadImageError('Corrupt WEBP format')
(self._width, self._height) = struct.unpack('<II', self._image_data[24:32])
if ((self._height is None) or (self._width is None)):
raise BadImageError('Corrupt WEBP format')
|
'Resize the image maintaining the aspect ratio.
If both width and height are specified, the more restricting of the two
values will be used when resizing the image. The maximum dimension allowed
for both width and height is 4000 pixels.
If both width and height are specified and crop_to_fit is True, the less
restrictin... | def resize(self, width=0, height=0, crop_to_fit=False, crop_offset_x=0.5, crop_offset_y=0.5, allow_stretch=False):
| if ((not isinstance(width, (int, long))) or (not isinstance(height, (int, long)))):
raise TypeError('Width and height must be integers.')
if ((width < 0) or (height < 0)):
raise BadRequestError('Width and height must be >= 0.')
if ((not width) and (not height... |
'Rotate an image a given number of degrees clockwise.
Args:
degrees: int, must be a multiple of 90.
Raises:
TypeError when degrees is not either \'int\' or \'long\' types.
BadRequestError when there is something wrong with the given degrees or
if MAX_TRANSFORMS_PER_REQUEST transforms have already been requested.'
| def rotate(self, degrees):
| if (not isinstance(degrees, (int, long))):
raise TypeError('Degrees must be integers.')
if ((degrees % 90) != 0):
raise BadRequestError('degrees argument must be multiple of 90.')
degrees = (degrees % 360)
self._check_transform_limits()
transform = images_s... |
'Flip the image horizontally.
Raises:
BadRequestError if MAX_TRANSFORMS_PER_REQUEST transforms have already been
requested on the image.'
| def horizontal_flip(self):
| self._check_transform_limits()
transform = images_service_pb.Transform()
transform.set_horizontal_flip(True)
self._transforms.append(transform)
|
'Flip the image vertically.
Raises:
BadRequestError if MAX_TRANSFORMS_PER_REQUEST transforms have already been
requested on the image.'
| def vertical_flip(self):
| self._check_transform_limits()
transform = images_service_pb.Transform()
transform.set_vertical_flip(True)
self._transforms.append(transform)
|
'Validate the given value of a Crop() method argument.
Args:
val: float, value of the argument.
val_name: str, name of the argument.
Raises:
TypeError if the args are not of type \'float\'.
BadRequestError when there is something wrong with the given bounding box.'
| def _validate_crop_arg(self, val, val_name):
| if (type(val) != float):
raise TypeError(("arg '%s' must be of type 'float'." % val_name))
if (not (0 <= val <= 1.0)):
raise BadRequestError(("arg '%s' must be between 0.0 and 1.0 (inclusive)" % val_name))
|
'Crop the image.
The four arguments are the scaling numbers to describe the bounding box
which will crop the image. The upper left point of the bounding box will
be at (left_x*image_width, top_y*image_height) the lower right point will
be at (right_x*image_width, bottom_y*image_height).
Args:
left_x: float value betwe... | def crop(self, left_x, top_y, right_x, bottom_y):
| self._validate_crop_arg(left_x, 'left_x')
self._validate_crop_arg(top_y, 'top_y')
self._validate_crop_arg(right_x, 'right_x')
self._validate_crop_arg(bottom_y, 'bottom_y')
if (left_x >= right_x):
raise BadRequestError('left_x must be less than right_x')
if (top_y >= bottom... |
'Automatically adjust image contrast and color levels.
This is similar to the "I\'m Feeling Lucky" button in Picasa.
Raises:
BadRequestError if MAX_TRANSFORMS_PER_REQUEST transforms have already
been requested for this image.'
| def im_feeling_lucky(self):
| self._check_transform_limits()
transform = images_service_pb.Transform()
transform.set_autolevels(True)
self._transforms.append(transform)
|
'Metadata of the original image.
Returns a dictionary of metadata extracted from the original image during
execute_transform.
Note, that some of the EXIF fields are processed, e.g., fields with multiple
values returned as lists, rational types are returned as floats, GPS
coordinates already parsed to signed floats, etc... | def get_original_metadata(self):
| return self._original_metadata
|
'Fills in an ImageData PB from this Image instance.
Args:
imagedata: An ImageData PB instance'
| def _set_imagedata(self, imagedata):
| if self._blob_key:
imagedata.set_content('')
imagedata.set_blob_key(self._blob_key)
else:
imagedata.set_content(self._image_data)
|
'Perform transformations on a given image.
Args:
output_encoding: A value from OUTPUT_ENCODING_TYPES.
quality: A value between 1 and 100 to specify the quality of the
encoding. This value is only used for JPEG & WEBP quality control.
parse_source_metadata: when True the metadata (EXIF) of the source image
is parsed be... | def execute_transforms(self, output_encoding=PNG, quality=None, parse_source_metadata=False, transparent_substitution_rgb=None, rpc=None):
| rpc = self.execute_transforms_async(output_encoding=output_encoding, quality=quality, parse_source_metadata=parse_source_metadata, transparent_substitution_rgb=transparent_substitution_rgb, rpc=rpc)
return rpc.get_result()
|
'Perform transformations on a given image - async version.
Args:
output_encoding: A value from OUTPUT_ENCODING_TYPES.
quality: A value between 1 and 100 to specify the quality of the
encoding. This value is only used for JPEG & WEBP quality control.
parse_source_metadata: when True the metadata (EXIF) of the source im... | def execute_transforms_async(self, output_encoding=PNG, quality=None, parse_source_metadata=False, transparent_substitution_rgb=None, rpc=None):
| if (output_encoding not in OUTPUT_ENCODING_TYPES):
raise BadRequestError(('Output encoding type not in recognized set %s' % OUTPUT_ENCODING_TYPES))
if (not self._transforms):
raise BadRequestError('Must specify at least one transformation.')
if transparent... |
'Gets the width of the image.'
| @property
def width(self):
| if (self._width is None):
self._update_dimensions()
return self._width
|
'Gets the height of the image.'
| @property
def height(self):
| if (self._height is None):
self._update_dimensions()
return self._height
|
'Gets the format of the image.'
| @property
def format(self):
| if (self._format is None):
self._update_dimensions()
return self._format
|
'Calculates the histogram of the image.
Args:
rpc: A UserRPC object.
Returns: 3 256-element lists containing the number of occurences of each
value of each color in the order RGB. As described at
http://en.wikipedia.org/wiki/Color_histogram for N = 256. i.e. the first
value of the first list contains the number of pixe... | def histogram(self, rpc=None):
| rpc = self.histogram_async(rpc)
return rpc.get_result()
|
'Calculates the histogram of the image - async version.
Args:
rpc: An optional UserRPC object.
Returns:
rpc: A UserRPC object.
Raises:
NotImageError when the image data given is not an image.
BadImageError when the image data given is corrupt.
LargeImageError when the image data given is too large to process.
Error whe... | def histogram_async(self, rpc=None):
| request = images_service_pb.ImagesHistogramRequest()
response = images_service_pb.ImagesHistogramResponse()
self._set_imagedata(request.mutable_image())
def get_histogram_hook(rpc):
'Check success, handles exceptions and returns the converted RPC result.\n\n ... |
'Checks that a parameters is an integer within the specified range.'
| @staticmethod
def CheckValidIntParameter(parameter, min_value, max_value, name):
| if (parameter is not None):
if (not isinstance(parameter, (int, long))):
raise TypeError(('%s must be an integer.' % name))
if ((parameter > max_value) or (parameter < min_value)):
raise BadRequestError(('%s must be between %s and %s.' % name), s... |
'Preloads PIL to load all modules in the unhardened environment.
Args:
service_name: Service name expected for all calls.
host_prefix: the URL prefix (protocol://host) to prepend to image urls
on a call to GetUrlBase.'
| def __init__(self, service_name='images', host_prefix=''):
| super(ImagesServiceStub, self).__init__(service_name, max_request_size=MAX_REQUEST_SIZE)
self._blob_stub = images_blob_stub.ImagesBlobStub(host_prefix)
Image.init()
|
'Implementation of ImagesService::Composite.
Based off documentation of the PIL library at
http://www.pythonware.com/library/pil/handbook/index.htm
Args:
request: ImagesCompositeRequest, contains image request info.
response: ImagesCompositeResponse, contains transformed image.'
| def _Dynamic_Composite(self, request, response):
| width = request.canvas().width()
height = request.canvas().height()
color = _ArgbToRgbaTuple(request.canvas().color())
color = _BackendPremultiplication(color)
canvas = Image.new('RGBA', (width, height), color)
sources = []
if ((not request.canvas().width()) or (request.canvas().width() > 40... |
'Trivial implementation of ImagesService::Histogram.
Based off documentation of the PIL library at
http://www.pythonware.com/library/pil/handbook/index.htm
Args:
request: ImagesHistogramRequest, contains the image.
response: ImagesHistogramResponse, contains histogram of the image.'
| def _Dynamic_Histogram(self, request, response):
| image = self._OpenImageData(request.image())
img_format = image.format
if (img_format not in ('BMP', 'GIF', 'ICO', 'JPEG', 'PNG', 'TIFF', 'WEBP')):
raise apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.NOT_IMAGE)
image = image.convert('RGBA')
red = ([0] * 256)
green... |
'Trivial implementation of ImagesService::Transform.
Based off documentation of the PIL library at
http://www.pythonware.com/library/pil/handbook/index.htm
Args:
request: ImagesTransformRequest, contains image request info.
response: ImagesTransformResponse, contains transformed image.'
| def _Dynamic_Transform(self, request, response):
| original_image = self._OpenImageData(request.image())
input_settings = request.input()
correct_orientation = (input_settings.has_correct_exif_orientation() and (input_settings.correct_exif_orientation() == images_service_pb.InputSettings.CORRECT_ORIENTATION))
source_metadata = self._ExtractMetadata(orig... |
'Encode the given image and return it in string form.
Args:
image: PIL Image object, image to encode.
output_encoding: ImagesTransformRequest.OutputSettings object.
substitution_rgb: The color to use for transparent pixels if the output
format does not support transparency.
Returns:
str with encoded image information i... | def _EncodeImage(self, image, output_encoding, substitution_rgb=None):
| image_string = StringIO.StringIO()
image_encoding = 'PNG'
if (output_encoding.mime_type() == images_service_pb.OutputSettings.WEBP):
image_encoding = 'WEBP'
if (output_encoding.mime_type() == images_service_pb.OutputSettings.JPEG):
image_encoding = 'JPEG'
if substitution_rgb:
... |
'Open image data from ImageData protocol buffer.
Args:
image_data: ImageData protocol buffer containing image data or blob
reference.
Returns:
Image containing the image data passed in or reference by blob-key.
Raises:
ApplicationError if both content and blob-key are provided.
NOTE: \'content\' must always be set beca... | def _OpenImageData(self, image_data):
| if (image_data.content() and image_data.has_blob_key()):
raise apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.INVALID_BLOB_KEY)
if image_data.has_blob_key():
image = self._OpenBlob(image_data.blob_key())
else:
image = self._OpenImage(image_data.content())
i... |
'Opens an image provided as a string.
Args:
image: image data to be opened
Raises:
apiproxy_errors.ApplicationError if the image cannot be opened or if it
is an unsupported format.
Returns:
Image containing the image data passed in.'
| def _OpenImage(self, image):
| if (not image):
raise apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.NOT_IMAGE)
image = StringIO.StringIO(image)
try:
return Image.open(image)
except IOError:
raise apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.BAD_IMAGE_DATA)
|
'Create an Image from the blob data read from blob_key.'
| def _OpenBlob(self, blob_key):
| storage_key = None
try:
gs_info = datastore.Get(datastore.Key.from_path(GS_INFO_KIND, blob_key, namespace=''))
storage_key = gs_info['storage_key']
except datastore_errors.EntityNotFoundError:
pass
if (not storage_key):
try:
key = datastore_types.Key.from_path... |
'Check an argument for the Crop transform.
Args:
arg: float, argument to Crop transform to check.
Raises:
apiproxy_errors.ApplicationError on problem with argument.'
| def _ValidateCropArg(self, arg):
| if (not isinstance(arg, float)):
raise apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)
if (not (0 <= arg <= 1.0)):
raise apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)
|
'Get new resize dimensions keeping the current aspect ratio.
This uses the more restricting of the two requested values to determine
the new ratio. See also crop_to_fit.
Args:
current_width: int, current width of the image.
current_height: int, current height of the image.
req_width: int, requested new width of the ima... | def _CalculateNewDimensions(self, current_width, current_height, req_width, req_height, crop_to_fit, allow_stretch):
| width_ratio = (float(req_width) / current_width)
height_ratio = (float(req_height) / current_height)
if allow_stretch:
if ((not req_width) or (not req_height)):
raise apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)
return (req_width, req_... |
'Use PIL to resize the given image with the given transform.
Args:
image: PIL.Image.Image object to resize.
transform: images_service_pb.Transform to use when resizing.
Returns:
PIL.Image.Image with transforms performed on it.
Raises:
BadRequestError if the resize data given is bad.'
| def _Resize(self, image, transform):
| width = 0
height = 0
if transform.has_width():
width = transform.width()
if ((width < 0) or (4000 < width)):
raise apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)
if transform.has_height():
height = transform.height()
... |
'Use PIL to rotate the given image with the given transform.
Args:
image: PIL.Image.Image object to rotate.
transform: images_service_pb.Transform to use when rotating.
Returns:
PIL.Image.Image with transforms performed on it.
Raises:
BadRequestError if the rotate data given is bad.'
| def _Rotate(self, image, transform):
| degrees = transform.rotate()
if ((degrees < 0) or ((degrees % 90) != 0)):
raise apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)
degrees %= 360
degrees = (360 - degrees)
return image.rotate(degrees, expand=True)
|
'Use PIL to crop the given image with the given transform.
Args:
image: PIL.Image.Image object to crop.
transform: images_service_pb.Transform to use when cropping.
Returns:
PIL.Image.Image with transforms performed on it.
Raises:
BadRequestError if the crop data given is bad.'
| def _Crop(self, image, transform):
| left_x = 0.0
top_y = 0.0
right_x = 1.0
bottom_y = 1.0
if transform.has_crop_left_x():
left_x = transform.crop_left_x()
self._ValidateCropArg(left_x)
if transform.has_crop_top_y():
top_y = transform.crop_top_y()
self._ValidateCropArg(top_y)
if transform.has_cro... |
'Extract EXIF metadata from the image.
Note that this is a much simplified version of metadata extraction. After
deployment applications have access to a more powerful parser that can
parse hundreds of fields from images.
Args:
image: PIL Image object.
parse_metadata: bool, True if metadata parsing has been requested. ... | @staticmethod
def _ExtractMetadata(image, parse_metadata):
| def ExifTimeToUnixtime(exif_time):
'Convert time in EXIF to unix time.\n\n Args:\n exif_time: str, the time from the EXIF block formated by EXIF standard.\n E.g., ... |
'Use PIL to correct the image orientation based on its EXIF.
See JEITA CP-3451 at http://www.exif.org/specifications.html,
Exif 2.2, page 18.
Args:
image: source PIL.Image.Image object.
orientation: integer in range (1,8) inclusive, corresponding the image
orientation from EXIF.
Returns:
PIL.Image.Image with transforms... | def _CorrectOrientation(self, image, orientation):
| if (orientation == 2):
image = image.transpose(Image.FLIP_LEFT_RIGHT)
elif (orientation == 3):
image = image.rotate(180)
elif (orientation == 4):
image = image.transpose(Image.FLIP_TOP_BOTTOM)
elif (orientation == 5):
image = image.transpose(Image.FLIP_TOP_BOTTOM)
... |
'Execute PIL operations based on transform values.
Args:
image: PIL.Image.Image instance, image to manipulate.
transforms: list of ImagesTransformRequest.Transform objects.
correct_orientation: True to indicate that image orientation should be
corrected based on its EXIF.
Returns:
PIL.Image.Image with transforms perfor... | def _ProcessTransforms(self, image, transforms, correct_orientation):
| new_image = image
if (len(transforms) > images.MAX_TRANSFORMS_PER_REQUEST):
raise apiproxy_errors.ApplicationError(images_service_pb.ImagesServiceError.BAD_TRANSFORM_DATA)
orientation = 1
if correct_orientation:
exif = self._GetExifFromImage(image)
if ((not exif) or (_EXIF_ORIENT... |
'Main entry point.
Args:
service: str, must be \'images\'.
call: str, name of the RPC to make, must be part of ImagesService.
request: pb object, corresponding args to the \'call\' argument.
response: pb object, return value for the \'call\' argument.
request_id: A unique string identifying the request associated with ... | def MakeSyncCall(self, service, call, request, response, request_id=None):
| if (service == 'images'):
if (call == 'GetUrlBase'):
self._blob_stub.GetUrlBase(request, response)
return
elif (call == 'DeleteUrlBase'):
self._blob_stub.DeleteUrlBase(request, response)
return
raise NotImplementedError('Unable to find the... |
'Stub implementation of blob-related parts of the images API.
Args:
host_prefix: the URL prefix (protocol://host) to prepend to image urls
on a call to GetUrlBase.'
| def __init__(self, host_prefix):
| self._host_prefix = host_prefix
|
'Trivial implementation of ImagesService::GetUrlBase.
Args:
request: ImagesGetUrlBaseRequest, contains a blobkey to an image
response: ImagesGetUrlBaseResponse, contains a url to serve the image'
| def GetUrlBase(self, request, response):
| if request.create_secure_url():
logging.info('Secure URLs will not be created using the development application server.')
entity_info = datastore.Entity(BLOB_SERVING_URL_KIND, name=request.blob_key(), namespace='')
entity_info['blob_key'] = request.blob_key()
datast... |
'Trivial implementation of ImagesService::DeleteUrlBase.
Args:
request: ImagesDeleteUrlBaseRequest, contains a blobkey to an image.
response: ImagesDeleteUrlBaseResonse - currently unused.'
| def DeleteUrlBase(self, request, response):
| key = datastore.Key.from_path(BLOB_SERVING_URL_KIND, request.blob_key(), namespace='')
datastore.Delete(key)
|
'Initializer for _VersionedLibrary.
Args:
name: The name of the library e.g. "django".
url: The URL for the library\'s project page e.g.
"http://www.djangoproject.com/".
description: A short description of the library e.g. "A framework...".
supported_versions: A list of supported version names ordered by release
date e... | def __init__(self, name, url, description, supported_versions, default_version=None, deprecated_versions=None, experimental_versions=None):
| self.name = name
self.url = url
self.description = description
self.supported_versions = supported_versions
self.default_version = default_version
self.deprecated_versions = (deprecated_versions or [])
self.experimental_versions = (experimental_versions or [])
|
'Returns argument, or raises an exception if it is invalid.
HTTP header names are defined by RFC 2616 section 4.2.
Args:
name: HTTP header field value.
unused_key: Unused.
Returns:
name argument, unchanged.
Raises:
appinfo_errors.InvalidHttpHeaderName: argument cannot be used as an HTTP
header name.'
| def Validate(self, name, unused_key=None):
| original_name = name
if isinstance(name, unicode):
try:
name = name.encode('ascii')
except UnicodeEncodeError:
raise appinfo_errors.InvalidHttpHeaderName('HTTP header values must not contain non-ASCII data')
name = name.lower()
if (not _HTTP_T... |
'Returns value, or raises an exception if it is invalid.
According to RFC 2616 section 4.2, header field values must consist "of
either *TEXT or combinations of token, separators, and quoted-string".
TEXT = <any OCTET except CTLs, but including LWS>
Args:
value: HTTP header field value.
key: HTTP header field name.
Ret... | def Validate(self, value, key=None):
| if isinstance(value, unicode):
try:
value = value.encode('ascii')
except UnicodeEncodeError:
raise appinfo_errors.InvalidHttpHeaderValue('HTTP header values must not contain non-ASCII data')
key = key.lower()
printable = set(string.printable[:(-5)... |
'Gets a header value.
Args:
header_name: HTTP header name to look for.
Returns:
A header value that corresponds to header_name. If more than one such
value is in self, one of the values is selected arbitrarily, and
returned. The selection is not deterministic.'
| def Get(self, header_name):
| for name in self:
if (name.lower() == header_name.lower()):
return self[name]
|
'Get handler for mapping.
Returns:
Value of the handler (determined by handler id attribute).'
| def GetHandler(self):
| return getattr(self, self.GetHandlerType())
|
'Get handler type of mapping.
Returns:
Handler type determined by which handler id attribute is set.
Raises:
UnknownHandlerType: when none of the no handler id attributes are set.
UnexpectedHandlerAttribute: when an unexpected attribute is set for the
discovered handler type.
HandlerTypeMissingAttribute: when the handl... | def GetHandlerType(self):
| if (getattr(self, HANDLER_API_ENDPOINT) is not None):
mapping_type = HANDLER_API_ENDPOINT
else:
for id_field in URLMap.ALLOWED_FIELDS.iterkeys():
if (getattr(self, id_field) is not None):
mapping_type = id_field
break
else:
raise ap... |
'Adds additional checking to make sure handler has correct fields.
In addition to normal ValidatedCheck calls GetHandlerType
which validates all the handler fields are configured
properly.
Raises:
UnknownHandlerType: when none of the no handler id attributes are set.
UnexpectedHandlerAttribute: when an unexpected attri... | def CheckInitialized(self):
| super(URLMap, self).CheckInitialized()
if (self.GetHandlerType() in (STATIC_DIR, STATIC_FILES)):
self.AssertUniqueContentType()
|
'Makes sure that self.http_headers is consistent with self.mime_type.
Assumes self is a static handler i.e. either self.static_dir or
self.static_files is set (to not None).
Raises:
appinfo_errors.ContentTypeSpecifiedMultipleTimes: Raised when
self.http_headers contains a Content-Type header, and self.mime_type is
set.... | def AssertUniqueContentType(self):
| used_both_fields = (self.mime_type and self.http_headers)
if (not used_both_fields):
return
content_type = self.http_headers.Get('Content-Type')
if (content_type is not None):
raise appinfo_errors.ContentTypeSpecifiedMultipleTimes(('http_header specified a Content-Type header... |
'Force omitted \'secure: ...\' handler fields to \'secure: optional\'.
The effect is that handler.secure is never equal to the (nominal)
default.
See http://b/issue?id=2073962.'
| def FixSecureDefaults(self):
| if (self.secure == SECURE_DEFAULT):
self.secure = SECURE_HTTP_OR_HTTPS
|
'Generates a warning for reserved URLs.
See:
https://developers.google.com/appengine/docs/python/config/appconfig#Reserved_URLs'
| def WarnReservedURLs(self):
| if (self.url == '/form'):
logging.warning('The URL path "/form" is reserved and will not be matched.')
|
'Raises an error if position is specified outside of AppInclude objects.'
| def ErrorOnPositionForAppInfo(self):
| if self.position:
raise appinfo_errors.PositionUsedInAppYamlHandler('The position attribute was specified for this handler, but this is an app.yaml file. Position attribute is only valid for include.yaml files.')
|
'Return the result of merging two AdminConsole objects.'
| @classmethod
def Merge(cls, adminconsole_one, adminconsole_two):
| if ((not adminconsole_one) or (not adminconsole_two)):
return (adminconsole_one or adminconsole_two)
if adminconsole_one.pages:
if adminconsole_two.pages:
adminconsole_one.pages.extend(adminconsole_two.pages)
else:
adminconsole_one.pages = adminconsole_two.pages
retur... |
'Ensure that all BuiltinHandler objects at least have attribute \'default\'.'
| def __init__(self, **attributes):
| self.builtin_name = ''
super(BuiltinHandler, self).__init__(**attributes)
|
'Permit ATTRIBUTES.iteritems() to return set of items that have values.
Whenever validate calls iteritems(), it is always called on ATTRIBUTES,
not on __dict__, so this override is important to ensure that functions
such as ToYAML() return the correct set of keys.'
| def __setattr__(self, key, value):
| if (key == 'builtin_name'):
object.__setattr__(self, key, value)
elif (not self.builtin_name):
self.ATTRIBUTES[key] = ''
self.builtin_name = key
super(BuiltinHandler, self).__setattr__(key, value)
else:
raise appinfo_errors.MultipleBuiltinsSpecified('More than o... |
'Convert BuiltinHander object to a dictionary.
Returns:
dictionary of the form: {builtin_handler_name: on/off}'
| def ToDict(self):
| return {self.builtin_name: getattr(self, self.builtin_name)}
|
'Find if a builtin is defined in a given list of builtin handler objects.
Args:
builtins_list: list of BuiltinHandler objects (typically yaml.builtins)
builtin_name: name of builtin to find whether or not it is defined
Returns:
true if builtin_name is defined by a member of builtins_list,
false otherwise'
| @classmethod
def IsDefined(cls, builtins_list, builtin_name):
| for b in builtins_list:
if (b.builtin_name == builtin_name):
return True
return False
|
'Converts a list of BuiltinHandler objects to a list of (name, status).'
| @classmethod
def ListToTuples(cls, builtins_list):
| return [(b.builtin_name, getattr(b, b.builtin_name)) for b in builtins_list]
|
'Verify that all BuiltinHandler objects are valid and not repeated.
Args:
builtins_list: list of BuiltinHandler objects to validate.
runtime: if set then warnings are generated for builtins that have been
deprecated in the given runtime.
Raises:
InvalidBuiltinFormat if the name of a Builtinhandler object
cannot be dete... | @classmethod
def Validate(cls, builtins_list, runtime=None):
| seen = set()
for b in builtins_list:
if (not b.builtin_name):
raise appinfo_errors.InvalidBuiltinFormat(('Name of builtin for list object %s could not be determined.' % b))
if (b.builtin_name in seen):
raise appinfo_errors.DuplicateBuiltinsSp... |
'Raises if the library configuration is not valid.'
| def CheckInitialized(self):
| super(Library, self).CheckInitialized()
if (self.name not in _NAME_TO_SUPPORTED_LIBRARY):
raise appinfo_errors.InvalidLibraryName(('the library "%s" is not supported' % self.name))
supported_library = _NAME_TO_SUPPORTED_LIBRARY[self.name]
if (self.version != 'latest'):
if ... |
'Takes the greater of <manual_scaling.instances> from the args.
Note that appinclude_one is mutated to be the merged result in this process.
Also, this function needs to be updated if ManualScaling gets additional
fields.
Args:
appinclude_one: object one to merge. Must have a "manual_scaling" field
which contains a Man... | @classmethod
def MergeManualScaling(cls, appinclude_one, appinclude_two):
| def _Instances(appinclude):
if appinclude.manual_scaling:
if appinclude.manual_scaling.instances:
return int(appinclude.manual_scaling.instances)
return None
instances = max(_Instances(appinclude_one), _Instances(appinclude_two))
if (instances is not None):
... |
'This function merges an app.yaml file with referenced builtins/includes.'
| @classmethod
def MergeAppYamlAppInclude(cls, appyaml, appinclude):
| if (not appinclude):
return appyaml
if appinclude.handlers:
tail = (appyaml.handlers or [])
appyaml.handlers = []
for h in appinclude.handlers:
if ((not h.position) or (h.position == 'head')):
appyaml.handlers.append(h)
else:
... |
'This function merges the non-referential state of the provided AppInclude
objects. That is, builtins and includes directives are not preserved, but
any static objects are copied into an aggregate AppInclude object that
preserves the directives of both provided AppInclude objects.
Note that appinclude_one is mutated t... | @classmethod
def MergeAppIncludes(cls, appinclude_one, appinclude_two):
| if ((not appinclude_one) or (not appinclude_two)):
return (appinclude_one or appinclude_two)
if appinclude_one.handlers:
if appinclude_two.handlers:
appinclude_one.handlers.extend(appinclude_two.handlers)
else:
appinclude_one.handlers = appinclude_two.handlers
appincl... |
'Performs non-regex-based validation.
The following are verified:
- At least one url mapping is provided in the URL mappers.
- Number of url mappers doesn\'t exceed MAX_URL_MAPS.
- Major version does not contain the string -dot-.
- If api_endpoints are defined, an api_config stanza must be defined.
- If the runtime is ... | def CheckInitialized(self):
| super(AppInfoExternal, self).CheckInitialized()
if ((not self.handlers) and (not self.builtins) and (not self.includes)):
raise appinfo_errors.MissingURLMapping('No URLMap entries found in application configuration')
if (self.handlers and (len(self.handlers) > MAX_URL_MAPS)):
... |
'Returns a list of all Library instances active for this configuration.
Returns:
The list of active Library instances for this configuration. This includes
directly-specified libraries as well as any required dependencies.'
| def GetAllLibraries(self):
| if (not self.libraries):
return []
library_names = set((library.name for library in self.libraries))
required_libraries = []
for library in self.libraries:
for (required_name, required_version) in REQUIRED_LIBRARIES.get((library.name, library.version), []):
if (required_name ... |
'Returns a list of normalized Library instances for this configuration.
Returns:
The list of active Library instances for this configuration. This includes
directly-specified libraries, their required dependencies as well as any
libraries enabled by default. Any libraries with "latest" as their version
will be replaced... | def GetNormalizedLibraries(self):
| libraries = self.GetAllLibraries()
enabled_libraries = set((library.name for library in libraries))
for library in _SUPPORTED_LIBRARIES:
if (library.default_version and (library.name not in enabled_libraries)):
libraries.append(Library(name=library.name, version=library.default_version))... |
'Applies settings from the indicated backend to the AppInfoExternal.
Backend entries may contain directives that modify other parts of the
app.yaml, such as the \'start\' directive, which adds a handler for the start
request. This method performs those modifications.
Args:
backend_name: The name of a backend defined i... | def ApplyBackendSettings(self, backend_name):
| if (backend_name is None):
return
if (self.backends is None):
raise appinfo_errors.BackendNotFound
self.version = backend_name
match = None
for backend in self.backends:
if (backend.name != backend_name):
continue
if match:
raise appinfo_errors... |
'Creates a new AppControllerClient.
Args:
host: The location where an AppController can be found.
secret: A str containing the secret key, used to authenticate this client
when talking to remote AppControllers.'
| def __init__(self, host, secret):
| if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context
self.host = host
self.server = SOAPpy.SOAPProxy('https://{0}:{1}'.format(host, self.PORT))
self.secret = secret
|
'Runs the given function, retrying it if a transient error is seen.
Args:
retries: The number of times to retry.
function: The function that should be executed.
*args: The arguments that will be passed to function.
Returns:
The return value of function(*args).
Raises:
AppControllerException: If the AppController we\'re... | def call(self, retries, function, *args):
| if (retries <= 0):
raise AppControllerException('Ran out of retries calling the AppController. ')
try:
result = function(*args)
if (result == self.BAD_SECRET_MESSAGE):
raise AppControllerException(('Could not authenticate successfully' + ' to ... |
'Passes the given parameters to an AppController, allowing it to start
configuring API services in this AppScale deployment.
Args:
layout: A list that contains the first node\'s IP address.
options: A list that contains API service-level configuration info,
as well as a mapping of IPs to the API services they should ho... | def set_parameters(self, layout, options, app=None):
| if (app is None):
app = 'none'
result = self.call(self.MAX_RETRIES, self.server.set_parameters, layout, options, [app], self.secret)
if result.startswith('Error'):
raise AppControllerException(result)
|
'Queries the AppController for a list of all the machines running in this
AppScale deployment, and returns their public IP addresses.
Returns:
A list of the public IP addresses of each machine in this AppScale
deployment.'
| def get_all_public_ips(self):
| return json.loads(self.call(self.MAX_RETRIES, self.server.get_all_public_ips, self.secret))
|
'Queries the AppController to determine what each node in the deployment
is doing and how it can be externally or internally reached.
Returns:
A dict that contains the public IP address, private IP address, and a list
of the API services that each node runs in this AppScale deployment.'
| def get_role_info(self):
| return json.loads(self.call(self.MAX_RETRIES, self.server.get_role_info, self.secret))
|
'Queries the AppController to see what database is being used to implement
support for the Google App Engine Datastore API, and how many replicas are
present for each piece of data.
Returns:
A dict that indicates both the name of the database in use (with the key
\'table\', for historical reasons) and the replication f... | def get_database_information(self):
| return json.loads(self.call(self.MAX_RETRIES, self.server.get_database_information, self.secret))
|
'Asks the AppController to start serving traffic for the named application
on the given ports, instead of the ports that it was previously serving at.
Args:
appid: A str that names the already deployed application that we want to
move to a different port.
http_port: An int between 80 and 90, or between 1024 and 65535, ... | def relocate_app(self, appid, http_port, https_port):
| res = self.call(self.MAX_RETRIES, self.server.relocate_app, appid, http_port, https_port, self.secret)
return res
|
'Tells the AppController to use the AppScale Tools to upload the Google
App Engine application at the specified location.
Args:
filename: A str that points to a compressed file on the local filesystem
containing the user\'s Google App Engine application.
file_suffix: A str that names the suffix this file should have.
e... | def upload_app(self, filename, file_suffix, email):
| return json.loads(self.call(self.MAX_RETRIES, self.server.upload_app, filename, file_suffix, email, self.secret))
|
'Queries the AppController to see if the App Engine app corresponding to
the given reservation ID has been successfully uploaded.
Args:
reservation_id: A str that corresponds to the App Engine app being
uploaded, likely given to the caller from the initial upload SOAP call.
Returns:
A str with the status of the applica... | def get_app_upload_status(self, reservation_id):
| return self.call(self.MAX_RETRIES, self.server.get_app_upload_status, reservation_id, self.secret)
|
'Queries the AppController to get request statistics for a given
application.
Args:
app_id: A String that indicates which application id we are querying for.
Returns:
A list of dicts, where each dict contains the average request rate,
timestamp, and total requests seen for the given application.'
| def get_request_info(self, app_id):
| return yaml.safe_load(self.call(self.MAX_RETRIES, self.server.get_request_info, app_id, self.secret))
|
'Queries the AppController to get server-level statistics and a list of
App Engine apps running in this cloud deployment across all machines.
Returns:
A list of dicts, where each dict contains information about the
AppServer processes hosting App Engine apps.'
| def get_instance_info(self):
| return yaml.safe_load(self.call(self.MAX_RETRIES, self.server.get_instance_info, self.secret))
|
'Queries the AppController to get server-level statistics and a list of
App Engine apps running in this cloud deployment across all machines.
Returns:
A list of dicts, where each dict contains server-level statistics (e.g.,
CPU, memory, disk usage) about one machine.'
| def get_cluster_stats(self):
| return yaml.safe_load(self.call(self.MAX_RETRIES, self.server.get_cluster_stats_json, self.secret))
|
'Queries the AppController to get application cron info (from cron.yaml and /etc/cron.d/).
Returns:
A dict that contains the cron.yaml and /etc/cron.d/appscale-#app_id files content'
| def get_application_cron_info(self, app_id):
| return json.loads(self.call(self.MAX_RETRIES, self.server.get_application_cron_info, app_id, self.secret))
|
'Queries the AppController to see if it has started up all of the API
services it is responsible for on its machine.
Returns:
A bool that indicates if all API services have finished starting up on
this machine.'
| def is_initialized(self):
| return self.call(self.MAX_RETRIES, self.server.is_done_initializing, self.secret)
|
'Dynamically adds the given machines to an AppScale deployment, with the
specified roles.
Args:
A JSON-dumped dict that maps roles to IP addresses.
Returns:
The result of executing the SOAP call on the remote AppController.'
| def start_roles_on_nodes(self, roles_to_nodes):
| return self.call(self.MAX_RETRIES, self.server.start_roles_on_nodes, roles_to_nodes, self.secret)
|
'Tells the AppController to no longer host the named application.
Args:
app_id: A str that indicates which application should be stopped.
Returns:
The result of telling the AppController to no longer host the app.'
| def stop_app(self, app_id):
| return self.call(self.MAX_RETRIES, self.server.stop_app, app_id, self.secret)
|
'Tells the AppController which applications to run, which we assume have
already been uploaded to that machine.
Args:
apps_to_run: A list of apps to start running on nodes running the App
Engine service.'
| def update(self, apps_to_run):
| return self.call(self.MAX_RETRIES, self.server.update, apps_to_run, self.secret)
|
'Tells the AppController to copy logs from all machines to a tar.gz file
stored in the AppDashboard\'s static file directory, so that users can
download it.'
| def gather_logs(self):
| return self.call(self.MAX_RETRIES, self.server.gather_logs, self.secret)
|
'Tells the AppController to clean up entities in the Datastore that have
been soft deleted, and to generate statistics about the entities still in
the Datastore (which can be viewed in the AppDashboard).'
| def run_groomer(self):
| return self.call(self.MAX_RETRIES, self.server.run_groomer, self.secret)
|
'Tells the AppController to begin routing traffic to an AppServer.
Args:
app_id: A string that contains the application ID.
appserver_ip: A string that contains the IP address of the instance
running the AppServer.
port: A string that contains the port that the AppServer listens on.'
| def add_routing_for_appserver(self, app_id, appserver_ip, port):
| return self.call(self.MAX_RETRIES, self.server.add_routing_for_appserver, app_id, appserver_ip, port, self.secret)
|
'Tells the AppController to begin routing traffic to the
BlobServer(s).'
| def add_routing_for_blob_server(self):
| return self.call(self.MAX_RETRIES, self.server.add_routing_for_blob_server, self.secret)
|
'Asks the AppController if the deployment ID is stored in ZooKeeper.
Returns:
A boolean indicating whether the deployment ID is stored or not.'
| def deployment_id_exists(self):
| return self.call(self.MAX_RETRIES, self.server.deployment_id_exists, self.secret)
|
'Retrieves the deployment ID from ZooKeeper.
Returns:
A string containing the deployment ID.'
| def get_deployment_id(self):
| return self.call(self.MAX_RETRIES, self.server.get_deployment_id, self.secret)
|
'Enables or disables datastore writes for the deployment.
Args:
read_only: A string that indicates whether or to turn read-only mode on
or off.'
| def set_read_only(self, read_only):
| return self.call(self.MAX_RETRIES, self.server.set_read_only, read_only, self.secret)
|
'Queries the AppController for a dictionary of its instance variables
whose names match the given regular expression, along with their associated
values.
Args:
property_regex: A str that names a regex of instance variables whose
values should be retrieved from the AppController.
Returns:
A dict mapping each instance va... | def get_property(self, property_regex):
| return json.loads(self.call(self.MAX_RETRIES, self.server.get_property, property_regex, self.secret))
|
'Retrieves a dictionary of information for each application.
Returns:
A dictionary of information for each application.
Raises:
AppControllerException if unable to retrieve information.'
| def get_app_info_map(self):
| response = self.call(self.MAX_RETRIES, self.server.get_app_info_map, self.secret)
try:
return json.loads(response)
except ValueError:
raise AppControllerException(response)
|
'Initialization for builder handler.
Args:
builder: Instance of Builder class.
Raises:
ListenerConfigurationError when builder is not a Builder class.'
| def __init__(self, builder):
| if (not isinstance(builder, Builder)):
raise yaml_errors.ListenerConfigurationError('Must provide builder of type yaml_listener.Builder')
self._builder = builder
self._stack = None
self._top = None
self._results = []
|
'Push values to stack at start of nesting.
When a new object scope is beginning, will push the token (type of scope)
along with the new objects value, the latter of which is provided through
the various build methods of the builder.
Args:
token: Token indicating the type of scope which is being created; must
belong to ... | def _Push(self, token, value):
| self._top = (token, value)
self._stack.append(self._top)
|
'Pop values from stack at end of nesting.
Called to indicate the end of a nested scope.
Returns:
Previously pushed value at the top of the stack.'
| def _Pop(self):
| assert ((self._stack != []) and (self._stack is not None))
(token, value) = self._stack.pop()
if self._stack:
self._top = self._stack[(-1)]
else:
self._top = None
return value
|
'Handle anchor attached to event.
Currently will raise an error if anchor is used. Anchors are used to
define a document wide tag to a given value (scalar, mapping or sequence).
Args:
event: Event which may have anchor property set.
Raises:
NotImplementedError if event attempts to use an anchor.'
| def _HandleAnchor(self, event):
| if (hasattr(event, 'anchor') and (event.anchor is not None)):
raise NotImplementedError('Anchors not supported in this handler')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.