desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get cache to store expensive objects. Some formats need expensive initialization to even start iteration. They can store the initialized objects into the cache and try to retrieve the objects from the cache at later iterations. For example, a zip format needs to create a ZipFile object to iterate over the zipfile. It ...
def get_cache(self):
return self._cache
'Create an default instance of FileFormat. Used by parser to create default instances. Args: kwargs: kwargs parser parsed from user input. Returns: A default instance of FileFormat.'
@classmethod def default_instance(cls, **kwargs):
return cls(0, **kwargs)
'Save _index before updating it to support potential rollback.'
def checkpoint(self):
self._previous_index = self._index
'Serialize states to a json compatible structure.'
def to_json(self):
return {self._KWARGS: self._kwargs, self._RANGE: self._range, self._FORMAT: self.NAME, self._PREVIOUS_INDEX: self._previous_index}
'Deserialize from json compatible structure.'
@classmethod def from_json(cls, json):
return cls(json[cls._PREVIOUS_INDEX], json[cls._RANGE], **json[cls._KWARGS])
'Indicates whether this format support splitting within a file boundary. Returns: True if a FileFormat allows its inputs to be splitted into different shards.'
@classmethod def can_split(cls):
try: cls.split(0, 0, None, {}) except NotImplementedError: return False return True
'Splits a single chunk of desired_size from file. FileFormatRoot uses this method to ask FileFormat how to split one file of this format. This method takes an opened file and a start_index. If file size is bigger than desired_size, the method determines a chunk of the file whose size is close to desired_size. The chuck...
@classmethod def split(cls, desired_size, start_index, input_file, cache):
raise NotImplementedError(('split is not implemented for %s.' % cls.__name__))
'Does preprocessing on the file-like object and returns another one. Normally a FileFormat directly reads from the file returned by get_current_file(). But some formats need to preprocess that file entirely before iteration can starts (e.g. text formats need to decode first). Args: file_object: read from this object an...
def preprocess(self, file_object):
return file_object
'Returns a file-like object containing next content. Returns: A file-like object containing next content. Raises: ValueError: if content is of none str type.'
def next(self):
result = None try: if (self._range is not None): if (self._index < self._range[0]): self._index = self._range[0] elif (self._index >= self._range[1]): raise EOFError() self._input_files_stream.checkpoint() self.checkpoint() ...
'Finds the next content to return. Expected steps of any implementation: 1. Call get_current_file() to get the file to iterate on. 2. If nothing is read, raise EOFError. Otherwise, process the contents read in anyway. _kwargs is guaranteed to be a dict containing all arguments and values specified by user. 3. If the fo...
def get_next(self):
raise NotImplementedError(('%s not implemented.' % self.__class__.__name__))
'Inherited.'
def get_next(self):
result = self.get_current_file().read() if (not result): raise EOFError() if (self.NAME != _BinaryFormat.NAME): return result.decode(self.NAME) return result
'Inherited.'
def get_next(self):
cache = self.get_cache() if ('zip_file' in cache): zip_file = cache['zip_file'] infolist = cache['infolist'] else: zip_file = zipfile.ZipFile(self._input_files_stream.current) infolist = zip_file.infolist() cache['zip_file'] = zip_file cache['infolist'] = info...
'Inherited.'
@classmethod def can_split(cls):
return True
'Inherited.'
@classmethod def split(cls, desired_size, start_index, opened_file, cache):
if ('infolist' in cache): infolist = cache['infolist'] else: zip_file = zipfile.ZipFile(opened_file) infolist = zip_file.infolist() cache['infolist'] = infolist index = start_index while ((desired_size > 0) and (index < len(infolist))): desired_size -= infolist[in...
'Decodes the entire file to read text.'
def preprocess(self, file_object):
if ('encoding' in self._kwargs): content = file_object.read() content = content.decode(self._kwargs['encoding']) file_object.close() return StringIO.StringIO(content) return file_object
'Inherited.'
def get_next(self):
result = self.get_current_file().readline() if (not result): raise EOFError() if ('encoding' in self._kwargs): result = result.encode(self._kwargs['encoding']) return result
'Base path for all mapreduce-related urls.'
def base_path(self):
path = self.request.path return path[:path.rfind('/')]
'Called before handle method to set up handler.'
def _setup(self):
pass
'To be implemented by subclasses.'
def handle(self):
raise NotImplementedError()
'Number of times this task has been retried.'
def task_retry_count(self):
return int(self.request.headers.get('X-AppEngine-TaskExecutionCount', 0))
'Initializer.'
def __init__(self, *args):
super(BaseHandler, self).__init__(*args) self.json_response = {}
'Base path for all mapreduce-related urls. JSON handlers are mapped to /base_path/command/command_name thus they require special treatment.'
def base_path(self):
path = self.request.path base_path = path[:path.rfind('/')] if (not base_path.endswith('/command')): raise BadRequestPathError('Json handlers should have /command path prefix') return base_path[:base_path.rfind('/')]
'To be implemented by sub-classes.'
def handle(self):
raise NotImplementedError()
'Generates a key name for an exception record. Args: signature: A signature representing the exception and its site. version: The major/minor version of the app the exception occurred in. date: The date the exception occurred. Returns: The unique key name for this exception record.'
@classmethod def get_key_name(cls, signature, version, date=None):
if (not date): date = datetime.date.today() return ('%s@%s:%s' % (signature, date, version))
'Constructs a new ExceptionRecordingHandler. Args: log_interval: The minimum interval at which we will log an individual exception. This is a per-exception timeout, so doesn\'t affect the aggregate rate of exception logging, only the rate at which we record ocurrences of a single exception, to prevent datastore content...
def __init__(self, log_interval=10):
self.log_interval = log_interval logging.Handler.__init__(self)
'Rewrites a path to be relative to the app\'s root directory. Args: path: The path to rewrite. Returns: The path with the prefix removed, if that prefix matches the app\'s root directory.'
@classmethod def __RelativePath(cls, path):
cwd = os.getcwd() if path.startswith(cwd): path = path[(len(cwd) + 1):] return path
'Returns a unique signature string for an exception. Args: exc_info: The exc_info object for an exception. Returns: A unique signature string for the exception, consisting of fully qualified exception name and call site.'
@classmethod def __GetSignature(cls, exc_info):
(ex_type, unused_value, trace) = exc_info frames = traceback.extract_tb(trace) fulltype = ('%s.%s' % (ex_type.__module__, ex_type.__name__)) (path, line_no) = frames[(-1)][:2] path = cls.__RelativePath(path) site = ('%s:%d' % (path, line_no)) signature = ('%s@%s' % (fulltype, site)) if (...
'Returns the URL of the page currently being served. Returns: The full URL of the page currently being served.'
@classmethod def __GetURL(cls):
if (os.environ['SERVER_PORT'] == '80'): scheme = 'http://' else: scheme = 'https://' host = os.environ['SERVER_NAME'] script_name = urllib.quote(os.environ['SCRIPT_NAME']) path_info = urllib.quote(os.environ['PATH_INFO']) qs = os.environ.get('QUERY_STRING', '') if qs: ...
'Returns the log formatter for this handler. Returns: The log formatter to use.'
def __GetFormatter(self):
if self.formatter: return self.formatter else: return logging._defaultFormatter
'Log an error to the datastore, if applicable. Args: The logging.LogRecord object. See http://docs.python.org/library/logging.html#logging.LogRecord'
def emit(self, record):
try: if (not record.exc_info): return signature = self.__GetSignature(record.exc_info) old_namespace = namespace_manager.get_namespace() try: namespace_manager.set_namespace('') if (not memcache.add(signature, None, self.log_interval)): ...
'Run in a transaction to insert or update the record for this transaction. Args: signature: The signature for this exception. exc_info: The exception info record.'
def __EmitTx(self, signature, exc_info):
today = datetime.date.today() version = os.environ['CURRENT_VERSION_ID'] (major_ver, minor_ver) = version.rsplit('.', 1) minor_ver = int(minor_ver) key_name = ExceptionRecord.get_key_name(signature, version) exrecord = ExceptionRecord.get_by_key_name(key_name) if (not exrecord): exre...
'Creates a query object that will retrieve the appropriate exceptions. Returns: A query to retrieve the exceptions required.'
def GetQuery(self, order=None):
q = ereporter.ExceptionRecord.all() q.filter('date =', self.yesterday) q.filter('major_version =', self.major_version) if (self.version_filter.lower() == 'latest'): q.filter('minor_version =', self.minor_version) if order: q.order(order) return q
'Generates an HTML exception report. Args: exceptions: A list of ExceptionRecord objects. This argument will be modified by this function. Returns: An HTML exception report.'
def GenerateReport(self, exceptions):
exceptions.sort(key=(lambda e: (e.minor_version, (- e.count)))) versions = [(minor, list(excs)) for (minor, excs) in itertools.groupby(exceptions, (lambda e: e.minor_version))] template_values = {'version_filter': self.version_filter, 'version_count': len(versions), 'exception_count': sum((len(excs) for (_,...
'Emails an exception report. Args: report: A string containing the report to send.'
def SendReport(self, report):
subject = ('Daily exception report for app "%s", major version "%s"' % (self.app_id, self.major_version)) report_text = saxutils.unescape(re.sub('<[^>]+>', '', report)) mail_args = {'sender': self.sender, 'subject': subject, 'body': report_text, 'html': report} if self.to: ...
'Ctor. Parses the input query into the class as a pre-compiled query, allowing for a later call to Bind() to bind arguments as defined in the documentation. Args: query_string: properly formatted GQL query string. namespace: the namespace to use for this query. Raises: datastore_errors.BadQueryError: if the query is no...
def __init__(self, query_string, _app=None, _auth_domain=None, namespace=None):
self.__app = _app self.__namespace = namespace self.__auth_domain = _auth_domain self.__symbols = self.TOKENIZE_REGEX.findall(query_string) initial_error = None for backwards_compatibility_mode in xrange(len(self.RESERVED_KEYWORDS)): self.__InitializeParseState() self.__active_re...
'Bind the existing query to the argument list. Assumes that the input args are first positional, then a dictionary. So, if the query contains references to :1, :2 and :name, it is assumed that arguments are passed as (:1, :2, dict) where dict contains a mapping [name] -> value. Args: args: the arguments to bind to the ...
def Bind(self, args, keyword_args, cursor=None, end_cursor=None):
num_args = len(args) input_args = frozenset(xrange(num_args)) used_args = set() queries = [] enumerated_queries = self.EnumerateQueries(used_args, args, keyword_args) if enumerated_queries: query_count = len(enumerated_queries) else: query_count = 1 for _ in xrange(query_...
'Create a list of all multi-query filter combinations required. To satisfy multi-query requests ("IN" and "!=" filters), multiple queries may be required. This code will enumerate the power-set of all multi-query filters. Args: used_args: set of used positional parameters (output only variable used in reporting for unu...
def EnumerateQueries(self, used_args, args, keyword_args):
enumerated_queries = [] for ((identifier, condition), value_list) in self.__filters.iteritems(): for (operator, params) in value_list: value = self.__Operate(args, keyword_args, used_args, operator, params) self.__AddMultiQuery(identifier, condition, value, enumerated_queries) ...
'Query building error for type cast operations. Args: operator: the failed cast operation values: value list passed to the cast operator error_message: string to emit as part of the \'Cast Error\' string. Raises: BadQueryError and passes on an error message from the caller. Will raise BadQueryError on all calls.'
def __CastError(self, operator, values, error_message):
raise datastore_errors.BadQueryError(('Type Cast Error: unable to cast %r with operation %s (%s)' % (values, operator.upper(), error_message)))
'Return values[0] if it exists -- default for most where clauses.'
def __CastNop(self, values):
if (len(values) != 1): self.__CastError(values, 'nop', 'requires one and only one value') else: return values[0]
'Return the full list of values -- only useful for IN clause.'
def __CastList(self, values):
if values: return values else: return None
'Cast input values to Key() class using encoded string or tuple list.'
def __CastKey(self, values):
if (not (len(values) % 2)): return datastore_types.Key.from_path(_app=self.__app, namespace=self.__namespace, *values) elif ((len(values) == 1) and isinstance(values[0], basestring)): return datastore_types.Key(values[0]) else: self.__CastError('KEY', values, 'requires an even ...
'Cast input to GeoPt() class using 2 input parameters.'
def __CastGeoPt(self, values):
if (len(values) != 2): self.__CastError('GEOPT', values, 'requires 2 input parameters') return datastore_types.GeoPt(*values)
'Cast to User() class using the email address in values[0].'
def __CastUser(self, values):
if (len(values) != 1): self.__CastError('user', values, 'requires one and only one value') elif (values[0] is None): self.__CastError('user', values, 'must be non-null') else: return users.User(email=values[0], _auth_domain=self.__auth_domain)
'Simple helper function to create an str from possibly unicode strings. Args: value: input string (should pass as an instance of str or unicode).'
def __EncodeIfNeeded(self, value):
if isinstance(value, unicode): return value.encode('utf8') else: return value
'Cast DATE values (year/month/day) from input (to datetime.datetime). Casts DATE input values formulated as ISO string or time tuple inputs. Args: values: either a single string with ISO time representation or 3 integer valued date tuple (year, month, day). Returns: datetime.datetime value parsed from the input values....
def __CastDate(self, values):
if (len(values) == 1): value = self.__EncodeIfNeeded(values[0]) if isinstance(value, str): try: time_tuple = time.strptime(value, '%Y-%m-%d')[0:6] except ValueError as err: self.__CastError('DATE', values, err) else: self.__...
'Cast TIME values (hour/min/sec) from input (to datetime.datetime). Casts TIME input values formulated as ISO string or time tuple inputs. Args: values: either a single string with ISO time representation or 1-4 integer valued time tuple (hour), (hour, minute), (hour, minute, second), (hour, minute, second, microsec). ...
def __CastTime(self, values):
if (len(values) == 1): value = self.__EncodeIfNeeded(values[0]) if isinstance(value, str): try: time_tuple = time.strptime(value, '%H:%M:%S') except ValueError as err: self.__CastError('TIME', values, err) time_tuple = ((1970, 1, 1)...
'Cast DATETIME values (string or tuple) from input (to datetime.datetime). Casts DATETIME input values formulated as ISO string or datetime tuple inputs. Args: values: either a single string with ISO representation or 3-7 integer valued time tuple (year, month, day, ...). Returns: datetime.datetime value parsed from th...
def __CastDatetime(self, values):
if (len(values) == 1): value = self.__EncodeIfNeeded(values[0]) if isinstance(value, str): try: time_tuple = time.strptime(str(value), '%Y-%m-%d %H:%M:%S')[0:6] except ValueError as err: self.__CastError('DATETIME', values, err) else...
'Create a single output value from params using the operator string given. Args: args,keyword_args: arguments passed in for binding purposes (used in binding positional and keyword based arguments). used_args: set of numeric arguments accessed in this call. values are ints representing used zero-based positional argume...
def __Operate(self, args, keyword_args, used_args, operator, params):
if (not params): return None param_values = [] for param in params: if isinstance(param, Literal): value = param.Get() else: value = self.__GetParam(param, args, keyword_args, used_args=used_args) if isinstance(param, int): used_arg...
'Return whether or not this condition could require multiple queries.'
def __IsMultiQuery(self, condition):
return (condition.lower() in ('in', '!='))
'Get the specified parameter from the input arguments. If param is an index or named reference, args and keyword_args are used. If param is a cast operator tuple, will use __Operate to return the cast value. Args: param: represents either an id for a filter reference in the filter list (string or number) or a tuple (ca...
def __GetParam(self, param, args, keyword_args, used_args=None):
num_args = len(args) if isinstance(param, int): if (param <= num_args): return args[(param - 1)] else: raise datastore_errors.BadArgumentError(('Missing argument for bind, requires argument #%i, but only has %i args.' % (param, num_args)))...
'Helper function to add a multi-query to previously enumerated queries. Args: identifier: property being filtered by this condition condition: filter condition (e.g. !=,in) value: value being bound enumerated_queries: in/out list of already bound queries -> expanded list with the full enumeration required to satisfy th...
def __AddMultiQuery(self, identifier, condition, value, enumerated_queries):
if ((condition.lower() in ('!=', 'in')) and self._keys_only): raise datastore_errors.BadQueryError('Keys only queries do not support IN or != filters.') def CloneQueries(queries, n): 'Do a full copy of the queries and append to the end ...
'Add a filter condition to a query based on the inputs. Args: identifier: name of the property (or self.__ANCESTOR for ancestors) condition: test condition value: test value passed from the caller query: query to add the filter to'
def __AddFilterToQuery(self, identifier, condition, value, query):
if (identifier != self.__ANCESTOR): filter_condition = ('%s %s' % (identifier, condition)) logging.log(LOG_LEVEL, 'Setting filter on "%s" with value "%s"', filter_condition, value.__class__) datastore._AddOrAppend(query, filter_condition, value) else: logging...
'Runs this query. Similar to datastore.Query.Run. Assumes that limit == -1 or > 0 Args: args: arguments used to bind to references in the compiled query object. keyword_args: dictionary-based arguments (for named parameters). Returns: A list of results if a query count limit was passed. A result iterator if no limit wa...
def Run(self, *args, **keyword_args):
bind_results = self.Bind(args, keyword_args) offset = self.offset() if (self.__limit == (-1)): it = bind_results.Run() try: for _ in xrange(offset): it.next() except StopIteration: pass return it else: res = bind_results.Get...
'Return the compiled list of filters.'
def filters(self):
return self.__filters
'Return the datastore hint.'
def hint(self):
return self.__hint
'Return numerical result count limit.'
def limit(self):
return self.__limit
'Return numerical result offset.'
def offset(self):
if (self.__offset == (-1)): return 0 else: return self.__offset
'Return the result ordering list.'
def orderings(self):
return self.__orderings
'Returns True if this query returns Keys, False if it returns Entities.'
def is_keys_only(self):
return self._keys_only
'Returns the tuple of properties in the projection, or None.'
def projection(self):
return self.__projection
'Returns True if this query is marked as distinct.'
def is_distinct(self):
return self.__distinct
'Generic query error. Args: error_message: string to emit as part of the \'Parse Error\' string. Raises: BadQueryError and passes on an error message from the caller. Will raise BadQueryError on all calls to __Error()'
def __Error(self, error_message):
if (self.__next_symbol >= len(self.__symbols)): raise datastore_errors.BadQueryError(('Parse Error: %s at end of string' % error_message)) else: raise datastore_errors.BadQueryError(('Parse Error: %s at symbol %s' % (error_message, self.__symbols[self.__next_symb...
'Advance the symbol and return true iff the next symbol matches input.'
def __Accept(self, symbol_string):
if (self.__next_symbol < len(self.__symbols)): logging.log(LOG_LEVEL, ' DCTB %s', self.__symbols) logging.log(LOG_LEVEL, ' DCTB Expect: %s Got: %s', symbol_string, self.__symbols[self.__next_symbol].upper()) if (self.__symbols[self.__next_symbol].upper() == symbol_string): ...
'Require that the next symbol matches symbol_string, or emit an error. Args: symbol_string: next symbol expected by the caller Raises: BadQueryError if the next symbol doesn\'t match the parameter passed in.'
def __Expect(self, symbol_string):
if (not self.__Accept(symbol_string)): self.__Error(('Unexpected Symbol: %s' % symbol_string))
'Advance and return the symbol if the next symbol matches the regex. Args: regex: the compiled regular expression to attempt acceptance on. Returns: The first group in the expression to allow for convenient access to simple matches. Requires () around some objects in the regex. None if no match is found.'
def __AcceptRegex(self, regex):
if (self.__next_symbol < len(self.__symbols)): match_symbol = self.__symbols[self.__next_symbol] logging.log(LOG_LEVEL, ' DCTB accept %s on symbol %s', regex, match_symbol) match = regex.match(match_symbol) if match: self.__next_symbol += 1 if matc...
'Accept either a single semi-colon or an empty string. Returns: True Raises: BadQueryError if there are unconsumed symbols in the query.'
def __AcceptTerminal(self):
self.__Accept(';') if (self.__next_symbol < len(self.__symbols)): self.__Error('Expected no additional symbols') return True
'Consume the SELECT clause and everything that follows it. Assumes SELECT * to start. Transitions to a FROM clause. Returns: True if parsing completed okay.'
def __Select(self):
self.__Expect('SELECT') if (('DISTINCT' in self.__active_reserved_words) and self.__Accept('DISTINCT')): self.__distinct = True if (not self.__Accept('*')): props = [self.__ExpectIdentifier()] while self.__Accept(','): props.append(self.__ExpectIdentifier()) if (p...
'Consume the FROM clause. Assumes a single well formed entity in the clause. Assumes FROM <Entity Name> Transitions to a WHERE clause. Returns: True if parsing completed okay.'
def __From(self):
if self.__Accept('FROM'): self._kind = self.__ExpectIdentifier() return self.__Where()
'Consume the WHERE cluase. These can have some recursion because of the AND symbol. Returns: True if parsing the WHERE clause completed correctly, as well as all subsequent clauses'
def __Where(self):
if self.__Accept('WHERE'): return self.__FilterList() return self.__OrderBy()
'Consume the filter list (remainder of the WHERE clause).'
def __FilterList(self):
identifier = self.__Identifier() if (not identifier): self.__Error('Invalid WHERE Identifier') condition = self.__AcceptRegex(self.__conditions_regex) if (not condition): self.__Error('Invalid WHERE Condition') self.__CheckFilterSyntax(identifier, condition) if (not s...
'Read in a list of parameters from the tokens and return the list. Reads in a set of tokens by consuming symbols. If the returned list of values is not intended to be used within a list, only accepts literals, positional parameters, or named parameters. If the returned list of values is intended to be used within a lis...
def __GetValueList(self, values_intended_for_list=False):
params = [] while True: reference = self.__Reference() if reference: params.append(reference) else: literal = self.__Literal() if literal: params.append(literal) elif values_intended_for_list: type_cast = sel...
'Check that filter conditions are valid and throw errors if not. Args: identifier: identifier being used in comparison condition: string form of the comparison operator used in the filter'
def __CheckFilterSyntax(self, identifier, condition):
if (identifier.lower() == 'ancestor'): if (condition.lower() == 'is'): if self.__has_ancestor: self.__Error('Only one ANCESTOR IS" clause allowed') else: self.__Error('"IS" expected to follow "ANCESTOR"') elif (condition.lower() ...
'Add a filter with post-processing required. Args: identifier: property being compared. condition: comparison operation being used with the property (e.g. !=). operator: operation to perform on the parameters before adding the filter. parameters: list of bound parameters passed to \'operator\' before creating the filte...
def __AddProcessedParameterFilter(self, identifier, condition, operator, parameters):
if (parameters is None): return False if (parameters[0] is None): return False logging.log(LOG_LEVEL, 'Adding Filter %s %s %s', identifier, condition, repr(parameters)) filter_rule = (identifier, condition) if (identifier.lower() == 'ancestor'): self.__has_ancesto...
'Add a filter to the query being built (no post-processing on parameter). Args: identifier: identifier being used in comparison condition: string form of the comparison operator used in the filter parameter: ID of the reference being made or a value of type Literal Returns: True if the filter could be added. False othe...
def __AddSimpleFilter(self, identifier, condition, parameter):
return self.__AddProcessedParameterFilter(identifier, condition, 'nop', [parameter])
'Consume an identifier and return it. Returns: The identifier string. If quoted, the surrounding quotes are stripped.'
def __Identifier(self):
logging.log(LOG_LEVEL, 'Try Identifier') identifier = self.__AcceptRegex(self.__identifier_regex) if identifier: if (identifier.upper() in self.__active_reserved_words): self.__next_symbol -= 1 self.__Error('Identifier is a reserved keyword') else: ...
'Consume a parameter reference and return it. Consumes a reference to a positional parameter (:1) or a named parameter (:email). Only consumes a single reference (not lists). Returns: The name of the reference (integer for positional parameters or string for named parameters) to a bind-time parameter.'
def __Reference(self):
logging.log(LOG_LEVEL, 'Try Reference') reference = self.__AcceptRegex(self.__ordinal_regex) if reference: return int(reference) else: reference = self.__AcceptRegex(self.__named_regex) if reference: return reference return None
'Parse literals from our token list. Returns: The parsed literal from the input string (currently either a string, integer, or floating point value).'
def __Literal(self):
logging.log(LOG_LEVEL, 'Try Literal') literal = None try: literal = int(self.__symbols[self.__next_symbol]) except ValueError: pass else: self.__next_symbol += 1 if (literal is None): try: literal = float(self.__symbols[self.__next_symbol]) ...
'Check if the next operation is a type-cast and return the cast if so. Casting operators look like simple function calls on their parameters. This code returns the cast operator found and the list of parameters provided by the user to complete the cast operation. In the case of a list, we allow the call to __GetValueLi...
def __TypeCast(self, can_cast_list=True):
logging.log(LOG_LEVEL, 'Try Type Cast') cast_op = self.__AcceptRegex(self.__cast_regex) if (not cast_op): if (can_cast_list and self.__Accept('(')): cast_op = 'list' else: return None else: cast_op = cast_op.lower() self.__Expect('(') par...
'Consume the ORDER BY clause.'
def __OrderBy(self):
if self.__Accept('ORDER'): self.__Expect('BY') return self.__OrderList() return self.__Limit()
'Consume variables and sort order for ORDER BY clause.'
def __OrderList(self):
identifier = self.__Identifier() if identifier: if self.__Accept('DESC'): self.__orderings.append((identifier, datastore.Query.DESCENDING)) elif self.__Accept('ASC'): self.__orderings.append((identifier, datastore.Query.ASCENDING)) else: self.__orderin...
'Consume the LIMIT clause.'
def __Limit(self):
if self.__Accept('LIMIT'): maybe_limit = self.__AcceptRegex(self.__number_regex) if maybe_limit: if self.__Accept(','): self.__offset = int(maybe_limit) if (self.__offset < 0): self.__Error('Bad offset in LIMIT Value') ...
'Consume the OFFSET clause.'
def __Offset(self):
if self.__Accept('OFFSET'): if (self.__offset != (-1)): self.__Error('Offset already defined in LIMIT clause') offset = self.__AcceptRegex(self.__number_regex) if offset: self.__offset = int(offset) if (self.__offset < 0): se...
'Consume the HINT clause. Requires one of three options (mirroring the rest of the datastore): HINT ORDER_FIRST HINT ANCESTOR_FIRST HINT FILTER_FIRST Returns: True if the hint clause and later clauses all parsed okay'
def __Hint(self):
if self.__Accept('HINT'): if self.__Accept('ORDER_FIRST'): self.__hint = 'ORDER_FIRST' elif self.__Accept('FILTER_FIRST'): self.__hint = 'FILTER_FIRST' elif self.__Accept('ANCESTOR_FIRST'): self.__hint = 'ANCESTOR_FIRST' else: self.__Er...
'Return the value of the literal.'
def Get(self):
return self.__value
'Default behavior for POST requests to deferred handler.'
def run_from_request(self):
if ('X-AppEngine-TaskName' not in self.request.headers): logging.critical('Detected an attempted XSRF attack. The header "X-AppEngine-Taskname" was not set.') self.response.set_status(403) return headers = [('%s:%s' % (k, v)) for (k, v) in self.request.heade...
'Activate the testbed. Invoking this method will also assign default values to environment variables required by App Engine services such as os.environ[\'APPLICATION_ID\']. You can set custom values with setup_env().'
def activate(self):
self._orig_env = dict(os.environ) self.setup_env() self._original_stub_map = apiproxy_stub_map.apiproxy self._test_stub_map = apiproxy_stub_map.APIProxyStubMap() internal_map = self._original_stub_map._APIProxyStubMap__stub_map self._test_stub_map._APIProxyStubMap__stub_map = dict(internal_map) ...
'Deactivate the testbed. This method will restore the API proxy and environment variables to the state before activate() was called. Raises: NotActivatedError: If called before activate() was called.'
def deactivate(self):
if (not self._activated): raise NotActivatedError('The testbed is not activated.') for (service_name, deactivate_callback) in self._enabled_stubs.iteritems(): if deactivate_callback: deactivate_callback(self._test_stub_map.GetStub(service_name)) apiproxy_stub_map.apip...
'Set up environment variables. Sets default and custom environment variables. By default, all the items in DEFAULT_ENVIRONMENT will be created without being specified. To set a value other than the default, or to pass a custom environment variable, pass a corresponding keyword argument: testbed_instance.setup_env() ...
def setup_env(self, overwrite=False, **kwargs):
merged_kwargs = {} for (key, value) in kwargs.iteritems(): if (key == 'app_id'): key = 'APPLICATION_ID' merged_kwargs[key.upper()] = value if (not overwrite): for (key, value) in DEFAULT_ENVIRONMENT.iteritems(): if (key not in merged_kwargs): m...
'Register a service stub. Args: service_name: The name of the service the stub represents. stub: The stub. deactivate_callback: An optional function to call when deactivating the stub. Must accept the stub as the only argument. Raises: NotActivatedError: The testbed is not activated.'
def _register_stub(self, service_name, stub, deactivate_callback=None):
self._disable_stub(service_name) self._test_stub_map.RegisterStub(service_name, stub) self._enabled_stubs[service_name] = deactivate_callback
'Disable a service stub. Args: service_name: The name of the service to disable. Raises: NotActivatedError: The testbed is not activated.'
def _disable_stub(self, service_name):
if (not self._activated): raise NotActivatedError('The testbed is not activated.') deactivate_callback = self._enabled_stubs.pop(service_name, None) if deactivate_callback: deactivate_callback(self._test_stub_map.GetStub(service_name)) if (service_name in self._test_stub_map....
'Get the stub for a service. Args: service_name: The name of the service. Returns: The stub for \'service_name\'. Raises: NotActivatedError: The testbed is not activated. StubNotSupportedError: The service is not supported by testbed. StubNotEnabledError: The service stub has not been enabled.'
def get_stub(self, service_name):
if (not self._activated): raise NotActivatedError('The testbed is not activated.') if (service_name not in SUPPORTED_SERVICES): msg = ('The "%s" service is not supported by testbed' % service_name) raise StubNotSupportedError(msg) if (service_name not...
'Enable the app identity stub. Args: enable: True, if the fake service should be enabled, False if real service should be disabled.'
def init_app_identity_stub(self, enable=True):
if (not enable): self._disable_stub(APP_IDENTITY_SERVICE_NAME) return stub = app_identity_stub.AppIdentityServiceStub() self._register_stub(APP_IDENTITY_SERVICE_NAME, stub)
'Creates a blob storage for stubs if needed.'
def _get_blob_storage(self):
if (self._blob_storage is None): self._blob_storage = dict_blob_storage.DictBlobStorage() return self._blob_storage
'Enable the blobstore stub. Args: enable: True, if the fake service should be enabled, False if real service should be disabled.'
def init_blobstore_stub(self, enable=True):
if (not enable): self._disable_stub(BLOBSTORE_SERVICE_NAME) return stub = blobstore_stub.BlobstoreServiceStub(self._get_blob_storage()) self._register_stub(BLOBSTORE_SERVICE_NAME, stub)
'Enable the capability stub. Args: enable: True, if the fake service should be enabled, False if real service should be disabled.'
def init_capability_stub(self, enable=True):
if (not enable): self._disable_stub(CAPABILITY_SERVICE_NAME) return stub = capability_stub.CapabilityServiceStub() self._register_stub(CAPABILITY_SERVICE_NAME, stub)
'Enable the channel stub. Args: enable: True, if the fake service should be enabled, False if real service should be disabled.'
def init_channel_stub(self, enable=True):
if (not enable): self._disable_stub(CHANNEL_SERVICE_NAME) return stub = channel_service_stub.ChannelServiceStub() self._register_stub(CHANNEL_SERVICE_NAME, stub)
'Enable the datastore stub. The \'datastore_file\' argument can be the path to an existing datastore file, or None (default) to use an in-memory datastore that is initially empty. If you use the sqlite stub and have \'datastore_file\' defined, changes you apply in a test will be written to the file. If you use the de...
def init_datastore_v3_stub(self, enable=True, datastore_file=None, use_sqlite=False, auto_id_policy=AUTO_ID_POLICY_SEQUENTIAL, **stub_kw_args):
if (not enable): self._disable_stub(DATASTORE_SERVICE_NAME) return if use_sqlite: if (datastore_sqlite_stub is None): raise StubNotSupportedError('The sqlite stub is not supported in production.') stub = datastore_sqlite_stub.DatastoreSqliteStub(o...
'Enable files api stub. Args: enable: True, if the fake service should be enabled, False if real service should be disabled.'
def init_files_stub(self, enable=True):
if (not enable): self._disable_stub(FILES_SERVICE_NAME) return stub = file_service_stub.FileServiceStub(self._get_blob_storage()) self._register_stub(FILES_SERVICE_NAME, stub)
'Enable the images stub. The images service stub is only available in dev_appserver because it uses the PIL library. Args: enable: True, if the fake service should be enabled, False if real service should be disabled.'
def init_images_stub(self, enable=True):
if (not enable): self._disable_stub(IMAGES_SERVICE_NAME) return if (images_stub is None): msg = 'Could not initialize images API; you are likely missing the Python "PIL" module.' raise StubNotSupportedError(msg) stub = images_stub.ImagesSer...
'Enable the log service stub. Args: enable: True, if the fake service should be enabled, False if real service should be disabled. Raises: StubNotSupportedError: The logservice stub is unvailable.'
def init_logservice_stub(self, enable=True):
if (not enable): self._disable_stub(LOG_SERVICE_NAME) return if (logservice_stub is None): raise StubNotSupportedError('The logservice stub is not supported in production.') stub = logservice_stub.LogServiceStub() self._register_stub(LOG_SERVICE_NAME, stub)