desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns a cached Model instance given the entity key if available. Args: key: Key instance. Returns: A Model instance if the key exists in the cache.'
def _load_from_cache_if_available(self, key):
if (key in self._cache): entity = self._cache[key] if ((entity is None) or (entity._key == key)): raise tasklets.Return(entity)
'Return a Model instance given the entity key. It will use the context cache if the cache policy for the given key is enabled. Args: key: Key instance. **ctx_options: Context options. Returns: A Model instance if the key exists in the datastore; None otherwise.'
@tasklets.tasklet def get(self, key, **ctx_options):
options = _make_ctx_options(ctx_options) use_cache = self._use_cache(key, options) if use_cache: self._load_from_cache_if_available(key) use_datastore = self._use_datastore(key, options) if (use_datastore and isinstance(self._conn, datastore_rpc.TransactionalConnection)): use_memcach...
'Return whether a transaction is currently active.'
def in_transaction(self):
return isinstance(self._conn, datastore_rpc.TransactionalConnection)
'Call a callback upon successful commit of a transaction. If not in a transaction, the callback is called immediately. In a transaction, multiple callbacks may be registered and will be called once the transaction commits, in the order in which they were registered. If the transaction fails, the callbacks will not be ...
def call_on_commit(self, callback):
if (not self.in_transaction()): callback() else: self._on_commit_queue.append(callback)
'Clears the in-memory cache. NOTE: This does not affect memcache.'
def clear_cache(self):
self._cache.clear()
'An auto-batching wrapper for memcache.get() or .get_multi(). Args: key: Key to set. This must be a string; no prefix is applied. for_cas: If True, request and store CAS ids on the Context. namespace: Optional namespace. deadline: Optional deadline for the RPC. Returns: A Future (!) whose return value is the value ret...
def memcache_get(self, key, for_cas=False, namespace=None, use_cache=False, deadline=None):
if (not isinstance(key, basestring)): raise TypeError(('key must be a string; received %r' % key)) if (not isinstance(for_cas, bool)): raise TypeError(('for_cas must be a bool; received %r' % for_cas)) if (namespace is None): namespace = namespace_...
'Kind name override.'
@classmethod def _get_kind(cls):
return cls.STORED_KIND_NAME
'Called by Django before deciding which view to execute.'
def process_request(self, unused_request):
tasklets._state.clear_all_pending() ctx = tasklets.make_default_context() tasklets.set_context(ctx)
'Called by Django just before returning a response.'
def process_response(self, request, response):
self._finish() return response
'Called by Django when a view raises an exception.'
def process_exception(self, unused_request, unused_exception):
self._finish() return None
'Override this to match the datastore entities written by Blobstore.'
@classmethod def _get_kind(cls):
return BLOB_INFO_KIND
'Retrieve a BlobInfo by key. Args: blob_key: A blob key. This may be a str, unicode or BlobKey instance. **ctx_options: Context options for Model().get_by_id(). Returns: A BlobInfo entity associated with the provided key, If there was no such entity, returns None.'
@classmethod def get(cls, blob_key, **ctx_options):
fut = cls.get_async(blob_key, **ctx_options) return fut.get_result()
'Async version of get().'
@classmethod def get_async(cls, blob_key, **ctx_options):
if (not isinstance(blob_key, (BlobKey, basestring))): raise TypeError(('Expected blob key, got %r' % (blob_key,))) if ('parent' in ctx_options): raise TypeError('Parent is not supported') return cls.get_by_id_async(str(blob_key), **ctx_options)
'Multi-key version of get(). Args: blob_keys: A list of blob keys. **ctx_options: Context options for Model().get_by_id(). Returns: A list whose items are each either a BlobInfo entity or None.'
@classmethod def get_multi(cls, blob_keys, **ctx_options):
futs = cls.get_multi_async(blob_keys, **ctx_options) return [fut.get_result() for fut in futs]
'Async version of get_multi().'
@classmethod def get_multi_async(cls, blob_keys, **ctx_options):
for blob_key in blob_keys: if (not isinstance(blob_key, (BlobKey, basestring))): raise TypeError(('Expected blob key, got %r' % (blob_key,))) if ('parent' in ctx_options): raise TypeError('Parent is not supported') blob_key_strs = map(str, blob_keys) keys...
'Cheap way to make BlobInfo entities read-only.'
def _put_async(self, **ctx_options):
raise TypeError('BlobInfo is read-only')
'Get key for blob. Returns: BlobKey instance that identifies this blob.'
def key(self):
return BlobKey(self._key.id())
'Permanently delete this blob from Blobstore. Args: **options: Options for create_rpc().'
def delete(self, **options):
fut = delete_async(self.key(), **options) fut.get_result()
'Async version of delete().'
def delete_async(self, **options):
return delete_async(self.key(), **options)
'Returns a BlobReader for this blob. Args: *args, **kwargs: Passed to BlobReader constructor. Returns: A BlobReader instance.'
def open(self, *args, **kwds):
return BlobReader(self, *args, **kwds)
'Fills the internal buffer. Args: size: Number of bytes to read. Will be clamped to [self.__buffer_size, MAX_BLOB_FETCH_SIZE].'
def __fill_buffer(self, size=0):
read_size = min(max(size, self.__buffer_size), MAX_BLOB_FETCH_SIZE) self.__buffer = fetch_data(self.__blob_key, self.__position, ((self.__position + read_size) - 1)) self.__buffer_position = 0 self.__eof = (len(self.__buffer) < read_size)
'Returns the BlobInfo for this file.'
@property def blob_info(self):
if (not self.__blob_info): self.__blob_info = BlobInfo.get(self.__blob_key) return self.__blob_info
'GET request handler. Typically the arguments are passed from the matching groups in the URL pattern passed to WSGIApplication(). Args: prefix: The zipfilename without the .zip suffix. name: The name within the zipfile.'
def get(self, prefix, name):
self.ServeFromZipFile((prefix + '.zip'), name)
'Helper for the GET request handler. This serves the contents of file \'name\' from zipfile \'zipfilename\', logging a message and returning a 404 response if either the zipfile cannot be opened or the named file cannot be read from it. Args: zipfilename: The name of the zipfile. name: The name within the zipfile.'
def ServeFromZipFile(self, zipfilename, name):
zipfile_object = self.zipfile_cache.get(zipfilename) if (zipfile_object is None): try: zipfile_object = zipfile.ZipFile(zipfilename) except (IOError, RuntimeError, zipfile.BadZipfile) as err: logging.error("Can't open zipfile %s: %s", zipfilename, err) ...
'Helper to set the caching headers. Override this to customize the headers beyond setting MAX_AGE.'
def SetCachingHeaders(self):
max_age = self.MAX_AGE self.response.headers['Expires'] = email.Utils.formatdate((time.time() + max_age), usegmt=True) cache_control = [] if self.PUBLIC: cache_control.append('public') cache_control.append(('max-age=%d' % max_age)) self.response.headers['Cache-Control'] = ', '.join(ca...
'Initializer.'
def __init__(self):
self.method = 'GET' self.scheme = 'http' self.host = 'foo.com' self._path = '/start' self.params = {} self.params_list = [] self.headers = MockHeaders() self.body = '' self.url = '' self.path_qs = '' self.query_string = '' self.update_properties() self.environ = {}
'Set full URL for the request. Parses the URL and sets path, scheme, host and parameters correctly.'
def set_url(self, url):
o = urlparse.urlparse(url) self.scheme = (o.scheme or self.scheme) self.host = (o.netloc or self.host) self.path = o.path self.update_properties() for (name, value) in urlparse.parse_qs(o.query).items(): assert (len(value) == 1) self.set(name, value[0])
'Looks up the value of a query parameter. Args: argument_name: The query parameter key as a string. default_value: The default query parameter value as a string if it was not supplied. allow_multiple: return a list of values with the given name Returns: If allow_multiple is False (which it is by default), we return the...
def get(self, argument_name, default_value='', allow_multiple=False):
if (argument_name not in self.params): if allow_multiple: return [] return default_value if allow_multiple: return list(self.params[argument_name]) if isinstance(self.params[argument_name], list): return self.params[argument_name][0] return self.params[argumen...
'Returns a list of query parameters with the given name. Args: argument_name: the name of the query argument. Returns: A (possibly empty) list of values.'
def get_all(self, argument_name):
if (argument_name in self.params): if isinstance(self.params[argument_name], list): return self.params[argument_name] else: return [self.params[argument_name]] return []
'Parses the given int argument, limiting it to the given range. Args: name: the name of the argument min_value: the minimum int value of the argument (if any) max_value: the maximum int value of the argument (if any) default: the default value of the argument if it is not given Returns: An int within the given range fo...
def get_range(self, name, min_value=None, max_value=None, default=0):
value = self.get(name, default) if (value is None): return value try: value = int(value) except ValueError: value = default if (value is not None): if (max_value is not None): value = min(value, max_value) if (min_value is not None): va...
'Sets the value of a query parameter. Args: argument_name: The string name of the query parameter. value: The string value of the query parameter. Pass None to remove query parameter.'
def set(self, argument_name, value):
self.params_list = filter((lambda p: (p[0] != argument_name)), self.params_list) if (value is not None): self.params[argument_name] = value if (type(value) == list): for v in value: self.params_list.append((argument_name, v)) else: self.params_list...
'Return an absolute (!) URL by combining self.path with other_url.'
def relative_url(self, other_url, to_application=False):
url = ('%s://%s/' % (self.scheme, self.host)) return urlparse.urljoin(url, other_url)
'Update url, path_qs property to be in sync with path and params.'
def update_properties(self):
self.path_qs = self._path self.query_string = '' for param_value_pair in self.params_list: if self.query_string: self.query_string += '&' self.query_string += ((param_value_pair[0] + '=') + param_value_pair[1]) if self.query_string: self.path_qs += ('?' + self.query_s...
'Gets the set of argument names used in this request.'
def arguments(self):
return list(set((p[0] for p in self.params_list)))
'Sets the value of status. Args: status: HTTP status code. message: HTTP status message.'
def set_status(self, status, message=None):
self.status = status if message: self.status_message = message
'Indicates whether the response was an error response.'
def has_error(self):
return (self.status >= 400)
'Clears all data written to self.out.'
def clear(self):
self.out.seek(0) self.out.truncate(0)
'Send a blob-response based on a blob_key. Sets the correct response header for serving a blob. If BlobInfo is provided and no content_type specified, will set request content type to BlobInfo\'s content type. Args: blob_key_or_info: BlobKey or BlobInfo record to serve. content_type: Content-type to override when know...
def send_blob(self, blob_key_or_info, content_type=None, save_as=None, start=None, end=None, **kwargs):
if (set(kwargs) - _SEND_BLOB_PARAMETERS): invalid_keywords = [] for keyword in kwargs: if (keyword not in _SEND_BLOB_PARAMETERS): invalid_keywords.append(keyword) if (len(invalid_keywords) == 1): raise TypeError(('send_blob got unexpected keyw...
'Get range from header if it exists. A range header of "bytes: 0-100" would return (0, 100). Returns: Tuple (start, end): start: Start index. None if there is None. end: End index (inclusive). None if there is None. None if there is no request header. Raises: UnsupportedRangeFormatError: If the range format in the he...
def get_range(self):
range_header = self.request.headers.get('range', None) if (range_header is None): return None parsed_range = _parse_bytes(range_header) if (parsed_range is None): raise RangeFormatError(('Invalid range header: %s' % range_header)) (units, ranges) = parsed_range if (len(r...
'Get uploads sent to this handler. Args: field_name: Only select uploads that were sent as a specific field. Returns: A list of BlobInfo records corresponding to each upload. Empty list if there are no blob-info records for field_name.'
def get_uploads(self, field_name=None):
if (self.__uploads is None): self.__uploads = collections.defaultdict(list) for (key, value) in self.request.params.items(): if isinstance(value, cgi.FieldStorage): if ('blob-key' in value.type_options): self.__uploads[key].append(blobstore.parse_blob_...
'Get the file infos associated to the uploads sent to this handler. Args: field_name: Only select uploads that were sent as a specific field. Specify None to select all the uploads. Returns: A list of FileInfo records corresponding to each upload. Empty list if there are no FileInfo records for field_name.'
def get_file_infos(self, field_name=None):
if (self.__file_infos is None): self.__file_infos = collections.defaultdict(list) for (key, value) in self.request.params.items(): if isinstance(value, cgi.FieldStorage): if ('blob-key' in value.type_options): self.__file_infos[key].append(blobstore.pa...
'Transforms body to email request.'
def post(self):
self.receive(mail.InboundEmailMessage(self.request.body))
'Receive an email message. Override this method to implement an email receiver. Args: mail_message: InboundEmailMessage instance representing received email.'
def receive(self, mail_message):
pass
'Convenience method to map handler class to application. Returns: Mapping from email URL to inbound mail handler class.'
@classmethod def mapping(cls):
return (MAIL_HANDLER_URL_PATTERN, cls)
'Transforms POST body to bounce request.'
def post(self):
self.receive(BounceNotification(self.request.POST))
'Convenience method to map handler class to application. Returns: Mapping from bounce URL to bounce notification handler class.'
@classmethod def mapping(cls):
return (BOUNCE_NOTIFICATION_HANDLER_URL_PATH, cls)
'Constructs a new BounceNotification from an HTTP request. Properties: original: a dict describing the message that caused the bounce. notification: a dict describing the bounce itself. original_raw_message: the raw message that caused the bounce. The \'original\' and \'notification\' dicts contain the following keys: ...
def __init__(self, post_vars):
try: self.__original = {} self.__notification = {} for field in ['to', 'from', 'subject', 'text']: self.__original[field] = post_vars[('original-' + field)] self.__notification[field] = post_vars[('notification-' + field)] self.__original_raw_message = mail.In...
'Constructs a Request object from a WSGI environment. If the charset isn\'t specified in the Content-Type header, defaults to UTF-8. Args: environ: A WSGI-compliant environment dictionary.'
def __init__(self, environ):
match = _CHARSET_RE.search(environ.get('CONTENT_TYPE', '')) if match: charset = match.group(1).lower() else: charset = 'utf-8' webob.Request.__init__(self, environ, charset=charset, unicode_errors='ignore', decode_param_names=True)
'Returns the query or POST argument with the given name. We parse the query string and POST payload lazily, so this will be a slower operation on the first call. Args: argument_name: the name of the query or POST argument default_value: the value to return if the given argument is not present allow_multiple: return a l...
def get(self, argument_name, default_value='', allow_multiple=False):
param_value = self.get_all(argument_name) if allow_multiple: logging.warning('allow_multiple is a deprecated param, please use the Request.get_all() method instead.') if (len(param_value) > 0): if allow_multiple: return param_value return par...
'Returns a list of query or POST arguments with the given name. We parse the query string and POST payload lazily, so this will be a slower operation on the first call. Args: argument_name: the name of the query or POST argument default_value: the value to return if the given argument is not present, None may not be us...
def get_all(self, argument_name, default_value=None):
if self.charset: argument_name = argument_name.encode(self.charset) if (default_value is None): default_value = [] param_value = self.params.getall(argument_name) if ((param_value is None) or (len(param_value) == 0)): return default_value for i in xrange(len(param_value)): ...
'Returns a list of the arguments provided in the query and/or POST. The return value is a list of strings.'
def arguments(self):
return list(set(self.params.keys()))
'Parses the given int argument, limiting it to the given range. Args: name: the name of the argument min_value: the minimum int value of the argument (if any) max_value: the maximum int value of the argument (if any) default: the default value of the argument if it is not given Returns: An int within the given range fo...
def get_range(self, name, min_value=None, max_value=None, default=0):
value = self.get(name, default) if (value is None): return value try: value = int(value) except ValueError: value = default if (value is not None): if (max_value is not None): value = min(value, max_value) if (min_value is not None): va...
'Constructs a response with the default settings.'
def __init__(self):
self.out = StringIO.StringIO() self.__wsgi_headers = [] self.headers = wsgiref.headers.Headers(self.__wsgi_headers) self.headers['Content-Type'] = 'text/html; charset=utf-8' self.headers['Cache-Control'] = 'no-cache' self.set_status(200)
'Returns current request status code.'
@property def status(self):
return self.__status[0]
'Returns current request status message.'
@property def status_message(self):
return self.__status[1]
'Sets the HTTP status code of this response. Args: message: the HTTP status string to use If no status string is given, we use the default from the HTTP/1.1 specification.'
def set_status(self, code, message=None):
if (not message): message = Response.http_status_message(code) self.__status = (code, message)
'Indicates whether the response was an error response.'
def has_error(self):
return (self.__status[0] >= 400)
'Clears all data written to the output stream so that it is empty.'
def clear(self):
self.out.seek(0) self.out.truncate(0)
'Writes this response using WSGI semantics with the given WSGI function. Args: start_response: the WSGI-compatible start_response function'
def wsgi_write(self, start_response):
body = self.out.getvalue() if isinstance(body, unicode): body = body.encode('utf-8') elif self.headers.get('Content-Type', '').endswith('; charset=utf-8'): try: body.decode('utf-8') except UnicodeError as e: logging.warning('Response written is not...
'Returns the default HTTP status message for the given code. Args: code: the HTTP code for which we want a message'
def http_status_message(code):
if (not Response.__HTTP_STATUS_MESSAGES.has_key(code)): raise Error(('Invalid HTTP status code: %d' % code)) return Response.__HTTP_STATUS_MESSAGES[code]
'Initializes this request handler with the given Request and Response.'
def initialize(self, request, response):
self.request = request self.response = response
'Handler method for GET requests.'
def get(self, *args):
self.error(405)
'Handler method for POST requests.'
def post(self, *args):
self.error(405)
'Handler method for HEAD requests.'
def head(self, *args):
self.error(405)
'Handler method for OPTIONS requests.'
def options(self, *args):
self.error(405)
'Handler method for PUT requests.'
def put(self, *args):
self.error(405)
'Handler method for DELETE requests.'
def delete(self, *args):
self.error(405)
'Handler method for TRACE requests.'
def trace(self, *args):
self.error(405)
'Clears the response output stream and sets the given HTTP error code. Args: code: the HTTP status error code (e.g., 501)'
def error(self, code):
self.response.set_status(code) self.response.clear()
'Issues an HTTP redirect to the given relative URL. Args: uri: a relative or absolute URI (e.g., \'../flowers.html\') permanent: if true, we use a 301 redirect instead of a 302 redirect'
def redirect(self, uri, permanent=False):
if permanent: self.response.set_status(301) else: self.response.set_status(302) absolute_url = urlparse.urljoin(self.request.uri, uri) self.response.headers['Location'] = str(absolute_url) self.response.clear()
'Called if this handler throws an exception during execution. The default behavior is to call self.error(500) and print a stack trace if debug_mode is True. Args: exception: the exception that was thrown debug_mode: True if the web application is running in debug mode'
def handle_exception(self, exception, debug_mode):
self.error(500) logging.exception(exception) if debug_mode: lines = ''.join(traceback.format_exception(*sys.exc_info())) self.response.clear() self.response.out.write(('<pre>%s</pre>' % cgi.escape(lines, quote=True)))
'Create new request handler factory. Use factory method to create reusable request handlers that just require a few configuration parameters to construct. Also useful for injecting shared state between multiple request handler instances without relying on global variables. For example, to create a set of post handler...
@classmethod def new_factory(cls, *args, **kwargs):
def new_instance(): return cls(*args, **kwargs) new_instance.__name__ = (cls.__name__ + 'Factory') return new_instance
'Returns the url for the given handler. The default implementation uses the patterns passed to the active WSGIApplication to create a url. However, it is different from Django\'s urlresolvers.reverse() in the following ways: - It does not try to resolve handlers via module loading - It does not support named arguments ...
@classmethod def get_url(cls, *args, **kargs):
app = WSGIApplication.active_instance pattern_map = app._pattern_map implicit_args = kargs.get('implicit_args', ()) if (implicit_args == True): implicit_args = app.current_request_args min_params = len(args) for pattern_tuple in pattern_map.get(cls, ()): num_params_in_pattern = p...
'Constructor. Do not use directly. Configure using new_factory method. Args: path: Path to redirect to. permanent: if true, we use a 301 redirect instead of a 302 redirect.'
def __init__(self, path, permanent=False):
self.path = path self.permanent = permanent
'Initializes this application with the given URL mapping. Args: url_mapping: list of (URI regular expression, RequestHandler) pairs (e.g., [(\'/\', ReqHan)]) debug: if true, we send Python stack traces to the browser on errors'
def __init__(self, url_mapping, debug=False):
self._init_url_mappings(url_mapping) self.__debug = debug WSGIApplication.active_instance = self self.current_request_args = ()
'Called by WSGI when a request comes in.'
def __call__(self, environ, start_response):
request = self.REQUEST_CLASS(environ) response = self.RESPONSE_CLASS() WSGIApplication.active_instance = self handler = None groups = () for (regexp, handler_class) in self._url_mapping: match = regexp.match(request.path) if match: try: handler = handl...
'Initializes the maps needed for mapping urls to handlers and handlers to urls. Args: handler_tuples: list of (URI, RequestHandler) pairs.'
def _init_url_mappings(self, handler_tuples):
handler_map = {} pattern_map = {} url_mapping = [] for (regexp, handler) in handler_tuples: try: handler_name = handler.__name__ except AttributeError: pass else: handler_map[handler_name] = handler if (not regexp.startswith('^')): ...
'Returns the handler given the handler\'s name. This uses the application\'s url mapping. Args: handler_name: The __name__ of a handler to return. Returns: The handler with the given name. Raises: KeyError: If the handler name is not found in the parent application.'
def get_registered_handler_by_name(self, handler_name):
try: return self._handler_map[handler_name] except: logging.error('Handler does not map to any urls: %s', handler_name) raise
'Called when a message is sent to the XMPP bot. Args: message: Message: The message that was sent by the user.'
def message_received(self, message):
raise NotImplementedError()
'Called if this handler throws an exception during execution. Args: exception: the exception that was thrown debug_mode: True if the web application is running in debug mode'
def handle_exception(self, exception, debug_mode):
super(BaseHandler, self).handle_exception(exception, debug_mode) if self.xmpp_message: self.xmpp_message.reply('Oops. Something went wrong.')
'Called when an unknown command is sent to the XMPP bot. Args: message: Message: The message that was sent by the user.'
def unhandled_command(self, message):
message.reply('Unknown command')
'Called when a message not prefixed by a /command is sent to the XMPP bot. Args: message: Message: The message that was sent by the user.'
def text_message(self, message):
pass
'Called when a message is sent to the XMPP bot. Args: message: Message: The message that was sent by the user.'
def message_received(self, message):
if message.command: handler_name = ('%s_command' % (message.command,)) handler = getattr(self, handler_name, None) if handler: handler(message) else: self.unhandled_command(message) else: self.text_message(message)
'Initialize parameters for histograms. E.g., start = 10, and exponent = 2 will bin data using intervals [0, 10], [11, 20], [21, 40], and so on. Args: start: upper bound of first interval exponent: ratio of upper bounds of two consecutive intervals.'
def __init__(self, start, exponent):
self.start = start self.exponent = exponent
'Compute counts of data items in various bins. Args: data: sorted list of integer or long data items. Returns: A list, with each element being count of data items in each bin'
def Bin(self, data):
bincounts = [] numbins = (self._BinIndex(data[(-1)]) + 1) for bin_index in range(numbins): bincounts.append(0) for item in data: bin_index = self._BinIndex(item) bincounts[bin_index] += 1 return bincounts
'Returns the upper bounds of intervals under exponential binning. E.g., if intervals are [0, 10], [11, 20], [21, 40], [41, 80], this function returns the list [10, 20, 40, 80]. Args: numbins: Number of bins. Returns: A list which contains upper bounds of each interval range.'
def Intervals(self, numbins):
if (numbins < 1): return [] intervals = [self.start] for _ in range(1, numbins): intervals.append((intervals[(-1)] * self.exponent)) return intervals
'Get bin to which item belongs. E.g., if intervals are [0, 10], [10, 20], [20, 40], [40, 80], _BinIndex(25) is 2, and _BinIndex(50) is 3. Bin numbers are 0-based. Args: item: data item Returns: bin to which item belongs, assuming 0-based binning.'
def _BinIndex(self, item):
if (item <= self.start): return 0 else: itembin = math.ceil(math.log((float(item) / self.start), self.exponent)) return int(itembin)
'Encodes data for drill page in JSON for UI. Returns: drill_json: A dictionary representation of the class with attributes encoded into JSON as necessary for the UI.'
def _ToJsonDrill(self):
drill_json = dict(self.__dict__) drill_json['rpcsummaries'] = [(l, s.requests, s.calls, json.dumps(s, cls=_RPCSummaryEncoder)) for (l, s) in self.rpcsummaries] drill_json['groupcounts'] = [(k, len(v), json.dumps(v)) for (k, v) in self.groupcounts] drill_json['entitycounts'] = [(k, len(v), json.dumps(v))...
'Arranges entity/entity group access counts by their kind. Args: obj: an object whose JSON encoding is desired. Returns: JSON encoding of obj.'
def default(self, obj):
if (not isinstance(obj, RPCSummary)): return json.JSONEncoder.default(self, obj) return obj.__dict__
'Constructor.'
def __init__(self):
self.hascontents = False self.filename = None self.mtime = None self.recordlist = []
'Reset and delete cache contents.'
def Reset(self):
self.hascontents = False self.filename = None self.mtime = None self.recordlist = []
'Check whether data from a file is cached. Args: source: name of file being read mtime: last modification time of file being read Returns: A boolean: true if cached, false otherwise.'
def IsCached(self, source, mtime):
if (not self.hascontents): return False if ((self.filename == source) and (self.mtime == mtime)): return True else: return False
'Insert records in cache. Args: source: name of file whose data is being cached. mtime: last modification time of file being cached. recordlist: list of StatsProto instances retrieved from file in reverse chronological order (i.e. most recent first).'
def Insert(self, source, mtime, recordlist):
self.hascontents = True self.filename = source self.mtime = mtime self.recordlist = recordlist
'Set filtering criteria. Args: url: consider only requests corresponding to this URL. starttime: consider only records recorded with timestamp (in seconds) higher than this value. Timestamps are measured from start of recording of entire data source. endtime: consider only records recorded with timestamp (in seconds) l...
def __init__(self, url=None, starttime=None, endtime=None, latency_lower=None, latency_upper=None):
self.url = url if starttime: self.starttime = int(starttime) if endtime: self.endtime = int(endtime) if latency_lower: self.latency_lower = int(latency_lower) if latency_upper: self.latency_upper = int(latency_upper) logging.info('Filtering requests: url: ...
'Check if record meets filtering criteria. Args: url: path of that http request (after normalization) timestamp: timestamp of record latency: latency of request that record pertains to. Returns: Boolean which is True if the record matches filtering criteria and false otherwise.'
def Match(self, url, timestamp, latency):
if self.url: if (url != self.url): return False if self.starttime: if (timestamp < self.starttime): return False if self.endtime: if (timestamp > self.endtime): return False if self.latency_lower: if (latency < self.latency_lower): ...
'Returns subset of records that meet filtering crtieria. While navigating the tool, developers may wish to focus on a certain subset of records that meet desired filters. Currently, the supported filters are (i) by time of recording; and (ii) request latency. Filter information is parsed from request arguments. Args: r...
def FilterRecords(self, recordlist, recording_starttime):
url = self.request.get('url') latency_lower = self.request.get('latency_lower') latency_upper = self.request.get('latency_upper') starttime = self.request.get('starttime') endtime = self.request.get('endtime') filter_condition = Filter(url=url, starttime=starttime, endtime=endtime, latency_lower...
'Rendering main page of analysis page. Args: urlstatsdict: A dictionary with keys being URL paths, and values being URLStat objects. source: Source of Appstats data. Either filename if being read from a file or MEMCACHE if being read from memcache. recording_starttime: Timestamp when recording of data starts expressed ...
def RenderMain(self, urlstatsdict, source, recording_starttime):
(resptime_byfreq, intervals) = process.URLFreqRespTime(urlstatsdict) data = {'resptime_byfreq': resptime_byfreq, 'intervals': intervals, 'source': source, 'recordingstart': time.asctime(time.gmtime(recording_starttime))} path = os.path.join(self.dirname, 'templates/main.html') self.response.out.write(te...
'Rendering analysis page that drills into URL. Args: url: URL that is being drilled into. urlstatsdict: A dictionary with keys being URL paths, and values being URLStat objects. recording_starttime: Timestamp when recording of data starts expressed in seconds. This is the timestamp of the earliest recorded Appstats dat...
def RenderDrill(self, url, urlstatsdict, recording_starttime, source, filter_condition):
if (url in urlstatsdict): urlstats = urlstatsdict[url] drill = process.DrillURL(urlstats) data = {'url': url, 'drill': drill, 'first_timestamp': recording_starttime, 'recordingstart': time.asctime(time.gmtime(recording_starttime)), 'source': source, 'filter_json': json.dumps(filter_condition...
'Renders detailed Appstats view of single request. Args: url: URL that is being drilled into. urlstatsdict: A dictionary with keys being URL paths, and values being URLStat objects. records_bytimestamp: A dictionary. Each key is the timestamp of an Appstats record (expressed in seconds). Each value is the corresponding...
def RenderDetail(self, url, urlstatsdict, records_bytimestamp, detail):
if (url in urlstatsdict): urlstats = urlstatsdict[url] revindex = ((- detail) - 1) ts = urlstats.urlrequestlist[revindex].timestamp record = records_bytimestamp[ts] ui.render_record(self.response, record)
'Render error message page. Args: errormessage: Error message to be rendered. source: Source of Appstats data. Either filename if being read from a file or MEMCACHE if being read from memcache.'
def RenderError(self, errormessage, source):
data = {'errormessage': errormessage, 'source': source} path = os.path.join(self.dirname, 'templates/error.html') self.response.out.write(template.render(path, data))