desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Lists all backends for an app.'
def BackendsList(self):
if self.args: self.parser.error('Expected no arguments.') appyaml = self._ParseAppInfoFromYaml(self.basepath) rpcserver = self._GetRpcServer() response = rpcserver.Send('/api/backends/list', app_id=appyaml.application) print >>self.out_fh, response
'Does a rollback of an existing transaction on this backend.'
def BackendsRollback(self):
if (len(self.args) != 1): self.parser.error('Expected a single <backend> argument.') self._Rollback(self.args[0])
'Starts a backend.'
def BackendsStart(self):
if (len(self.args) != 1): self.parser.error('Expected a single <backend> argument.') backend = self.args[0] appyaml = self._ParseAppInfoFromYaml(self.basepath) rpcserver = self._GetRpcServer() response = rpcserver.Send('/api/backends/start', app_id=appyaml.application, backend=ba...
'Stops a backend.'
def BackendsStop(self):
if (len(self.args) != 1): self.parser.error('Expected a single <backend> argument.') backend = self.args[0] appyaml = self._ParseAppInfoFromYaml(self.basepath) rpcserver = self._GetRpcServer() response = rpcserver.Send('/api/backends/stop', app_id=appyaml.application, backend=bac...
'Deletes a backend.'
def BackendsDelete(self):
if (len(self.args) != 1): self.parser.error('Expected a single <backend> argument.') backend = self.args[0] appyaml = self._ParseAppInfoFromYaml(self.basepath) rpcserver = self._GetRpcServer() response = rpcserver.Send('/api/backends/delete', app_id=appyaml.application, backend=b...
'Changes the configuration of an existing backend.'
def BackendsConfigure(self):
if (len(self.args) != 1): self.parser.error('Expected a single <backend> argument.') backend = self.args[0] appyaml = self._ParseAppInfoFromYaml(self.basepath) backends_yaml = self._ParseBackendsYaml(self.basepath) rpcserver = self._GetRpcServer() response = rpcserver.Send('/...
'Validates given yaml paths and returns the parsed yaml objects. Args: yaml_paths: List of paths to AppInfo yaml files. Returns: List of parsed AppInfo yamls.'
def _ParseAndValidateModuleYamls(self, yaml_paths):
results = [] app_id = None last_yaml_path = None for yaml_path in yaml_paths: if (not os.path.isfile(yaml_path)): _PrintErrorAndExit(self.error_fh, ("Error: The given path '%s' is not to a YAML configuration file.\n" % yaml_path)) file_name = ...
'Process flags and yaml files and make a call to the given path. The \'start\' and \'stop\' actions are extremely similar in how they process input to appcfg.py and only really differ in what path they hit on the RPCServer. Args: action_path: Path on the RPCServer to send the call to.'
def _ModuleAction(self, action_path):
modules_to_process = [] if (len(self.args) == 0): if (not (self.options.app_id and self.options.module and self.options.version)): _PrintErrorAndExit(self.error_fh, 'Expected at least one <file> argument or the --application, --module and --version flags ...
'Starts one or more modules.'
def Start(self):
self._ModuleAction('/api/modules/start')
'Stops one or more modules.'
def Stop(self):
self._ModuleAction('/api/modules/stop')
'Does a rollback of an existing transaction for this app version.'
def Rollback(self):
if self.args: self.parser.error('Expected a single <directory> or <file> argument.') self._Rollback()
'Does a rollback of an existing transaction. Args: backend: name of a backend to rollback, or None If a backend is specified the rollback will affect only that backend, if no backend is specified the rollback will affect the current app version.'
def _Rollback(self, backend=None):
if os.path.isdir(self.basepath): module_yaml = self._ParseAppInfoFromYaml(self.basepath) else: file_name = os.path.basename(self.basepath) self.basepath = os.path.dirname(self.basepath) if (not self.basepath): self.basepath = '.' module_yaml = self._ParseAppIn...
'Sets the default version.'
def SetDefaultVersion(self):
module = '' if (len(self.args) == 1): appyaml = self._ParseAppInfoFromYaml(self.args[0]) app_id = appyaml.application module = (appyaml.module or '') version = appyaml.version elif (len(self.args) == 0): if (not (self.options.app_id and self.options.version)): ...
'Write request logs to a file.'
def RequestLogs(self):
args_length = len(self.args) module = '' if (args_length == 2): appyaml = self._ParseAppInfoFromYaml(self.args.pop(0)) app_id = appyaml.application module = (appyaml.module or '') version = appyaml.version elif (args_length == 1): if (not (self.options.app_id and ...
'Translates an ISO 8601 date to a date object. Args: date: A date string as YYYY-MM-DD. time_func: time.time() function for testing. Returns: A date object representing the last day of logs to get. If no date is given, returns today in the US/Pacific timezone.'
@staticmethod def _ParseEndDate(date, time_func=time.time):
if (not date): return PacificDate(time_func()) return datetime.date(*[int(i) for i in date.split('-')])
'Adds request_logs-specific options to \'parser\'. Args: parser: An instance of OptionsParser.'
def _RequestLogsOptions(self, parser):
parser.add_option('-n', '--num_days', type='int', dest='num_days', action='store', default=None, help='Number of days worth of log data to get. The cut-off point is midnight US/Pacific. Use 0 to get all available logs. Default is 1, unless ...
'Displays information about cron definitions. Args: now: used for testing. output: Used for testing.'
def CronInfo(self, now=None, output=sys.stdout):
if self.args: self.parser.error('Expected a single <directory> argument.') if (now is None): now = datetime.datetime.utcnow() cron_yaml = self._ParseCronYaml(self.basepath) if (cron_yaml and cron_yaml.cron): for entry in cron_yaml.cron: description = entry...
'Adds cron_info-specific options to \'parser\'. Args: parser: An instance of OptionsParser.'
def _CronInfoOptions(self, parser):
parser.add_option('-n', '--num_runs', type='int', dest='num_runs', action='store', default=5, help='Number of runs of each cron job to displayDefault is 5')
'Checks that upload/download options are present.'
def _CheckRequiredLoadOptions(self):
for option in ['filename']: if (getattr(self.options, option) is None): self.parser.error(("Option '%s' is required." % option)) if (not self.options.url): self.parser.error("You must have google.appengine.ext.remote_api.handler assigned to an endpoint ...
'Uses app.yaml to determine the remote_api endpoint. Args: appyaml: A parsed app.yaml file. Returns: The url of the remote_api endpoint as a string, or None'
def InferRemoteApiUrl(self, appyaml):
handlers = appyaml.handlers handler_suffixes = ['remote_api/handler.py', 'remote_api.handler.application'] app_id = appyaml.application for handler in handlers: if (hasattr(handler, 'script') and handler.script): if any((handler.script.endswith(suffix) for suffix in handler_suffixes)...
'Invokes the bulkloader with the given keyword arguments. Args: arg_dict: Dictionary of arguments to pass to bulkloader.Run().'
def RunBulkloader(self, arg_dict):
try: import sqlite3 except ImportError: logging.error('upload_data action requires SQLite3 and the python sqlite3 module (included in python since 2.5).') sys.exit(1) sys.exit(bulkloader.Run(arg_dict))
'Performs common verification and set up for upload and download.'
def _SetupLoad(self):
if ((len(self.args) != 1) and (not self.options.url)): self.parser.error('Expected either --url or a single <directory> argument.') if (len(self.args) == 1): self.basepath = self.args[0] appyaml = self._ParseAppInfoFromYaml(self.basepath) self.options.app_id ...
'Performs a datastore download via the bulkloader. Args: run_fn: Function to invoke the bulkloader, used for testing.'
def PerformDownload(self, run_fn=None):
if (run_fn is None): run_fn = self.RunBulkloader self._SetupLoad() StatusUpdate('Downloading data records.') args = self._MakeLoaderArgs() args['download'] = bool(args['config_file']) args['has_header'] = False args['map'] = False args['dump'] = (not args['config_file']) ...
'Performs a datastore upload via the bulkloader. Args: run_fn: Function to invoke the bulkloader, used for testing.'
def PerformUpload(self, run_fn=None):
if (run_fn is None): run_fn = self.RunBulkloader self._SetupLoad() StatusUpdate('Uploading data records.') args = self._MakeLoaderArgs() args['download'] = False args['map'] = False args['dump'] = False args['restore'] = (not args['config_file']) args['create_config'] =...
'Create a bulkloader config via the bulkloader wizard. Args: run_fn: Function to invoke the bulkloader, used for testing.'
def CreateBulkloadConfig(self, run_fn=None):
if (run_fn is None): run_fn = self.RunBulkloader self._SetupLoad() StatusUpdate('Creating bulkloader configuration.') args = self._MakeLoaderArgs() args['download'] = False args['has_header'] = False args['map'] = False args['dump'] = False args['restore'] = False a...
'Adds options common to \'upload_data\' and \'download_data\'. Args: parser: An instance of OptionsParser.'
def _PerformLoadOptions(self, parser):
parser.add_option('--url', type='string', dest='url', action='store', help='The location of the remote_api endpoint.') parser.add_option('--batch_size', type='int', dest='batch_size', action='store', default=10, help='Number of records to post in each request.') parser.ad...
'Adds \'upload_data\' specific options to the \'parser\' passed in. Args: parser: An instance of OptionsParser.'
def _PerformUploadOptions(self, parser):
self._PerformLoadOptions(parser) parser.add_option('--filename', type='string', dest='filename', action='store', help='The name of the file containing the input data. (Required)') parser.add_option('--kind', type='string', dest='kind', action='store', help='The kind of th...
'Adds \'download_data\' specific options to the \'parser\' passed in. Args: parser: An instance of OptionsParser.'
def _PerformDownloadOptions(self, parser):
self._PerformLoadOptions(parser) parser.add_option('--filename', type='string', dest='filename', action='store', help='The name of the file where output data is to be written. (Required)') parser.add_option('--kind', type='string', dest='kind', action='store', help='The ...
'Adds \'download_data\' specific options to the \'parser\' passed in. Args: parser: An instance of OptionsParser.'
def _CreateBulkloadConfigOptions(self, parser):
self._PerformLoadOptions(parser) parser.add_option('--filename', type='string', dest='filename', action='store', help='The name of the file where the generated template is to be written. (Required)')
'Outputs the current resource limits. Args: output: The file handle to write the output to (used for testing).'
def ResourceLimitsInfo(self, output=None):
appyaml = self._ParseAppInfoFromYaml(self.basepath) resource_limits = GetResourceLimits(self._GetRpcServer(), appyaml) for attr_name in sorted(resource_limits): print >>output, ('%s: %s' % (attr_name, resource_limits[attr_name]))
'Initializer for the class attributes.'
def __init__(self, function, usage, short_desc, long_desc='', error_desc=None, options=(lambda obj, parser: None), uses_basepath=True, hidden=False):
self.function = function self.usage = usage self.short_desc = short_desc self.long_desc = long_desc self.error_desc = error_desc self.options = options self.uses_basepath = uses_basepath self.hidden = hidden
'Invoke this Action on the specified AppCfg. This calls the function of the appropriate name on AppCfg, and respects polymophic overrides. Args: appcfg: The appcfg to use. Returns: The result of the function call.'
def __call__(self, appcfg):
method = getattr(appcfg, self.function) return method()
'Constructor. Args: blob_storage: BlobStorage instance where actual blobs are stored. generate_blob_key: Function used for generating unique blob keys. now_func: Function that returns the current timestamp.'
def __init__(self, blob_storage, generate_blob_key=GenerateBlobKey, now_func=datetime.datetime.now):
self.__blob_storage = blob_storage self.__generate_blob_key = generate_blob_key self.__now_func = now_func
'Store form-item to blob storage. Args: form_item: FieldStorage instance that represents a specific form field. This instance should have a non-empty filename attribute, meaning that it is an uploaded blob rather than a normal form field. creation: Timestamp to associate with new blobs creation time. This parameter is...
def StoreBlob(self, form_item, creation):
(main_type, sub_type) = _SplitMIMEType(form_item['content_type']) blob_key = self.__generate_blob_key() self.__blob_storage.StoreBlob(blob_key, cStringIO.StringIO(form_item['body'])) content_type_formatter = base.MIMEBase(main_type, sub_type) blob_entity = datastore.Entity('__BlobInfo__', name=str(b...
'Generate a new post from original form. Also responsible for storing blobs in the datastore. Args: form: Instance of cgi.FieldStorage representing the whole form derived from original post data. boundary: Boundary to use for resulting form. Used only in tests so that the boundary is always consistent. max_bytes_per_b...
def _GenerateMIMEMessage(self, form, boundary=None, max_bytes_per_blob=None, max_bytes_total=None, bucket_name=None):
message = multipart.MIMEMultipart('form-data', boundary) for (name, value) in form.headers.items(): if (name.lower() not in STRIPPED_HEADERS): message.add_header(name, value) def IterateForm(): 'Flattens form in to single sequence of cgi.FieldStorage insta...
'Generate a new post string from original form. Args: form: Instance of cgi.FieldStorage representing the whole form derived from original post data. boundary: Boundary to use for resulting form. Used only in tests so that the boundary is always consistent. max_bytes_per_blob: The maximum size in bytes that any single...
def GenerateMIMEMessageString(self, form, boundary=None, max_bytes_per_blob=None, max_bytes_total=None, bucket_name=None):
message = self._GenerateMIMEMessage(form, boundary=boundary) message_out = cStringIO.StringIO() gen = generator.Generator(message_out, maxheaderlen=0) gen.flatten(message, unixfrom=False) return message_out.getvalue()
'Create a ServerRequestException from a given urllib2.HTTPError. Args: http_error: The HTTPError that the ServerRequestException will be based on.'
def __init__(self, http_error):
error_details = None if http_error.fp: try: error_body = json.load(http_error.fp) error_details = [('%s: %s' % (detail['message'], detail['debug_info'])) for detail in error_body['error']['errors']] except (ValueError, TypeError, KeyError): pass if erro...
'Initialize a ReQueue instance. Args: queue_capacity: The number of items that can be put in the ReQueue. requeue_capacity: The numer of items that can be reput in the ReQueue. queue_factory: Used for dependency injection. get_time: Used for dependency injection.'
def __init__(self, queue_capacity, requeue_capacity=None, queue_factory=Queue.Queue, get_time=time.time):
if (requeue_capacity is None): requeue_capacity = queue_capacity self.get_time = get_time self.queue = queue_factory(queue_capacity) self.requeue = queue_factory(requeue_capacity) self.lock = threading.Lock() self.put_cond = threading.Condition(self.lock) self.get_cond = threading.Co...
'Performs the given action with a timeout. The action must be non-blocking, and raise an instance of exc on a recoverable failure. If the action fails with an instance of exc, we wait on wait_cond before trying again. Failure after the timeout is reached is propagated as an exception. Success is signalled by notifyi...
def _DoWithTimeout(self, action, exc, wait_cond, done_cond, lock, timeout=None, block=True):
if ((timeout is not None) and (timeout < 0.0)): raise ValueError("'timeout' must not be a negative number") if (not block): timeout = 0.0 result = None success = False start_time = self.get_time() lock.acquire() try: while (not success): ...
'Put an item into the requeue. Args: item: An item to add to the requeue. block: Whether to block if the requeue is full. timeout: Maximum on how long to wait until the queue is non-full. Raises: Queue.Full if the queue is full and the timeout expires.'
def put(self, item, block=True, timeout=None):
def PutAction(): self.queue.put(item, block=False) self._DoWithTimeout(PutAction, Queue.Full, self.get_cond, self.put_cond, self.lock, timeout=timeout, block=block)
'Re-put an item back into the requeue. Re-putting an item does not increase the number of outstanding tasks, so the reput item should be uniquely associated with an item that was previously removed from the requeue and for which TaskDone has not been called. Args: item: An item to add to the requeue. block: Whether to ...
def reput(self, item, block=True, timeout=None):
def ReputAction(): self.requeue.put(item, block=False) self._DoWithTimeout(ReputAction, Queue.Full, self.get_cond, self.put_cond, self.lock, timeout=timeout, block=block)
'Get an item from the requeue. Args: block: Whether to block if the requeue is empty. timeout: Maximum on how long to wait until the requeue is non-empty. Returns: An item from the requeue. Raises: Queue.Empty if the queue is empty and the timeout expires.'
def get(self, block=True, timeout=None):
def GetAction(): try: result = self.requeue.get(block=False) self.requeue.task_done() except Queue.Empty: result = self.queue.get(block=False) return result return self._DoWithTimeout(GetAction, Queue.Empty, self.put_cond, self.get_cond, self.lock, tim...
'Blocks until all of the items in the requeue have been processed.'
def join(self):
self.queue.join()
'Indicate that a previously enqueued item has been fully processed.'
def task_done(self):
self.queue.task_done()
'Returns true if the requeue is empty.'
def empty(self):
return (self.queue.empty() and self.requeue.empty())
'Try to get an item from the queue without blocking.'
def get_nowait(self):
return self.get(block=False)
'Constructor. Args: relative_url: Mapped directly to attribute. path: Mapped directly to attribute. headers: Mapped directly to attribute. infile: Mapped directly to attribute. force_admin: Mapped directly to attribute.'
def __init__(self, relative_url, path, headers, infile, secret_hash, force_admin=False):
self.relative_url = relative_url self.path = path self.headers = headers self.infile = infile self.force_admin = force_admin if (DEVEL_PAYLOAD_RAW_HEADER in self.headers): if (self.headers[DEVEL_PAYLOAD_RAW_HEADER] == secret_hash): self.force_admin = True if (DEVEL_FAKE_I...
'Used mainly for testing. Returns: True if all fields of both requests are equal, else False.'
def __eq__(self, other):
if (type(self) == type(other)): for attribute in self.ATTRIBUTES: if (getattr(self, attribute) != getattr(other, attribute)): return False return True
'String representation of request. Used mainly for testing. Returns: String representation of AppServerRequest. Strings of different request objects that have the same values for all fields compare as equal.'
def __repr__(self):
results = [] for attribute in self.ATTRIBUTES: results.append(('%s: %s' % (attribute, getattr(self, attribute)))) return ('<AppServerRequest %s>' % ' '.join(results))
'Dispatch and handle an HTTP request. base_env_dict should contain at least these CGI variables: REQUEST_METHOD, REMOTE_ADDR, SERVER_SOFTWARE, SERVER_NAME, SERVER_PROTOCOL, SERVER_PORT Args: request: AppServerRequest instance. outfile: File-like object where output data should be written. base_env_dict: Dictionary of C...
def Dispatch(self, request, outfile, base_env_dict=None):
raise NotImplementedError
'Process the end of an internal redirect. This method is called after all subsequent dispatch requests have finished. By default the output from the dispatched process is copied to the original. This will not be called on dispatchers that do not return an internal redirect. Args: dispatched_output: StringIO buffer cont...
def EndRedirect(self, dispatched_output, original_output):
original_output.write(dispatched_output.read())
'Initializer.'
def __init__(self):
self._url_patterns = []
'Adds a URL pattern to the list of patterns. If the supplied regex starts with a \'^\' or ends with a \'$\' an InvalidAppConfigError exception will be raised. Start and end symbols and implicitly added to all regexes, meaning we assume that all regexes consume all input from a URL. Args: regex: String containing the re...
def AddURL(self, regex, dispatcher, path, requires_login, admin_only, auth_fail_action):
if (not isinstance(dispatcher, URLDispatcher)): raise TypeError('dispatcher must be a URLDispatcher sub-class') if (regex.startswith('^') or regex.endswith('$')): raise InvalidAppConfigError('regex starts with "^" or ends with "$"') adjusted_regex = ('^%s$...
'Matches a URL from a request against the list of URL patterns. The supplied relative_url may include the query string (i.e., the \'?\' character and everything following). Args: relative_url: Relative URL being accessed in a request. split_url: Used for dependency injection. Returns: Tuple (dispatcher, matched_path, r...
def Match(self, relative_url, split_url=SplitURL):
(adjusted_url, unused_query_string) = split_url(relative_url) for url_tuple in self._url_patterns: (url_re, dispatcher, path, requires_login, admin_only, auth_fail_action) = url_tuple the_match = url_re.match(adjusted_url) if the_match: adjusted_path = the_match.expand(path) ...
'Retrieves the URLDispatcher objects that could be matched. Should only be used in tests. Returns: A set of URLDispatcher objects.'
def GetDispatchers(self):
return set([url_tuple[1] for url_tuple in self._url_patterns])
'Initializer. Args: config: AppInfoExternal instance representing the parsed app.yaml file. login_url: Relative URL which should be used for handling user logins. module_manager: ModuleManager instance that is used to detect and reload modules if the matched Dispatcher is dynamic. url_matchers: Sequence of URLMatcher o...
def __init__(self, config, login_url, module_manager, url_matchers, get_user_info=dev_appserver_login.GetUserInfo, login_redirect=dev_appserver_login.LoginRedirect):
self._config = config self._login_url = login_url self._module_manager = module_manager self._url_matchers = tuple(url_matchers) self._get_user_info = get_user_info self._login_redirect = login_redirect
'Dispatches a request to the first matching dispatcher. Matchers are checked in the order they were supplied to the constructor. If no matcher matches, a 404 error will be written to the outfile. The path variable supplied to this method is ignored. The value of request.path is ignored.'
def Dispatch(self, request, outfile, base_env_dict=None):
cookies = ', '.join(request.headers.getheaders('cookie')) (email_addr, user_id, admin, valid_cookie) = self._get_user_info(cookies) for matcher in self._url_matchers: (dispatcher, matched_path, requires_login, admin_only, auth_fail_action) = matcher.Match(request.relative_url) if (dispatc...
'Initializer. Args: config: AppInfoExternal instance representing the parsed app.yaml file. module_dict: Dictionary in which application-loaded modules should be preserved between requests. This dictionary must be separate from the sys.modules dictionary. path_adjuster: Instance of PathAdjuster to use for finding absol...
def __init__(self, config, module_dict, root_path, path_adjuster, setup_env=SetupEnvironment, exec_cgi=ExecuteCGI):
self._config = config self._module_dict = module_dict self._root_path = root_path self._path_adjuster = path_adjuster self._setup_env = setup_env self._exec_cgi = exec_cgi
'Dispatches the Python CGI.'
def Dispatch(self, request, outfile, base_env_dict=None):
request_size = GetRequestSize(request, base_env_dict, outfile) if (request_size is None): return memory_file = cStringIO.StringIO() CopyStreamPart(request.infile, memory_file, request_size) memory_file.seek(0) before_level = logging.root.level try: env = {} if self._c...
'Returns a string representation of this dispatcher.'
def __str__(self):
return 'CGI dispatcher'
'Initializer. Args: config: AppInfoExternal instance representing the parsed app.yaml file. module_dict: Passed to CGIDispatcher. path_adjuster: Passed to CGIDispatcher. cgi_func: Callable function taking no parameters that should be executed in a CGI environment in the current process.'
def __init__(self, config, module_dict, path_adjuster, cgi_func):
self._cgi_func = cgi_func def curried_exec_script(*args, **kwargs): cgi_func() return False def curried_exec_cgi(*args, **kwargs): kwargs['exec_script'] = curried_exec_script return ExecuteCGI(*args, **kwargs) CGIDispatcher.__init__(self, config, module_dict, '', path_adj...
'Preserves sys.modules for CGIDispatcher.Dispatch.'
def Dispatch(self, *args, **kwargs):
self._module_dict.update(sys.modules) CGIDispatcher.Dispatch(self, *args, **kwargs)
'Returns a string representation of this dispatcher.'
def __str__(self):
return ('Local CGI dispatcher for %s' % self._cgi_func)
'Initializer. Args: root_path: Path to the root of the application running on the server.'
def __init__(self, root_path):
self._root_path = os.path.abspath(root_path)
'Adjusts application file paths to relative to the application. More precisely this method adjusts application file path to paths relative to the application or external library directories. Handler paths that start with $PYTHON_LIB will be converted to paths relative to the google directory. Args: path: File path that...
def AdjustPath(self, path):
if path.startswith(PYTHON_LIB_VAR): path = os.path.join(SDK_ROOT, path[(len(PYTHON_LIB_VAR) + 1):]) else: path = os.path.join(self._root_path, path) return path
'Initializer. Args: url_map_list: List of appinfo.URLMap objects. If empty or None, then we always use the mime type chosen by the mimetypes module. default_expiration: String describing default expiration time for browser based caching of static files. If set to None this disallows any browser caching of static conte...
def __init__(self, url_map_list, default_expiration):
if (default_expiration is not None): self._default_expiration = appinfo.ParseExpiration(default_expiration) else: self._default_expiration = None self._patterns = [] for url_map in (url_map_list or []): handler_type = url_map.GetHandlerType() if (handler_type not in (appi...
'Returns the first appinfo.URLMap that matches path, or a dummy instance. A dummy instance is returned when no appinfo.URLMap matches path (see the URLMap.static_file_path_re property). When a dummy instance is returned, it is always the same one. The dummy instance is constructed simply by doing the following: appinfo...
def _FirstMatch(self, path):
for (path_re, url_map) in self._patterns: if path_re.match(path): return url_map return StaticFileConfigMatcher._DUMMY_URLMAP
'Tests if the given path points to a "static" file. Args: path: A string containing the file\'s path relative to the app. Returns: Boolean, True if the file was configured to be static.'
def IsStaticFile(self, path):
return (self._FirstMatch(path) is not self._DUMMY_URLMAP)
'Returns the mime type that we should use when serving the specified file. Args: path: A string containing the file\'s path relative to the app. Returns: String containing the mime type to use. Will be \'application/octet-stream\' if we have no idea what it should be.'
def GetMimeType(self, path):
url_map = self._FirstMatch(path) if (url_map.mime_type is not None): return url_map.mime_type (unused_filename, extension) = os.path.splitext(path) return mimetypes.types_map.get(extension, 'application/octet-stream')
'Returns the cache expiration duration to be users for the given file. Args: path: A string containing the file\'s path relative to the app. Returns: Integer number of seconds to be used for browser cache expiration time.'
def GetExpiration(self, path):
if (self._default_expiration is None): return 0 url_map = self._FirstMatch(path) if (url_map.expiration is None): return self._default_expiration return appinfo.ParseExpiration(url_map.expiration)
'Returns http_headers of the matching appinfo.URLMap, or an empty one. Args: path: A string containing the file\'s path relative to the app. Returns: A user-specified HTTP headers to be used in static content response. These headers are contained in an appinfo.HttpHeadersDict, which maps header names to values (both st...
def GetHttpHeaders(self, path):
return (self._FirstMatch(path).http_headers or appinfo.HttpHeadersDict())
'Initializer. Args: config: AppInfoExternal instance representing the parsed app.yaml file. path_adjuster: Instance of PathAdjuster to use for finding absolute paths of data files on disk. static_file_config_matcher: StaticFileConfigMatcher object. read_data_file: Used for dependency injection.'
def __init__(self, config, path_adjuster, static_file_config_matcher, read_data_file=ReadDataFile):
self._config = config self._path_adjuster = path_adjuster self._static_file_config_matcher = static_file_config_matcher self._read_data_file = read_data_file
'Reads the file and returns the response status and data.'
def Dispatch(self, request, outfile, base_env_dict=None):
full_path = self._path_adjuster.AdjustPath(request.path) (status, data) = self._read_data_file(full_path) content_type = self._static_file_config_matcher.GetMimeType(request.path) static_file = self._static_file_config_matcher.IsStaticFile(request.path) expiration = self._static_file_config_matcher....
'Returns a string representation of this dispatcher.'
def __str__(self):
return 'File dispatcher'
'Returns string of hash of file content, unique per URL.'
@staticmethod def CreateEtag(data):
data_crc = zlib.crc32(data) return base64.b64encode(str(data_crc))
'Checks if there is an entity tag match. Args: supplied_etags: list of input etags current_etag: the calculated etag for the entity allow_weak_match: Allow for weak tag comparison. Returns: True if there is a match, False otherwise.'
@staticmethod def _CheckETagMatches(supplied_etags, current_etag, allow_weak_match):
for tag in supplied_etags: if (allow_weak_match and tag.startswith('W/')): tag = tag[2:] tag_data = tag.strip('"') if ((tag_data == '*') or (tag_data == current_etag)): return True return False
'Initializer. Args: response_file: A file-like object that contains the full response generated by the user application request handler. If present the headers and body are set from this value, although the values may be further overridden by the keyword parameters. kwds: All keywords are mapped to attributes of AppSe...
def __init__(self, response_file=None, **kwds):
self.status_code = 200 self.status_message = 'Good to go' self.large_response = False if response_file: self.SetResponse(response_file) else: self.headers = mimetools.Message(cStringIO.StringIO()) self.body = None for (name, value) in kwds.iteritems(): setat...
'Sets headers and body from the response file. Args: response_file: File like object to set body and headers from.'
def SetResponse(self, response_file):
self.headers = mimetools.Message(response_file) self.body = response_file
'Get header data as a string. Returns: String representation of header with line breaks cleaned up.'
@property def header_data(self):
header_list = [] for header in self.headers.headers: header = header.rstrip('\n\r') header_list.append(header) if (not self.headers.getheader('Content-Type')): header_list.append('Content-Type: text/html') return ('\r\n'.join(header_list) + '\r\n')
'Initializer. Args: modules: Dictionary containing monitored modules.'
def __init__(self, modules):
self._modules = modules self._default_modules = self._modules.copy() self._save_path_hooks = sys.path_hooks[:] self._modification_times = {} self._dirty = True
'Helper method to try to determine modules source file. Args: module: Module object to get file for. is_file: Function used to determine if a given path is a file. Returns: Path of the module\'s corresponding Python source file if it exists, or just the module\'s compiled Python file. If the module has an invalid __fil...
@staticmethod def GetModuleFile(module, is_file=os.path.isfile):
module_file = getattr(module, '__file__', None) if (module_file is None): return None source_file = module_file[:(module_file.rfind('py') + 2)] if is_file(source_file): return source_file return module.__file__
'Determines if any monitored files have been modified. Returns: True if one or more files have been modified, False otherwise.'
def AreModuleFilesModified(self):
for (name, (mtime, fname)) in self._modification_times.iteritems(): if (name not in self._modules): continue module = self._modules[name] try: if (mtime != os.path.getmtime(fname)): self._dirty = True return True except OSError ...
'Records the current modification times of all monitored modules.'
def UpdateModuleFileModificationTimes(self):
if (not self._dirty): return self._modification_times.clear() for (name, module) in self._modules.items(): if (not isinstance(module, types.ModuleType)): continue module_file = self.GetModuleFile(module) if (not module_file): continue try: ...
'Clear modules so that when request is run they are reloaded.'
def ResetModules(self):
lib_config._default_registry.reset() self._modules.clear() self._modules.update(self._default_modules) sys.path_hooks[:] = self._save_path_hooks sys.meta_path = [] apiproxy_stub_map.apiproxy.GetPreCallHooks().Clear() apiproxy_stub_map.apiproxy.GetPostCallHooks().Clear()
'Check to see if this is a service url and matches inbound_services.'
def ExcludePath(self, path):
skip = False for reserved_path in self.reserved_paths.keys(): if path.startswith(reserved_path): if ((not self.inbound_services) or (self.reserved_paths[reserved_path] not in self.inbound_services)): return (True, self.reserved_paths[reserved_path]) return (False, None)
'Constructor. Args: server_address: the bind address of the server. request_handler_class: class used to handle requests.'
def __init__(self, server_address, request_handler_class):
BaseHTTPServer.HTTPServer.__init__(self, server_address, request_handler_class) self._events = [] self._stopped = False
'Override the base handle_request call. Python 2.6 changed the semantics of handle_request() with r61289. This patches it back to the Python 2.5 version, which has helpfully been renamed to _handle_request_noblock.'
def handle_request(self):
if hasattr(self, '_handle_request_noblock'): self._handle_request_noblock() else: BaseHTTPServer.HTTPServer.handle_request(self)
'Overrides the base get_request call. Args: time_func: used for testing. select_func: used for testing. Returns: a (socket_object, address info) tuple.'
def get_request(self, time_func=time.time, select_func=select.select):
while True: if self._events: current_time = time_func() next_eta = self._events[0][0] delay = (next_eta - current_time) else: delay = DEFAULT_SELECT_DELAY (readable, _, _) = select_func([self.socket], [], [], max(delay, 0)) if readable:...
'Handle one request at a time until told to stop.'
def serve_forever(self):
while (not self._stopped): self.handle_request() self.server_close()
'Stop the serve_forever() loop. Stop happens on the next handle_request() loop; it will not stop immediately. Since dev_appserver.py must run on py2.5 we can\'t use newer features of SocketServer (e.g. shutdown(), added in py2.6).'
def stop_serving_forever(self):
self._stopped = True
'Add a runnable event to be run at the specified time. Args: eta: when to run the event, in seconds since epoch. runnable: a callable object. service: the service that owns this event. Should be set if id is set. event_id: optional id of the event. Used for UpdateEvent below.'
def AddEvent(self, eta, runnable, service=None, event_id=None):
heapq.heappush(self._events, (eta, runnable, service, event_id))
'Update a runnable event in the heap with a new eta. TODO(moishel): come up with something better than a linear scan to update items. For the case this is used for now -- updating events to "time out" channels -- this works fine because those events are always soon (within seconds) and thus found quickly towards the fr...
def UpdateEvent(self, service, event_id, eta):
for id in xrange(len(self._events)): item = self._events[id] if ((item[2] == service) and (item[3] == event_id)): item = (eta, item[1], item[2], item[3]) del self._events[id] heapq.heappush(self._events, item) break
'Load a single NagFile object where one and only one is expected. Args: nag_file: A file-like object or string containing the yaml data to parse. Returns: A NagFile instance.'
@staticmethod def Load(nag_file):
return yaml_object.BuildSingleObject(NagFile, nag_file)
'Create a new SDKUpdateChecker. Args: rpcserver: The AbstractRpcServer to use. configs: A list of yaml objects or a single yaml object that specify the configuration of this application. isdir: Replacement for os.path.isdir (for testing). isfile: Replacement for os.path.isfile (for testing). open_fn: Replacement for th...
def __init__(self, rpcserver, configs, isdir=os.path.isdir, isfile=os.path.isfile, open_fn=open):
if (not isinstance(configs, list)): configs = [configs] self.rpcserver = rpcserver self.isdir = isdir self.isfile = isfile self.open = open_fn self.runtimes = set((config.runtime for config in configs)) self.runtime_to_api_version = {} for config in configs: self.runtime_...
'Returns the filename for the nag file for this user.'
@staticmethod def MakeNagFilename():
user_homedir = os.path.expanduser('~/') if (not os.path.isdir(user_homedir)): (drive, unused_tail) = os.path.splitdrive(os.__file__) if drive: os.environ['HOMEDRIVE'] = drive return os.path.expanduser(('~/' + NAG_FILE))
'Parse the local VERSION file. Returns: A Yaml object or None if the file does not exist.'
def _ParseVersionFile(self):
return GetVersionObject(isfile=self.isfile, open_fn=self.open)
'Determines if the app\'s api_version is supported by the SDK. Uses the api_version field from the AppInfoExternal to determine if the SDK supports that api_version. Raises: sys.exit if the api_version is not supported.'
def CheckSupportedVersion(self):
version = self._ParseVersionFile() if (version is None): logging.error('Could not determine if the SDK supports the api_version requested in app.yaml.') return unsupported_api_versions_found = False for (runtime, api_versions) in self.runtime_to_api_versi...
'Queries the server for updates and nags the user if appropriate. Queries the server for the latest SDK version at the same time reporting the local SDK version. The server will respond with a yaml document containing the fields: \'release\': The name of the release (e.g. 1.2). \'timestamp\': The time the release was ...
def CheckForUpdates(self):
version = self._ParseVersionFile() if (version is None): logging.info('Skipping update check') return logging.info('Checking for updates to the SDK.') responses = {} try: for runtime in self.runtimes: responses[runtime] = yaml.safe_load(self.r...
'Parses the nag file. Returns: A NagFile if the file was present else None.'
def _ParseNagFile(self):
nag_filename = SDKUpdateChecker.MakeNagFilename() if self.isfile(nag_filename): fh = self.open(nag_filename, 'r') try: nag = NagFile.Load(fh) finally: fh.close() return nag return None
'Writes the NagFile to the user\'s nag file. If the destination path does not exist, this method will log an error and fail silently. Args: nag: The NagFile to write.'
def _WriteNagFile(self, nag):
nagfilename = SDKUpdateChecker.MakeNagFilename() try: fh = self.open(nagfilename, 'w') try: fh.write(nag.ToYAML()) finally: fh.close() except (OSError, IOError) as e: logging.error('Could not write nag file to %s. Error: %s', na...