desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Sets the number of instances to run for a version of a module. Args: module_name: A str containing the name of the module. version: A str containing the version. num_instances: An int containing the number of instances to run. Raises: ModuleDoesNotExistError: The module does not exist. VersionDoesNotExistError: The ve...
def set_num_instances(self, module_name, version, num_instances):
self._get_module(module_name, version).set_num_instances(num_instances)
'Returns the number of instances running for a version of a module. Returns: An int containing the number of instances running for a module version. Args: module_name: A str containing the name of the module. version: A str containing the version. Raises: ModuleDoesNotExistError: The module does not exist. VersionDoesN...
def get_num_instances(self, module_name, version):
return self._get_module(module_name, version).get_num_instances()
'Starts a module. Args: module_name: A str containing the name of the module. version: A str containing the version. Raises: ModuleDoesNotExistError: The module does not exist. VersionDoesNotExistError: The version does not exist. NotSupportedWithAutoScalingError: The provided module/version uses automatic scaling.'
def start_module(self, module_name, version):
self._get_module(module_name, version).resume()
'Stops a module. Args: module_name: A str containing the name of the module. version: A str containing the version. Raises: ModuleDoesNotExistError: The module does not exist. VersionDoesNotExistError: The version does not exist. NotSupportedWithAutoScalingError: The provided module/version uses automatic scaling.'
def stop_module(self, module_name, version):
self._get_module(module_name, version).suspend()
'Dispatch a background thread request. Args: module_name: A str containing the module name to service this request. version: A str containing the version to service this request. inst: The instance to service this request. background_request_id: A str containing the unique background thread request identifier. Raises: ...
def send_background_request(self, module_name, version, inst, background_request_id):
_module = self._get_module(module_name, version) try: inst.reserve_background_thread() except instance.CannotAcceptRequests: raise request_info.BackgroundThreadLimitReachedError() port = _module.get_instance_port(inst.instance_id) environ = _module.build_request_environ('GET', '/_ah/...
'Dispatch an HTTP request asynchronously. Args: method: A str containing the HTTP method of the request. relative_url: A str containing path and query string of the request. headers: A list of (key, value) tuples where key and value are both str. body: A str containing the request body. source_ip: The source ip address...
def add_async_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None):
if module_name: _module = self._get_module(module_name, version) else: _module = self._module_for_request(urlparse.urlsplit(relative_url).path) inst = (_module.get_instance(instance_id) if instance_id else None) port = (_module.get_instance_port(instance_id) if instance_id else _module.b...
'Process an HTTP request. Args: method: A str containing the HTTP method of the request. relative_url: A str containing path and query string of the request. headers: A list of (key, value) tuples where key and value are both str. body: A str containing the request body. source_ip: The source ip address for the request...
def add_request(self, method, relative_url, headers, body, source_ip, module_name=None, version=None, instance_id=None, fake_login=False):
if module_name: _module = self._get_module(module_name, version) inst = (_module.get_instance(instance_id) if instance_id else None) else: headers_dict = wsgiref.headers.Headers(headers) (_module, inst) = self._resolve_target(headers_dict['Host'], urlparse.urlsplit(relative_url)....
'Returns the module and instance that should handle this request. Args: hostname: A string containing the value of the host header in the request or None if one was not present. path: A string containing the path of the request. Returns: A tuple (_module, inst) where: _module: The module.Module that should handle this ...
def _resolve_target(self, hostname, path):
if (self._port == 80): default_address = self.host else: default_address = ('%s:%s' % (self.host, self._port)) if ((not hostname) or (hostname == default_address)): return (self._module_for_request(path), None) default_address_offset = hostname.find(default_address) if (defau...
'Dispatch a WSGI request. Args: environ: An environ dict for the request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. _module: The module to dispatch this request to. inst: The instance to service this request. If None, the module will be left to choose the instance to serve this...
def _handle_request(self, environ, start_response, _module, inst=None, request_type=instance.NORMAL_REQUEST, catch_and_log_exceptions=False):
try: return _module._handle_request(environ, start_response, inst=inst, request_type=request_type) except: if catch_and_log_exceptions: logging.exception('Internal error while handling request.') else: raise
'Acts like imp.find_module with support for path hooks. Args: submodule_name: The name of the submodule within its parent package. fullname: The full name of the module to load. path: A list containing the paths to search for the module. Returns: A tuple (source_file, path_name, description, loader) where: source_file:...
def _find_module_or_loader(self, submodule_name, fullname, path):
for path_entry in ((path + [None]) + [LXML_PATH]): result = self._find_path_hook(submodule_name, fullname, path_entry) if (result is not None): break else: raise ImportError(('No module named %s' % fullname)) if isinstance(result, tuple): return (result +...
'Finds and loads a module, using a provided search path. Args: submodule_name: The name of the submodule within its parent package. fullname: The full name of the module to load. path: A list containing the paths to search for the module. Returns: The requested module. Raises: ImportError: The module could not be impor...
def _find_and_load_module(self, submodule_name, fullname, path):
(source_file, path_name, description, loader) = self._find_module_or_loader(submodule_name, fullname, path) if loader: return loader.load_module(fullname) try: return imp.load_module(fullname, source_file, path_name, description) finally: if source_file: source_file.c...
'Helper for _find_and_load_module to find a module in a path entry. Args: submodule: The last portion of the module name from submodule_fullname. submodule_fullname: The full name of the module to be imported. path_entry: A single sys.path entry, or None representing the builtins. Returns: None if nothing was found, a ...
def _find_path_hook(self, submodule, submodule_fullname, path_entry):
if (path_entry is None): if (submodule_fullname in sys.builtin_module_names): try: result = imp.find_module(submodule) except ImportError: pass else: (_, _, description) = result (_, _, file_type) = descripti...
'Retrieves the parent package of a fully qualified module name. Args: fullname: Full name of the module whose parent should be retrieved (e.g., foo.bar). Returns: Module instance for the parent or None if there is no parent module. Raises: ImportError: The module\'s parent could not be found.'
def _get_parent_package(self, fullname):
all_modules = fullname.split('.') parent_module_fullname = '.'.join(all_modules[:(-1)]) if parent_module_fullname: __import__(parent_module_fullname) return sys.modules[parent_module_fullname] return None
'Determines the search path of a module\'s parent package. Args: fullname: Full name of the module to look up (e.g., foo.bar). Returns: Tuple (submodule, search_path) where: submodule: The last portion of the module name from fullname (e.g., if fullname is foo.bar, then this is bar). search_path: List of paths that bel...
def _get_parent_search_path(self, fullname):
(_, _, submodule) = fullname.rpartition('.') parent_package = self._get_parent_package(fullname) search_path = sys.path if ((parent_package is not None) and hasattr(parent_package, '__path__')): search_path = parent_package.__path__ return (submodule, search_path)
'Determines the path on disk and the search path of a module or package. Args: fullname: Full name of the module to look up (e.g., foo.bar). Returns: Tuple (pathname, search_path, submodule, loader) where: pathname: String containing the full path of the module on disk, or None if the module wasn\'t loaded from disk (e...
def _get_module_info(self, fullname):
(submodule, search_path) = self._get_parent_search_path(fullname) (_, pathname, description, loader) = self._find_module_or_loader(submodule, fullname, search_path) if loader: return (None, None, None, loader) else: (_, _, file_type) = description module_search_path = None ...
'Returns whether the module specified by fullname refers to a package. This implements part of the extensions to the PEP 302 importer protocol. Args: fullname: The fullname of the module. Returns: True if fullname refers to a package.'
def is_package(self, fullname):
(submodule, search_path) = self._get_parent_search_path(fullname) (_, _, description, loader) = self._find_module_or_loader(submodule, fullname, search_path) if loader: return loader.is_package(fullname) (_, _, file_type) = description if (file_type == imp.PKG_DIRECTORY): return True...
'Returns the source for the module specified by fullname. This implements part of the extensions to the PEP 302 importer protocol. Args: fullname: The fullname of the module. Returns: The source for the module.'
def get_source(self, fullname):
(full_path, _, _, loader) = self._get_module_info(fullname) if loader: return loader.get_source(fullname) if (full_path is None): return None source_file = open(full_path) try: return source_file.read() finally: source_file.close()
'Returns the code object for the module specified by fullname. This implements part of the extensions to the PEP 302 importer protocol. Args: fullname: The fullname of the module. Returns: The code object associated the module.'
def get_code(self, fullname):
(full_path, _, _, loader) = self._get_module_info(fullname) if loader: return loader.get_code(fullname) if (full_path is None): return None source_file = open(full_path) try: source_code = source_file.read() finally: source_file.close() encoding = DEFAULT_ENCO...
'Returns the directory containing the module or None if not found.'
def _get_module_path(self, fullname):
try: (_, _, submodule) = fullname.rpartition('.') (f, filepath, _, loader) = self._find_module_or_loader(submodule, fullname, sys.path) except ImportError: return None if f: f.close() if loader: return loader.find_module(fullname) return os.path.dirname(filepa...
'Apply this policy to the provided module dict. In order, one of the following will apply: - Symbols in overrides are set to the override value. - Symbols in deletes are removed. - Whitelisted symbols and symbols with a constant type are unchanged. - If a default stub is set, all other symbols are replaced by it. - If ...
def apply_policy(self, module_dict):
for symbol in module_dict.keys(): if (symbol in self.overrides): module_dict[symbol] = self.overrides[symbol] elif (symbol in self.deletes): del module_dict[symbol] elif (not ((symbol in self.whitelist) or isinstance(module_dict[symbol], self.constant_types) or (symbo...
'Import the stub module replacement for the specified module.'
def import_stub_module(self, name):
providing_dist = dist if (name in dist27.__all__): providing_dist = dist27 fullname = ('%s.%s' % (providing_dist.__name__, name)) __import__(fullname, {}, {}) module = imp.new_module(fullname) module.__dict__.update(sys.modules[fullname].__dict__) module.__loader__ = self module....
'Returns a dict containing the environ to pass to the user\'s application. Args: environ: A dict containing the request WSGI environ. Returns: A dict containing the environ representing an HTTP request.'
def get_user_environ(self, environ):
user_environ = self.environ_template.copy() self.copy_headers(environ, user_environ) user_environ['REQUEST_METHOD'] = environ.get('REQUEST_METHOD', 'GET') content_type = environ.get('CONTENT_TYPE') if content_type: user_environ['HTTP_CONTENT_TYPE'] = content_type content_length = environ...
'Copy headers from source_environ to dest_environ. This extracts headers that represent environ values and propagates all other headers which are not used for internal implementation details or headers that are stripped. Args: source_environ: The source environ dict. dest_environ: The environ dict to populate.'
def copy_headers(self, source_environ, dest_environ):
for env in http_runtime_constants.ENVIRONS_TO_PROPAGATE: value = source_environ.get((http_runtime_constants.INTERNAL_ENVIRON_PREFIX + env), None) if (value is not None): dest_environ[env] = value for (name, value) in source_environ.items(): if (name.startswith('HTTP_') and (n...
'Flushes logs using the LogService API. Args: logs: A list of tuples (timestamp_usec, level, message).'
def _flush_logs(self, logs):
logs_group = log_service_pb.UserAppLogGroup() for (timestamp_usec, level, message) in logs: log_line = logs_group.add_log_line() log_line.set_timestamp_usec(timestamp_usec) log_line.set_level(level) log_line.set_message(message) request = log_service_pb.FlushRequest() req...
'Configures which paths are allowed to be accessed. Must be called at least once before any file objects are created in the hardened environment. Args: root_path: Absolute path to the root of the application. application_paths: List of additional paths that the application may access, this must include the App Engine r...
@staticmethod def set_allowed_paths(root_path, application_paths):
_application_paths = (set((os.path.realpath(path) for path in application_paths)) | set((os.path.abspath(path) for path in application_paths))) FakeFile._root_path = os.path.normcase(os.path.abspath(root_path)) _application_paths.add(FakeFile._root_path) FakeFile._allowed_dirs = (_application_paths | Fa...
'Configure the skip_files regex. Files that match this regex are inaccessible in the hardened environment. Must be called at least once before any file objects are created in the hardened environment. Args: skip_files: A str containing a regex to match against file paths.'
@staticmethod def set_skip_files(skip_files):
FakeFile._skip_files = re.compile(skip_files) with FakeFile._availability_cache_lock: FakeFile._availability_cache = {}
'Configure the static_files regex. Files that match this regex are inaccessible in the hardened environment. Must be called at least once before any file objects are created in the hardened environment. Args: static_files: A str containing a regex to match against file paths.'
@staticmethod def set_static_files(static_files):
FakeFile._static_files = re.compile(static_files) with FakeFile._availability_cache_lock: FakeFile._availability_cache = {}
'Determines if a file is accessible. set_allowed_paths(), set_skip_files() and SetStaticFileConfigMatcher() must be called before this method or else all file accesses will raise an error. Args: filename: Path of the file to check (relative or absolute). May be a directory, in which case access for files inside that di...
@staticmethod def is_file_accessible(filename):
if (not isinstance(filename, basestring)): raise TypeError() fixed_filename = os.path.normcase(os.path.abspath(filename)) with FakeFile._availability_cache_lock: result = FakeFile._availability_cache.get(fixed_filename) if (result is None): if (_is_path_in_directories(fixed_filen...
'Initializer. See file built-in documentation.'
def __init__(self, filename, mode='r', bufsize=(-1), **kwargs):
if (mode not in FakeFile.ALLOWED_MODES): raise IOError(errno.EROFS, 'Read-only file system', filename) if (not FakeFile.is_file_accessible(filename)): raise IOError(errno.EACCES, 'file not accessible', filename) super(FakeFile, self).__init__(filename, mode, bufsize, **kwargs)
'Initializer. Args: original_func: Callable that takes as its first argument the path to a file or directory on disk; all subsequent arguments may be variable.'
def __init__(self, original_func):
self._original_func = original_func functools.update_wrapper(self, original_func)
'Enforces access permissions for the wrapped function.'
def __call__(self, path, *args, **kwargs):
if (not FakeFile.is_file_accessible(path)): raise OSError(errno.EACCES, 'path not accessible', path) return self._original_func(path, *args, **kwargs)
'Records the start of a user-created thread as part of this request.'
def start_thread(self):
thread_id = threading.current_thread().ident with self._condition: self._threads.add(thread_id)
'Records the end of a user-created thread as part of this request.'
def end_thread(self):
thread_id = threading.current_thread().ident with self._condition: self._threads.remove(thread_id) self._condition.notify()
'Ends the request and blocks until all threads for this request finish.'
def end_request(self):
thread_id = threading.current_thread().ident with self._condition: self._threads.remove(thread_id) while self._threads: self._condition.wait()
'Injects an exception to all threads running as part of this request.'
def inject_exception(self, exception):
with self._condition: thread_ids = list(self._threads) for thread_id in thread_ids: ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id), ctypes.py_object(exception))
'Merge the response stream and the values returned by the WSGI app.'
def merged_response(self, response):
return (self.response_stream.getvalue() + ''.join(response))
'Serves a request by displaying an error page. Args: environ: An environ dict for the request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. url_map: An appinfo.URLMap instance containing the configuration for the handler matching this request. match: A re.MatchObject containing th...
def handle(self, environ, start_response, url_map, match, request_id, request_type):
start_response('500 Internal Server Error', [('Content-Type', 'text/plain; charset=utf-8')]) (yield 'The Go application could not be built.\n') (yield '\n') (yield str(self._failure_exception))
'Initializer for GoRuntimeInstanceFactory. Args: request_data: A wsgi_request_info.WSGIRequestInfo that will be provided with request information for use by API stubs. runtime_config_getter: A function that can be called without arguments and returns the runtime_config_pb2.RuntimeConfig containing the configuration for...
def __init__(self, request_data, runtime_config_getter, module_configuration):
super(GoRuntimeInstanceFactory, self).__init__(request_data, 8, 10) self._runtime_config_getter = runtime_config_getter self._module_configuration = module_configuration self._application_lock = threading.Lock() self._go_application = go_application.GoApplication(self._module_configuration) self...
'Returns a list of directories changes in which should trigger a restart. Returns: A list of src directory paths in the GOPATH. Changes (i.e. files added, deleted or modified) in these directories will trigger a restart of all instances created with this factory.'
def get_restart_directories(self):
try: go_path = os.environ['GOPATH'] except KeyError: return [] else: if sys.platform.startswith('win32'): roots = go_path.split(';') else: roots = go_path.split(':') dirs = [os.path.join(r, 'src') for r in roots] return [d for d in dirs...
'Called when a file relevant to the factory *might* have changed.'
def files_changed(self):
with self._application_lock: self._modified_since_last_build = True
'Called when the configuration of the module has changed. Args: config_changes: A set containing the changes that occured. See the *_CHANGED constants in the application_configuration module.'
def configuration_changed(self, config_changes):
if (config_changes & _REBUILD_CONFIG_CHANGES): with self._application_lock: self._modified_since_last_build = True
'Create and return a new Instance. Args: instance_id: A string or integer representing the unique (per module) id of the instance. expect_ready_request: If True then the instance will be sent a special request (i.e. /_ah/warmup or /_ah/start) before it can handle external requests. Returns: The newly created instance.I...
def new_instance(self, instance_id, expect_ready_request=False):
def instance_config_getter(): runtime_config = self._runtime_config_getter() runtime_config.instance_id = str(instance_id) return runtime_config with self._application_lock: try: if self._go_application.maybe_build(self._modified_since_last_build): if ...
'Initializer for InotifyFileWatcher. Args: directory: A string representing the path to a directory that should be monitored for changes i.e. files and directories added, renamed, deleted or changed.'
def __init__(self, directory):
self._directory = os.path.abspath(directory) self._watch_to_directory = {} self._directory_to_watch_descriptor = {} self._directory_to_subdirs = {} self._inotify_events = '' self._inotify_fd = None self._inotify_poll = None
'Start watching the directory for changes.'
def start(self):
self._class_setup() self._inotify_fd = InotifyFileWatcher._libc.inotify_init() if (self._inotify_fd < 0): error = OSError('failed call to inotify_init') error.errno = ctypes.get_errno() error.strerror = errno.errorcode[ctypes.get_errno()] raise error self._inotif...
'Stop watching the directory for changes.'
def quit(self):
os.close(self._inotify_fd)
'Return paths for changed files and directories. start() must be called before this method. Returns: A set of strings representing file and directory paths that have changed since the last call to get_changed_paths.'
def _get_changed_paths(self):
paths = set() while True: if (not self._inotify_poll.poll(0)): break self._inotify_events += os.read(self._inotify_fd, 1024) while (len(self._inotify_events) > _INOTIFY_EVENT_SIZE): (wd, mask, cookie, length) = _INOTIFY_EVENT.unpack(self._inotify_events[:_INOTIFY_...
'Start the API Server.'
def start(self):
super(APIServer, self).start() logging.info('Starting API server at: http://%s:%d', self._host, self.port)
'Normalize a headers set to a list with lowercased names. Args: headers: A sequence of pairs, a dict or a wsgiref.headers.Headers object. Returns: headers, converted to a sequence of pairs (if it was not already), with all of the header names lowercased.'
@staticmethod def _normalize_headers(headers):
if (isinstance(headers, dict) or isinstance(headers, wsgiref.headers.Headers)): headers = headers.items() return [(name.lower(), value) for (name, value) in headers]
'Tests whether two sets of HTTP headers are equivalent. The header sets expected and actual are equal if they both have exactly the same set of header name/value pairs. Header names are considered case-insensitive, but header values are case sensitive. The order does not matter, but duplicate headers (headers of the sa...
def assertHeadersEqual(self, expected, actual, msg=None):
expected = self._normalize_headers(expected) actual = self._normalize_headers(actual) for (name, value) in actual: self.assertIsInstance(name, str, ('header name %r must be a str' % name)) self.assertIsInstance(name, str, ('header value %r must be a str' %...
'Calls fn(*args, <start_response>, **kwargs) and checks the result. Args: expected_status: The expected HTTP status returned e.g. \'200 OK\'. expected_headers: A dict, list or wsgiref.headers.Headers representing the expected generated HTTP headers e.g. {\'Content-type\': \'text/plain\'}. expected_content: The expected...
def assertResponse(self, expected_status, expected_headers, expected_content, fn, *args, **kwargs):
write_buffer = cStringIO.StringIO() def start_response(status, headers, exc_info=None): self.assertEqual(expected_status, status) self.assertHeadersEqual(expected_headers, headers) self.assertEqual(None, exc_info) return write_buffer.write args += (start_response,) respon...
'Tests that a rewritten application produces the expected response. This applies the response rewriter chain to application and then tests the result. Args: expected_status: The expected HTTP status returned e.g. \'200 OK\'. expected_headers: A dict, list or wsgiref.headers.Headers representing the expected generated H...
def assert_rewritten_response(self, expected_status, expected_headers, expected_body, application, environ=None):
if (environ is None): environ = {} wrapped_application = self.rewriter_middleware(application) self.assertResponse(expected_status, expected_headers, expected_body, wrapped_application, environ)
'Schedule an event to be run. Args: runnable: A callable to run. eta: An int containing when to run runnable in seconds since the epoch. key: An optional key that implements __hash__ that can be passed to update_event.'
def add_event(self, runnable, eta, key=None):
event = _Event(eta, runnable, key) with self._work_ready_condition: if (key is not None): self._key_to_events[key] = event self._enqueue_event(event)
'Modify when an event should be run. Args: eta: An int containing when to schedule the event in seconds since the epoch. key: The key of the event to modify.'
def update_event(self, eta, key):
with self._work_ready_condition: old_event = self._key_to_events.get(key) if old_event: event = old_event.copy(eta) old_event.cancel() self._key_to_events[key] = event self._enqueue_event(event)
'Create a new RewriterState. Args: environ: An environ dict for the current request as defined in PEP-333. status: A status code and message as a string. (e.g., \'200 OK\'.) headers: A list of tuples containing the response headers. body: An iterable of strings containing the response body.'
def __init__(self, environ, status, headers, body):
self.environ = environ self.status = status self.headers = wsgiref.headers.Headers(headers) self.body = body self.allow_large_response = False
'The integer value of the response status.'
@property def status_code(self):
return int(self.status.split(' ', 1)[0])
'Constructs a new Application. Args: forward_app: A WSGI application to forward successful upload requests to. get_blob_storage: Callable that returns a BlobStorage instance. The default is fine, but may be overridden for testing purposes. generate_blob_key: Function used for generating unique blob keys. now_func: Func...
def __init__(self, forward_app, get_blob_storage=_get_blob_storage, generate_blob_key=_generate_blob_key, now_func=datetime.datetime.now):
self._forward_app = forward_app self._blob_storage = get_blob_storage() self._generate_blob_key = generate_blob_key self._now_func = now_func
'Aborts the application by raising a webob.exc.HTTPException. Args: code: HTTP status code int. detail: Optional detail message str. Raises: webob.exc.HTTPException: Always.'
def abort(self, code, detail=None):
exception = webob.exc.status_map[code]() if detail: exception.detail = detail raise exception
'Store a supplied form-data item to the blobstore. The appropriate metadata is stored into the datastore. Args: content_type: The MIME content type of the uploaded file. filename: The filename of the uploaded file. md5_hash: MD5 hash of the file contents, as a hashlib hash object. blob_file: A file-like object containi...
def store_blob(self, content_type, filename, md5_hash, blob_file, creation):
blob_key = self._generate_blob_key() self._blob_storage.StoreBlob(blob_key, blob_file) blob_entity = datastore.Entity('__BlobInfo__', name=str(blob_key), namespace='') blob_entity['content_type'] = content_type blob_entity['creation'] = creation blob_entity['filename'] = filename blob_entity...
'Store a supplied form-data item to GS. Delegate all the work of gs file creation to CloudStorageStub. Args: content_type: The MIME content type of the uploaded file. gs_filename: The gs filename to create of format bucket/filename. blob_file: A file-like object containing the contents of the file. filename: user provi...
def store_gs_file(self, content_type, gs_filename, blob_file, filename):
gs_stub = cloudstorage_stub.CloudStorageStub(self._blob_storage) blobkey = gs_stub.post_start_creation(('/' + gs_filename), {'content-type': content_type}) content = blob_file.read() return gs_stub.put_continue_creation(blobkey, content, (0, (len(content) - 1)), len(content), filename)
'Preprocess data and metadata before storing them. Args: content_type: The MIME content type of the uploaded file. blob_file: A file-like object containing the contents of the file. filename: The filename of the uploaded file. base64_encoding: True, if the file contents are base-64 encoded. Returns: (content_type, blob...
def _preprocess_data(self, content_type, blob_file, filename, base64_encoding):
if base64_encoding: blob_file = cStringIO.StringIO(base64.urlsafe_b64decode(blob_file.read())) try: if (not isinstance(content_type, unicode)): content_type = content_type.decode('utf-8') if (filename and (not isinstance(filename, unicode))): filename = filename.d...
'Reads form data, stores blobs data and builds the forward request. This finds all of the file uploads in a set of form fields, converting them into blobs and storing them in the blobstore. It also generates the HTTP request to forward to the user\'s application. Args: form: cgi.FieldStorage instance representing the w...
def store_and_build_forward_message(self, form, boundary=None, max_bytes_per_blob=None, max_bytes_total=None, bucket_name=None):
message = multipart.MIMEMultipart('form-data', boundary) creation = self._now_func() total_bytes_uploaded = 0 created_blobs = [] mime_type_error = None too_many_conflicts = False upload_too_large = False filename_too_large = False content_type_too_large = False form_items = [] ...
'Stores a blob in response to a WSGI request and transforms environ. environ is modified so that it is suitable for forwarding to the user\'s application. Args: environ: An environ dict for the current request as defined in PEP-333. Raises: webob.exc.HTTPException: The upload failed.'
def store_blob_and_transform_request(self, environ):
if (environ['REQUEST_METHOD'].lower() != 'post'): self.abort(405) url_match = _UPLOAD_URL_PATTERN.match(environ['PATH_INFO']) if (not url_match): self.abort(404) upload_key = url_match.group(1) try: upload_session = datastore.Get(upload_key) except datastore_errors.Entity...
'Handles WSGI requests. Args: environ: An environ dict for the current request as defined in PEP-333. start_response: A function with semantics defined in PEP-333. Returns: An iterable over strings containing the body of the HTTP response.'
def __call__(self, environ, start_response):
try: self.store_blob_and_transform_request(environ) except webob.exc.HTTPException as e: def start_response_with_exc_info(status, headers, exc_info=sys.exc_info()): start_response(status, headers, exc_info) return e(environ, start_response_with_exc_info) return self._forw...
'Configure test harness.'
def setUp(self):
self.original_environ = dict(os.environ) os.environ.update({'APPLICATION_ID': 'app', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '8080', 'AUTH_DOMAIN': 'abcxyz.com', 'USER_EMAIL': 'user@abcxyz.com'}) self.tmpdir = tempfile.mkdtemp() storage_directory = os.path.join(self.tmpdir, 'blob_storage') self.b...
'Restore original environment.'
def tearDown(self):
os.environ = self.original_environ shutil.rmtree(self.tmpdir)
'Create a blob in the datastore and on disk. Returns: BlobKey of new blob.'
def create_blob(self):
contents = 'a blob' blob_key = blobstore.BlobKey('blob-key-1') self.blob_storage.StoreBlob(blob_key, cStringIO.StringIO(contents)) entity = datastore.Entity(blobstore.BLOB_INFO_KIND, name=str(blob_key), namespace='') entity['content_type'] = 'image/png' entity['creation'] = datetime.datetime(...
'Response is not rewritten if missing download header.'
def test_non_download_response(self):
environ = {'HTTP_RANGE': 'bytes=2-5'} headers = [(blobstore.BLOB_RANGE_HEADER, 'bytes=1-4')] state = request_rewriter.RewriterState(environ, '200 original message', headers, 'original body') blob_download.blobstore_download_rewriter(state) self.assertEqual('200 original message', stat...
'Test getting blob storage from datastore stub.'
def test_get_blob_storage(self):
blob_storage = blob_download._get_blob_storage() self.assertEquals(self.blobstore_stub.storage, blob_storage)
'Test ParseRangeHeader function.'
def test_parse_range_header(self):
self.assertEquals((None, None), blob_download._parse_range_header('')) self.assertEquals((None, None), blob_download._parse_range_header('invalid')) self.assertEquals((1, None), blob_download._parse_range_header('bytes=1-')) self.assertEquals((10, 21), blob_download._parse_range_header('bytes=10-20')) ...
'Use auto Content-Type to set the blob\'s stored mime type.'
def test_rewrite_for_download_use_stored_content_type_auto_mime(self):
self.test_rewrite_for_download_use_stored_content_type(auto_mimetype=True)
'Tests that downloads rewrite when using blob\'s original content-type.'
def test_rewrite_for_download_use_stored_content_type(self, auto_mimetype=False):
blob_key = self.create_blob() headers = [(blobstore.BLOB_KEY_HEADER, str(blob_key))] if auto_mimetype: headers.append(('Content-Type', blob_download._AUTO_MIME_TYPE)) state = request_rewriter.RewriterState({}, '200 original message', headers, 'original body') blob_download.blobstore...
'Tests that the application\'s provided Content-Type is preserved.'
def test_rewrite_for_download_preserve_user_content_type(self):
blob_key = self.create_blob() headers = [(blobstore.BLOB_KEY_HEADER, str(blob_key)), ('Content-Type', 'image/jpg')] state = request_rewriter.RewriterState({}, '200 original message', headers, 'original body') blob_download.blobstore_download_rewriter(state) self.assertEqual('200 original...
'Download requested, but status code is not 200.'
def test_rewrite_for_download_not_200(self):
blob_key = self.create_blob() headers = [(blobstore.BLOB_KEY_HEADER, str(blob_key))] state = request_rewriter.RewriterState({}, '201 original message', headers, 'original body') blob_download.blobstore_download_rewriter(state) self.assertEqual('500 Internal Server Error', state.sta...
'Tests downloading a missing blob key.'
def test_rewrite_for_download_missing_blob(self):
environ = {'HTTP_RANGE': 'bytes=2-5'} headers = [(blobstore.BLOB_KEY_HEADER, 'no such blob')] state = request_rewriter.RewriterState(environ, '200 original message', headers, 'original body') blob_download.blobstore_download_rewriter(state) self.assertEqual('500 Internal Server ...
'Tests that a missing blob deletes Content-Type and BlobRange headers.'
def test_rewrite_for_download_missing_blob_delete_headers(self):
environ = {'HTTP_RANGE': 'bytes=2-5'} headers = [(blobstore.BLOB_KEY_HEADER, 'no such blob'), (blobstore.BLOB_RANGE_HEADER, 'bytes=1-4'), ('Content-Type', 'image/jpg')] state = request_rewriter.RewriterState(environ, '200 original message', headers, 'original body') blob_download.blobstor...
'Performs a blob range response test. Args: blobrange: Value of the X-AppEngine-BlobRange response header. expected_range: Expected Content-Range. expected_body: Expected body. test_range_request: If True, tests with a Range request header instead of an X-AppEngine-BlobRange application response header. expect_unsatisf...
def do_blob_range_test(self, blobrange, expected_range, expected_body, test_range_request=False, expect_unsatisfiable=False):
blob_key = self.create_blob() environ = {} if test_range_request: environ['HTTP_RANGE'] = blobrange else: environ['HTTP_RANGE'] = 'bytes=2-5' headers = [(blobstore.BLOB_KEY_HEADER, str(blob_key)), ('Content-Type', 'image/jpg'), ('Content-Range', 'bytes 1-2/6')] if (not test_ra...
'Tests downloading range due to X-AppEngine-BlobRange response header.'
def test_download_range_blob_range_header(self):
self.do_blob_range_test('bytes=1-4', 'bytes 1-4/6', ' blo')
'Tests downloading range when BlobRange start is before the blob start.'
def test_download_range_blob_range_header_start_before_start(self):
self.do_blob_range_test('bytes=-10', 'bytes 0-5/6', 'a blob')
'Tests for error when BlobRange start is after the blob end.'
def test_download_range_blob_range_header_start_after_end(self):
self.do_blob_range_test('bytes=6-20', '*/6', '', expect_unsatisfiable=True)
'Tests downloading range when BlobRange is larger than blob.'
def test_download_range_blob_range_header_too_long(self):
self.do_blob_range_test('bytes=1-400', 'bytes 1-5/6', ' blob')
'Tests for error when BlobRange header is not parseable.'
def test_download_range_blob_range_header_not_parseable(self):
self.do_blob_range_test('bytes=xyz', '*/6', '', expect_unsatisfiable=True)
'Tests downloading range when BlobRange only provides start index.'
def test_download_range_blob_range_header_no_end(self):
self.do_blob_range_test('bytes=2-', 'bytes 2-5/6', 'blob')
'Tests downloading range when BlobRange uses a negative start index.'
def test_download_range_blob_range_header_negative_start(self):
self.do_blob_range_test('bytes=-1', 'bytes 5-5/6', 'b') self.do_blob_range_test('bytes=-2', 'bytes 4-5/6', 'ob') self.do_blob_range_test('bytes=-3', 'bytes 3-5/6', 'lob') self.do_blob_range_test('bytes=-4', 'bytes 2-5/6', 'blob') self.do_blob_range_test('bytes=-5', 'bytes 1-5/6', ' ...
'Tests downloading range when BlobRange is a single byte.'
def test_download_range_blob_range_header_single_byte(self):
self.do_blob_range_test('bytes=0-0', 'bytes 0-0/6', 'a') self.do_blob_range_test('bytes=1-1', 'bytes 1-1/6', ' ') self.do_blob_range_test('bytes=2-2', 'bytes 2-2/6', 'b') self.do_blob_range_test('bytes=3-3', 'bytes 3-3/6', 'l') self.do_blob_range_test('bytes=4-4', 'bytes 4-4/6', 'o...
'Tests that whole blob is downloaded when BlobRange is empty.'
def test_download_range_blob_range_header_empty(self):
blob_key = self.create_blob() environ = {'HTTP_RANGE': 'bytes=2-5'} headers = [(blobstore.BLOB_KEY_HEADER, str(blob_key)), (blobstore.BLOB_RANGE_HEADER, ''), ('Content-Type', 'image/jpg')] state = request_rewriter.RewriterState(environ, '200 original message', headers, 'original body') blob...
'Tests downloading range due to a Range request header.'
def test_download_range_range_header(self):
self.do_blob_range_test('bytes=1-4', 'bytes 1-4/6', ' blo', test_range_request=True)
'Tests downloading range when Range start is before the blob start.'
def test_download_range_request_range_header_start_before_start(self):
self.do_blob_range_test('bytes=-10', 'bytes 0-5/6', 'a blob', test_range_request=True)
'Tests for error when Range start is after the blob end.'
def test_download_range_request_range_header_start_after_end(self):
self.do_blob_range_test('bytes=6-20', '*/6', '', test_range_request=True, expect_unsatisfiable=True)
'Tests downloading range when Range is larger than blob.'
def test_download_range_range_header_too_long(self):
self.do_blob_range_test('bytes=1-500', 'bytes 1-5/6', ' blob', test_range_request=True)
'Tests for error when Range header is not parseable.'
def test_download_range_request_range_header_not_parsable(self):
self.do_blob_range_test('bytes=half of it', '*/6', '', test_range_request=True, expect_unsatisfiable=True)
'Tests downloading range when Range only provides start index.'
def test_download_range_range_header_no_end(self):
self.do_blob_range_test('bytes=2-', 'bytes 2-5/6', 'blob', test_range_request=True)
'Tests downloading range when Range uses a negative start index.'
def test_download_range_range_header_negative_start(self):
self.do_blob_range_test('bytes=-1', 'bytes 5-5/6', 'b', test_range_request=True) self.do_blob_range_test('bytes=-2', 'bytes 4-5/6', 'ob', test_range_request=True) self.do_blob_range_test('bytes=-3', 'bytes 3-5/6', 'lob', test_range_request=True) self.do_blob_range_test('bytes=-4', 'bytes 2-5...
'Tests downloading range when Range is a single byte.'
def test_download_range_range_header_single_byte(self):
self.do_blob_range_test('bytes=0-0', 'bytes 0-0/6', 'a', test_range_request=True) self.do_blob_range_test('bytes=1-1', 'bytes 1-1/6', ' ', test_range_request=True) self.do_blob_range_test('bytes=2-2', 'bytes 2-2/6', 'b', test_range_request=True) self.do_blob_range_test('bytes=3-3', 'bytes ...
'Tests that whole blob is downloaded when Range is empty.'
def test_download_range_range_header_empty(self):
blob_key = self.create_blob() environ = {'HTTP_RANGE': ''} headers = [(blobstore.BLOB_KEY_HEADER, str(blob_key)), ('Content-Type', 'image/jpg')] state = request_rewriter.RewriterState(environ, '200 original message', headers, 'original body') blob_download.blobstore_download_rewriter(state)...
'Setup for namespaces test.'
def setUp(self):
super(BlobDownloadTestNamespace, self).setUp() namespace_manager.set_namespace('abc')
'Create a GS object in the datastore and on disk. Overrides the superclass create_blob method. Returns: The BlobKey of the new object."'
def create_blob(self, content_type='image/png'):
data = 'a blob' filename = '/some_bucket/some_object' stub = cloudstorage_stub.CloudStorageStub(self.blob_storage) options = {} if content_type: options['content-type'] = content_type blob_key = stub.post_start_creation(filename, options) stub.put_continue_creation(blob_key, data,...
'Tests downloads when upload does not specify content-type.'
def test_default_content_type(self):
blob_key = self.create_blob(content_type=None) headers = [(blobstore.BLOB_KEY_HEADER, str(blob_key))] state = request_rewriter.RewriterState({}, '200 original message', headers, 'original body') blob_download.blobstore_download_rewriter(state) self.assertEqual('200 original message', ...
'Use auto Content-Type to set the blob\'s stored mime type.'
def test_rewrite_for_download_use_stored_content_type_auto_mime(self):
self.test_rewrite_for_download_use_stored_content_type(auto_mimetype=True)
'Tests that downloads rewrite when using blob\'s original content-type.'
def test_rewrite_for_download_use_stored_content_type(self, auto_mimetype=False):
blob_key = self.create_blob() headers = [(blobstore.BLOB_KEY_HEADER, str(blob_key))] if auto_mimetype: headers.append(('Content-Type', blob_download._AUTO_MIME_TYPE)) application = wsgi_test_utils.constant_app('200 original message', headers, 'original body') expected_status = '200 ...
'Tests that a missing blob key gives the default content-type.'
def test_rewrite_for_download_missing_blob(self):
headers = [(blobstore.BLOB_KEY_HEADER, 'no such blob'), ('Content-Type', 'text/x-my-content-type')] application = wsgi_test_utils.constant_app('200 original message', headers, 'original body') expected_status = '500 Internal Server Error' expected_headers = {'Content-Length': '0'...